var bs = Object.defineProperty;
var ys = (l, e, t) => e in l ? bs(l, e, { enumerable: !0, configurable: !0, writable: !0, value: t }) : l[e] = t;
var Ut = (l, e, t) => (ys(l, typeof e != "symbol" ? e + "" : e, t), t);
import { d as Ts } from "./dice-box.es.js";
class Ms {
  /**
   * 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(e, t = !1, i, s) {
    this.initialize(e, t, i, s);
  }
  /**
   * 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(e, t = !1, i, s) {
    return this.mask = e, this.skipNextObservers = t, this.target = i, this.currentTarget = s, this;
  }
}
class Rs {
  /**
   * 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(e, t, i = null) {
    this.callback = e, this.mask = t, this.scope = i, this._willBeUnregistered = !1, this.unregisterOnNextCall = !1;
  }
}
class w {
  /**
   * 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(e, t) {
    const i = new w();
    return e.then((s) => {
      i.notifyObservers(s);
    }).catch((s) => {
      if (t)
        t.notifyObservers(s);
      else
        throw s;
    }), i;
  }
  /**
   * 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(e, t = !1) {
    this.notifyIfTriggered = t, this._observers = new Array(), this._numObserversMarkedAsDeleted = 0, this._hasNotified = !1, this._eventState = new Ms(0), e && (this._onObserverAdded = e);
  }
  /**
   * Create a new Observer with the specified callback
   * @param callback the callback that will be executed for that Observer
   * @param mask the mask used to filter observers
   * @param insertFirst if true the callback will be inserted at the first position, hence executed before the others ones. If false (default behavior) the callback will be inserted at the last position, executed after all the others already present.
   * @param scope optional scope for the callback to be called from
   * @param unregisterOnFirstCall defines if the observer as to be unregistered after the next notification
   * @returns the new observer created for the callback
   */
  add(e, t = -1, i = !1, s = null, r = !1) {
    if (!e)
      return null;
    const n = new Rs(e, t, s);
    return n.unregisterOnNextCall = r, i ? this._observers.unshift(n) : this._observers.push(n), this._onObserverAdded && this._onObserverAdded(n), this._hasNotified && this.notifyIfTriggered && this._lastNotifiedValue !== void 0 && this.notifyObserver(n, this._lastNotifiedValue), n;
  }
  /**
   * Create a new Observer with the specified callback and unregisters after the next notification
   * @param callback the callback that will be executed for that Observer
   * @returns the new observer created for the callback
   */
  addOnce(e) {
    return this.add(e, void 0, void 0, void 0, !0);
  }
  /**
   * 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(e) {
    return e && this._observers.indexOf(e) !== -1 ? (this._deferUnregister(e), !0) : !1;
  }
  /**
   * 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(e, t) {
    for (let i = 0; i < this._observers.length; i++) {
      const s = this._observers[i];
      if (!s._willBeUnregistered && s.callback === e && (!t || t === s.scope))
        return this._deferUnregister(s), !0;
    }
    return !1;
  }
  /**
   * @internal
   */
  _deferUnregister(e) {
    e._willBeUnregistered || (this._numObserversMarkedAsDeleted++, e.unregisterOnNextCall = !1, e._willBeUnregistered = !0, setTimeout(() => {
      this._remove(e);
    }, 0));
  }
  // This should only be called when not iterating over _observers to avoid callback skipping.
  // Removes an observer from the _observer Array.
  _remove(e, t = !0) {
    if (!e)
      return !1;
    const i = this._observers.indexOf(e);
    return i !== -1 ? (t && this._numObserversMarkedAsDeleted--, this._observers.splice(i, 1), !0) : !1;
  }
  /**
   * Moves the observable to the top of the observer list making it get called first when notified
   * @param observer the observer to move
   */
  makeObserverTopPriority(e) {
    this._remove(e, !1), this._observers.unshift(e);
  }
  /**
   * Moves the observable to the bottom of the observer list making it get called last when notified
   * @param observer the observer to move
   */
  makeObserverBottomPriority(e) {
    this._remove(e, !1), this._observers.push(e);
  }
  /**
   * 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(e, t = -1, i, s, r) {
    if (this.notifyIfTriggered && (this._hasNotified = !0, this._lastNotifiedValue = e), !this._observers.length)
      return !0;
    const n = this._eventState;
    n.mask = t, n.target = i, n.currentTarget = s, n.skipNextObservers = !1, n.lastReturnValue = e, n.userInfo = r;
    for (const a of this._observers)
      if (!a._willBeUnregistered && (a.mask & t && (a.unregisterOnNextCall && this._deferUnregister(a), a.scope ? n.lastReturnValue = a.callback.apply(a.scope, [e, n]) : n.lastReturnValue = a.callback(e, n)), n.skipNextObservers))
        return !1;
    return !0;
  }
  /**
   * 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(e, t, i = -1) {
    if (this.notifyIfTriggered && (this._hasNotified = !0, this._lastNotifiedValue = t), e._willBeUnregistered)
      return;
    const s = this._eventState;
    s.mask = i, s.skipNextObservers = !1, e.unregisterOnNextCall && this._deferUnregister(e), e.callback(t, s);
  }
  /**
   * 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() {
    this._observers.length = 0, 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 = !1, this._lastNotifiedValue = void 0;
  }
  /**
   * Clone the current observable
   * @returns a new observable
   */
  clone() {
    const e = new w();
    return e._observers = this._observers.slice(0), e;
  }
  /**
   * 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(e = -1) {
    for (const t of this._observers)
      if (t.mask & e || t.mask === e)
        return !0;
    return !1;
  }
}
function Ie() {
  return typeof window < "u";
}
function vi() {
  return typeof navigator < "u";
}
function Wt() {
  return typeof document < "u";
}
function Ii(l) {
  let e = "", t = l.firstChild;
  for (; t; )
    t.nodeType === 3 && (e += t.textContent), t = t.nextSibling;
  return e;
}
const Mi = {
  /**
   * Checks if the window object exists
   * @returns true if the window object exists
   */
  IsWindowObjectExist: Ie,
  /**
   * Checks if the navigator object exists
   * @returns true if the navigator object exists
   */
  IsNavigatorAvailable: vi,
  /**
   * Check if the document object exists
   * @returns true if the document object exists
   */
  IsDocumentAvailable: Wt,
  /**
   * Extracts text content from a DOM element hierarchy
   * @param element defines the root element
   * @returns a string
   */
  GetDOMTextContent: Ii
};
class S {
  static _CheckLimit(e, t) {
    let i = S._LogLimitOutputs[e];
    return i ? i.current++ : (i = { limit: t, current: 1 }, S._LogLimitOutputs[e] = i), i.current <= i.limit;
  }
  static _GenerateLimitMessage(e, t = 1) {
    var i;
    const s = S._LogLimitOutputs[e];
    if (!s || !S.MessageLimitReached)
      return;
    const r = this._Levels[t];
    s.current === s.limit && S[r.name](S.MessageLimitReached.replace(/%LIMIT%/g, "" + s.limit).replace(/%TYPE%/g, (i = r.name) !== null && i !== void 0 ? i : ""));
  }
  static _AddLogEntry(e) {
    S._LogCache = e + S._LogCache, S.OnNewCacheEntry && S.OnNewCacheEntry(e);
  }
  static _FormatMessage(e) {
    const t = (s) => s < 10 ? "0" + s : "" + s, i = /* @__PURE__ */ new Date();
    return "[" + t(i.getHours()) + ":" + t(i.getMinutes()) + ":" + t(i.getSeconds()) + "]: " + e;
  }
  // eslint-disable-next-line @typescript-eslint/no-unused-vars
  static _LogDisabled(e, t) {
  }
  static _LogEnabled(e = 1, t, i) {
    if (i !== void 0 && !S._CheckLimit(t, i))
      return;
    const s = S._FormatMessage(t), r = this._Levels[e];
    r.logFunc && r.logFunc("BJS - " + s);
    const n = `<div style='color:${r.color}'>${s}</div><br>`;
    S._AddLogEntry(n), S._GenerateLimitMessage(t, e);
  }
  /**
   * Gets current log cache (list of logs)
   */
  static get LogCache() {
    return S._LogCache;
  }
  /**
   * Clears the log cache
   */
  static ClearLogCache() {
    S._LogCache = "", S._LogLimitOutputs = {}, S.errorsCount = 0;
  }
  /**
   * Sets the current log level (MessageLogLevel / WarningLogLevel / ErrorLogLevel)
   */
  static set LogLevels(e) {
    S.Log = S._LogDisabled, S.Warn = S._LogDisabled, S.Error = S._LogDisabled, [S.MessageLogLevel, S.WarningLogLevel, S.ErrorLogLevel].forEach((t) => {
      if ((e & t) === t) {
        const i = this._Levels[t];
        S[i.name] = S._LogEnabled.bind(S, t);
      }
    });
  }
}
S.NoneLogLevel = 0;
S.MessageLogLevel = 1;
S.WarningLogLevel = 2;
S.ErrorLogLevel = 4;
S.AllLogLevel = 7;
S.MessageLimitReached = "Too many %TYPE%s (%LIMIT%), no more %TYPE%s will be reported for this message.";
S._LogCache = "";
S._LogLimitOutputs = {};
S._Levels = [
  {},
  { color: "white", logFunc: console.log, name: "Log" },
  { color: "orange", logFunc: console.warn, name: "Warn" },
  {},
  { color: "red", logFunc: console.error, name: "Error" }
];
S.errorsCount = 0;
S.Log = S._LogEnabled.bind(S, S.MessageLogLevel);
S.Warn = S._LogEnabled.bind(S, S.WarningLogLevel);
S.Error = S._LogEnabled.bind(S, S.ErrorLogLevel);
const Ni = (l, e) => !l || l.getClassName && l.getClassName() === "Mesh" ? null : l.getClassName && l.getClassName() === "SubMesh" ? l.clone(e) : l.clone ? l.clone() : null;
function As(l) {
  const e = [];
  do
    Object.getOwnPropertyNames(l).forEach(function(t) {
      e.indexOf(t) === -1 && e.push(t);
    });
  while (l = Object.getPrototypeOf(l));
  return e;
}
class Ci {
  /**
   * 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(e, t, i, s) {
    const r = As(e);
    for (const n of r) {
      if (n[0] === "_" && (!s || s.indexOf(n) === -1) || n.endsWith("Observable") || i && i.indexOf(n) !== -1)
        continue;
      const a = e[n], o = typeof a;
      if (o !== "function")
        try {
          if (o === "object")
            if (a instanceof Array) {
              if (t[n] = [], a.length > 0)
                if (typeof a[0] == "object")
                  for (let h = 0; h < a.length; h++) {
                    const c = Ni(a[h], t);
                    t[n].indexOf(c) === -1 && t[n].push(c);
                  }
                else
                  t[n] = a.slice(0);
            } else
              t[n] = Ni(a, t);
          else
            t[n] = a;
        } catch (h) {
          S.Warn(h.message);
        }
    }
  }
}
class Et {
  /**
   * Gets either window.performance.now() if supported or Date.now() else
   */
  static get Now() {
    return Mi.IsWindowObjectExist() && window.performance && window.performance.now ? window.performance.now() : Date.now();
  }
}
function Y(l) {
  return `${l} needs to be imported before as it contains a side-effect required by your code.`;
}
function xs() {
  return typeof _native < "u" && _native.XMLHttpRequest ? new _native.XMLHttpRequest() : new XMLHttpRequest();
}
class He {
  constructor() {
    this._xhr = xs(), this._requestURL = "";
  }
  _injectCustomRequestHeaders() {
    if (!this._shouldSkipRequestModifications(this._requestURL))
      for (const e in He.CustomRequestHeaders) {
        const t = He.CustomRequestHeaders[e];
        t && this._xhr.setRequestHeader(e, t);
      }
  }
  _shouldSkipRequestModifications(e) {
    return He.SkipRequestModificationForBabylonCDN && (e.includes("preview.babylonjs.com") || e.includes("cdn.babylonjs.com"));
  }
  /**
   * Gets or sets a function to be called when loading progress changes
   */
  get onprogress() {
    return this._xhr.onprogress;
  }
  set onprogress(e) {
    this._xhr.onprogress = e;
  }
  /**
   * 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(e) {
    this._xhr.responseType = e;
  }
  /**
   * Gets or sets the timeout value in milliseconds
   */
  get timeout() {
    return this._xhr.timeout;
  }
  set timeout(e) {
    this._xhr.timeout = e;
  }
  addEventListener(e, t, i) {
    this._xhr.addEventListener(e, t, i);
  }
  removeEventListener(e, t, i) {
    this._xhr.removeEventListener(e, t, i);
  }
  /**
   * 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(e) {
    He.CustomRequestHeaders && this._injectCustomRequestHeaders(), this._xhr.send(e);
  }
  /**
   * 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(e, t) {
    for (const i of He.CustomRequestModifiers) {
      if (this._shouldSkipRequestModifications(t))
        return;
      i(this._xhr, t);
    }
    return t = t.replace("file:http:", "http:"), t = t.replace("file:https:", "https:"), this._requestURL = t, this._xhr.open(e, t, !0);
  }
  /**
   * 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(e, t) {
    this._xhr.setRequestHeader(e, t);
  }
  /**
   * 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(e) {
    return this._xhr.getResponseHeader(e);
  }
}
He.CustomRequestHeaders = {};
He.CustomRequestModifiers = new Array();
He.SkipRequestModificationForBabylonCDN = !0;
class J {
  /**
   * Gets the latest created engine
   */
  static get LastCreatedEngine() {
    return this.Instances.length === 0 ? null : this.Instances[this.Instances.length - 1];
  }
  /**
   * Gets the latest created scene
   */
  static get LastCreatedScene() {
    return this._LastCreatedScene;
  }
}
J.Instances = new Array();
J.OnEnginesDisposedObservable = new w();
J._LastCreatedScene = null;
J.UseFallbackTexture = !0;
J.FallbackTexture = "";
class kt {
}
kt.FilesToLoad = {};
class Es {
  /**
   * 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(e = 3, t = 500) {
    return (i, s, r) => s.status !== 0 || r >= e || i.indexOf("file:") !== -1 ? -1 : Math.pow(2, r) * t;
  }
}
class Ot extends Error {
}
Ot._setPrototypeOf = Object.setPrototypeOf || ((l, e) => (l.__proto__ = e, l));
const vt = {
  // 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
};
class ct extends Ot {
  /**
   * 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(e, t, i) {
    super(e), this.errorCode = t, this.innerError = i, this.name = "RuntimeError", Ot._setPrototypeOf(this, ct.prototype);
  }
}
const vs = (l) => {
  const e = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";
  let t = "", i, s, r, n, a, o, h, c = 0;
  const u = ArrayBuffer.isView(l) ? new Uint8Array(l.buffer, l.byteOffset, l.byteLength) : new Uint8Array(l);
  for (; c < u.length; )
    i = u[c++], s = c < u.length ? u[c++] : Number.NaN, r = c < u.length ? u[c++] : Number.NaN, n = i >> 2, a = (i & 3) << 4 | s >> 4, o = (s & 15) << 2 | r >> 6, h = r & 63, isNaN(s) ? o = h = 64 : isNaN(r) && (h = 64), t += e.charAt(n) + e.charAt(a) + e.charAt(o) + e.charAt(h);
  return t;
}, ss = (l) => atob(l), Is = (l) => {
  const e = ss(l), t = e.length, i = new Uint8Array(new ArrayBuffer(t));
  for (let s = 0; s < t; s++)
    i[s] = e.charCodeAt(s);
  return i.buffer;
}, Cs = "attribute", Ps = "varying";
class Vt {
  constructor() {
    this.children = [];
  }
  // eslint-disable-next-line @typescript-eslint/no-unused-vars
  isValid(e) {
    return !0;
  }
  process(e, t) {
    var i, s, r, n, a, o;
    let h = "";
    if (this.line) {
      let c = this.line;
      const u = t.processor;
      if (u) {
        u.lineProcessor && (c = u.lineProcessor(c, t.isFragment, t.processingContext));
        const d = (s = (i = t.processor) === null || i === void 0 ? void 0 : i.attributeKeywordName) !== null && s !== void 0 ? s : Cs, g = t.isFragment && (!((r = t.processor) === null || r === void 0) && r.varyingFragmentKeywordName) ? (n = t.processor) === null || n === void 0 ? void 0 : n.varyingFragmentKeywordName : !t.isFragment && (!((a = t.processor) === null || a === void 0) && a.varyingVertexKeywordName) ? (o = t.processor) === null || o === void 0 ? void 0 : o.varyingVertexKeywordName : Ps;
        !t.isFragment && u.attributeProcessor && this.line.startsWith(d) ? c = u.attributeProcessor(this.line, e, t.processingContext) : u.varyingProcessor && this.line.startsWith(g) ? c = u.varyingProcessor(this.line, t.isFragment, e, t.processingContext) : u.uniformProcessor && u.uniformRegexp && u.uniformRegexp.test(this.line) ? t.lookForClosingBracketForUniformBuffer || (c = u.uniformProcessor(this.line, t.isFragment, e, t.processingContext)) : u.uniformBufferProcessor && u.uniformBufferRegexp && u.uniformBufferRegexp.test(this.line) ? t.lookForClosingBracketForUniformBuffer || (c = u.uniformBufferProcessor(this.line, t.isFragment, t.processingContext), t.lookForClosingBracketForUniformBuffer = !0) : u.textureProcessor && u.textureRegexp && u.textureRegexp.test(this.line) ? c = u.textureProcessor(this.line, t.isFragment, e, t.processingContext) : (u.uniformProcessor || u.uniformBufferProcessor) && this.line.startsWith("uniform") && !t.lookForClosingBracketForUniformBuffer && (/uniform\s+(?:(?:highp)?|(?:lowp)?)\s*(\S+)\s+(\S+)\s*;/.test(this.line) ? u.uniformProcessor && (c = u.uniformProcessor(this.line, t.isFragment, e, t.processingContext)) : u.uniformBufferProcessor && (c = u.uniformBufferProcessor(this.line, t.isFragment, t.processingContext), t.lookForClosingBracketForUniformBuffer = !0)), t.lookForClosingBracketForUniformBuffer && this.line.indexOf("}") !== -1 && (t.lookForClosingBracketForUniformBuffer = !1, u.endOfUniformBufferProcessor && (c = u.endOfUniformBufferProcessor(this.line, t.isFragment, t.processingContext)));
      }
      h += c + `\r
`;
    }
    return this.children.forEach((c) => {
      h += c.process(e, t);
    }), this.additionalDefineKey && (e[this.additionalDefineKey] = this.additionalDefineValue || "true"), h;
  }
}
class Ss {
  constructor() {
    this._lines = [];
  }
  get currentLine() {
    return this._lines[this.lineIndex];
  }
  get canRead() {
    return this.lineIndex < this._lines.length - 1;
  }
  set lines(e) {
    this._lines.length = 0;
    for (const t of e) {
      if (t[0] === "#") {
        this._lines.push(t);
        continue;
      }
      if (t.trim().startsWith("//")) {
        this._lines.push(t);
        continue;
      }
      const i = t.split(";");
      for (let s = 0; s < i.length; s++) {
        let r = i[s];
        r = r.trim(), r && this._lines.push(r + (s !== i.length - 1 ? ";" : ""));
      }
    }
  }
}
class mi extends Vt {
  process(e, t) {
    for (let i = 0; i < this.children.length; i++) {
      const s = this.children[i];
      if (s.isValid(e))
        return s.process(e, t);
    }
    return "";
  }
}
class Ds extends Vt {
  isValid(e) {
    return this.testExpression.isTrue(e);
  }
}
class we {
  // eslint-disable-next-line @typescript-eslint/no-unused-vars
  isTrue(e) {
    return !0;
  }
  static postfixToInfix(e) {
    const t = [];
    for (const i of e)
      if (we._OperatorPriority[i] === void 0)
        t.push(i);
      else {
        const s = t[t.length - 1], r = t[t.length - 2];
        t.length -= 2, t.push(`(${r}${i}${s})`);
      }
    return t[t.length - 1];
  }
  static infixToPostfix(e) {
    const t = [];
    let i = -1;
    const s = () => {
      h = h.trim(), h !== "" && (t.push(h), h = "");
    }, r = (c) => {
      i < we._Stack.length - 1 && (we._Stack[++i] = c);
    }, n = () => we._Stack[i], a = () => i === -1 ? "!!INVALID EXPRESSION!!" : we._Stack[i--];
    let o = 0, h = "";
    for (; o < e.length; ) {
      const c = e.charAt(o), u = o < e.length - 1 ? e.substr(o, 2) : "";
      if (c === "(")
        h = "", r(c);
      else if (c === ")") {
        for (s(); i !== -1 && n() !== "("; )
          t.push(a());
        a();
      } else if (we._OperatorPriority[u] > 1) {
        for (s(); i !== -1 && we._OperatorPriority[n()] >= we._OperatorPriority[u]; )
          t.push(a());
        r(u), o++;
      } else
        h += c;
      o++;
    }
    for (s(); i !== -1; )
      n() === "(" ? a() : t.push(a());
    return t;
  }
}
we._OperatorPriority = {
  ")": 0,
  "(": 1,
  "||": 2,
  "&&": 3
};
we._Stack = ["", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", ""];
class Zt extends we {
  constructor(e, t = !1) {
    super(), this.define = e, this.not = t;
  }
  isTrue(e) {
    let t = e[this.define] !== void 0;
    return this.not && (t = !t), t;
  }
}
class Fs extends we {
  isTrue(e) {
    return this.leftOperand.isTrue(e) || this.rightOperand.isTrue(e);
  }
}
class ws extends we {
  isTrue(e) {
    return this.leftOperand.isTrue(e) && this.rightOperand.isTrue(e);
  }
}
class Os extends we {
  constructor(e, t, i) {
    super(), this.define = e, this.operand = t, this.testValue = i;
  }
  isTrue(e) {
    let t = e[this.define];
    t === void 0 && (t = this.define);
    let i = !1;
    const s = parseInt(t), r = parseInt(this.testValue);
    switch (this.operand) {
      case ">":
        i = s > r;
        break;
      case "<":
        i = s < r;
        break;
      case "<=":
        i = s <= r;
        break;
      case ">=":
        i = s >= r;
        break;
      case "==":
        i = s === r;
        break;
    }
    return i;
  }
}
var Ce;
(function(l) {
  l[l.GLSL = 0] = "GLSL", l[l.WGSL = 1] = "WGSL";
})(Ce || (Ce = {}));
const Bs = /defined\s*?\((.+?)\)/g, bi = /defined\s*?\[(.+?)\]/g, ki = /#include\s?<(.+)>(\((.*)\))*(\[(.*)\])*/g;
class xt {
  static Initialize(e) {
    e.processor && e.processor.initializeShaders && e.processor.initializeShaders(e.processingContext);
  }
  static Process(e, t, i, s) {
    var r;
    !((r = t.processor) === null || r === void 0) && r.preProcessShaderCode && (e = t.processor.preProcessShaderCode(e, t.isFragment)), this._ProcessIncludes(e, t, (n) => {
      t.processCodeAfterIncludes && (n = t.processCodeAfterIncludes(t.isFragment ? "fragment" : "vertex", n));
      const a = this._ProcessShaderConversion(n, t, s);
      i(a, n);
    });
  }
  static PreProcess(e, t, i, s) {
    var r;
    !((r = t.processor) === null || r === void 0) && r.preProcessShaderCode && (e = t.processor.preProcessShaderCode(e, t.isFragment)), this._ProcessIncludes(e, t, (n) => {
      t.processCodeAfterIncludes && (n = t.processCodeAfterIncludes(t.isFragment ? "fragment" : "vertex", n));
      const a = this._ApplyPreProcessing(n, t, s);
      i(a, n);
    });
  }
  static Finalize(e, t, i) {
    return !i.processor || !i.processor.finalizeShaders ? { vertexCode: e, fragmentCode: t } : i.processor.finalizeShaders(e, t, i.processingContext);
  }
  static _ProcessPrecision(e, t) {
    var i;
    if (!((i = t.processor) === null || i === void 0) && i.noPrecision)
      return e;
    const s = t.shouldUseHighPrecisionShader;
    return e.indexOf("precision highp float") === -1 ? s ? e = `precision highp float;
` + e : e = `precision mediump float;
` + e : s || (e = e.replace("precision highp float", "precision mediump float")), e;
  }
  static _ExtractOperation(e) {
    const i = /defined\((.+)\)/.exec(e);
    if (i && i.length)
      return new Zt(i[1].trim(), e[0] === "!");
    const s = ["==", ">=", "<=", "<", ">"];
    let r = "", n = 0;
    for (r of s)
      if (n = e.indexOf(r), n > -1)
        break;
    if (n === -1)
      return new Zt(e);
    const a = e.substring(0, n).trim(), o = e.substring(n + r.length).trim();
    return new Os(a, r, o);
  }
  static _BuildSubExpression(e) {
    e = e.replace(Bs, "defined[$1]");
    const t = we.infixToPostfix(e), i = [];
    for (const r of t)
      if (r !== "||" && r !== "&&")
        i.push(r);
      else if (i.length >= 2) {
        let n = i[i.length - 1], a = i[i.length - 2];
        i.length -= 2;
        const o = r == "&&" ? new ws() : new Fs();
        typeof n == "string" && (n = n.replace(bi, "defined($1)")), typeof a == "string" && (a = a.replace(bi, "defined($1)")), o.leftOperand = typeof a == "string" ? this._ExtractOperation(a) : a, o.rightOperand = typeof n == "string" ? this._ExtractOperation(n) : n, i.push(o);
      }
    let s = i[i.length - 1];
    return typeof s == "string" && (s = s.replace(bi, "defined($1)")), typeof s == "string" ? this._ExtractOperation(s) : s;
  }
  static _BuildExpression(e, t) {
    const i = new Ds(), s = e.substring(0, t);
    let r = e.substring(t);
    return r = r.substring(0, (r.indexOf("//") + 1 || r.length + 1) - 1).trim(), s === "#ifdef" ? i.testExpression = new Zt(r) : s === "#ifndef" ? i.testExpression = new Zt(r, !0) : i.testExpression = this._BuildSubExpression(r), i;
  }
  static _MoveCursorWithinIf(e, t, i) {
    let s = e.currentLine;
    for (; this._MoveCursor(e, i); ) {
      s = e.currentLine;
      const r = s.substring(0, 5).toLowerCase();
      if (r === "#else") {
        const n = new Vt();
        t.children.push(n), this._MoveCursor(e, n);
        return;
      } else if (r === "#elif") {
        const n = this._BuildExpression(s, 5);
        t.children.push(n), i = n;
      }
    }
  }
  static _MoveCursor(e, t) {
    for (; e.canRead; ) {
      e.lineIndex++;
      const i = e.currentLine, r = /(#ifdef)|(#else)|(#elif)|(#endif)|(#ifndef)|(#if)/.exec(i);
      if (r && r.length)
        switch (r[0]) {
          case "#ifdef": {
            const a = new mi();
            t.children.push(a);
            const o = this._BuildExpression(i, 6);
            a.children.push(o), this._MoveCursorWithinIf(e, a, o);
            break;
          }
          case "#else":
          case "#elif":
            return !0;
          case "#endif":
            return !1;
          case "#ifndef": {
            const a = new mi();
            t.children.push(a);
            const o = this._BuildExpression(i, 7);
            a.children.push(o), this._MoveCursorWithinIf(e, a, o);
            break;
          }
          case "#if": {
            const a = new mi(), o = this._BuildExpression(i, 3);
            t.children.push(a), a.children.push(o), this._MoveCursorWithinIf(e, a, o);
            break;
          }
        }
      else {
        const n = new Vt();
        if (n.line = i, t.children.push(n), i[0] === "#" && i[1] === "d") {
          const a = i.replace(";", "").split(" ");
          n.additionalDefineKey = a[1], a.length === 3 && (n.additionalDefineValue = a[2]);
        }
      }
    }
    return !1;
  }
  static _EvaluatePreProcessors(e, t, i) {
    const s = new Vt(), r = new Ss();
    return r.lineIndex = -1, r.lines = e.split(`
`), this._MoveCursor(r, s), s.process(t, i);
  }
  static _PreparePreProcessors(e, t) {
    var i;
    const s = e.defines, r = {};
    for (const n of s) {
      const o = n.replace("#define", "").replace(";", "").trim().split(" ");
      r[o[0]] = o.length > 1 ? o[1] : "";
    }
    return ((i = e.processor) === null || i === void 0 ? void 0 : i.shaderLanguage) === Ce.GLSL && (r.GL_ES = "true"), r.__VERSION__ = e.version, r[e.platformName] = "true", t._getGlobalDefines(r), r;
  }
  static _ProcessShaderConversion(e, t, i) {
    let s = this._ProcessPrecision(e, t);
    if (!t.processor || t.processor.shaderLanguage === Ce.GLSL && s.indexOf("#version 3") !== -1 && (s = s.replace("#version 300 es", ""), !t.processor.parseGLES3))
      return s;
    const r = t.defines, n = this._PreparePreProcessors(t, i);
    return t.processor.preProcessor && (s = t.processor.preProcessor(s, r, t.isFragment, t.processingContext)), s = this._EvaluatePreProcessors(s, n, t), t.processor.postProcessor && (s = t.processor.postProcessor(s, r, t.isFragment, t.processingContext, i)), i._features.needShaderCodeInlining && (s = i.inlineShaderCode(s)), s;
  }
  static _ApplyPreProcessing(e, t, i) {
    var s, r;
    let n = e;
    const a = t.defines, o = this._PreparePreProcessors(t, i);
    return !((s = t.processor) === null || s === void 0) && s.preProcessor && (n = t.processor.preProcessor(n, a, t.isFragment, t.processingContext)), n = this._EvaluatePreProcessors(n, o, t), !((r = t.processor) === null || r === void 0) && r.postProcessor && (n = t.processor.postProcessor(n, a, t.isFragment, t.processingContext, i)), i._features.needShaderCodeInlining && (n = i.inlineShaderCode(n)), n;
  }
  static _ProcessIncludes(e, t, i) {
    let s = ki.exec(e), r = new String(e), n = !1;
    for (; s != null; ) {
      let a = s[1];
      if (a.indexOf("__decl__") !== -1 && (a = a.replace(/__decl__/, ""), t.supportsUniformBuffers && (a = a.replace(/Vertex/, "Ubo"), a = a.replace(/Fragment/, "Ubo")), a = a + "Declaration"), t.includesShadersStore[a]) {
        let o = t.includesShadersStore[a];
        if (s[2]) {
          const h = s[3].split(",");
          for (let c = 0; c < h.length; c += 2) {
            const u = new RegExp(h[c], "g"), d = h[c + 1];
            o = o.replace(u, d);
          }
        }
        if (s[4]) {
          const h = s[5];
          if (h.indexOf("..") !== -1) {
            const c = h.split(".."), u = parseInt(c[0]);
            let d = parseInt(c[1]), g = o.slice(0);
            o = "", isNaN(d) && (d = t.indexParameters[c[1]]);
            for (let f = u; f < d; f++)
              t.supportsUniformBuffers || (g = g.replace(/light\{X\}.(\w*)/g, (m, b) => b + "{X}")), o += g.replace(/\{X\}/g, f.toString()) + `
`;
          } else
            t.supportsUniformBuffers || (o = o.replace(/light\{X\}.(\w*)/g, (c, u) => u + "{X}")), o = o.replace(/\{X\}/g, h);
        }
        r = r.replace(s[0], o), n = n || o.indexOf("#include<") >= 0 || o.indexOf("#include <") >= 0;
      } else {
        const o = t.shadersRepository + "ShadersInclude/" + a + ".fx";
        xt._FileToolsLoadFile(o, (h) => {
          t.includesShadersStore[a] = h, this._ProcessIncludes(r, t, i);
        });
        return;
      }
      s = ki.exec(e);
    }
    n ? this._ProcessIncludes(r.toString(), t, i) : i(r);
  }
  /**
   * 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(e, t, i, s, r, n) {
    throw Y("FileTools");
  }
}
class ge {
  /**
   * Gets the shaders repository path for a given shader language
   * @param shaderLanguage the shader language
   * @returns the path to the shaders repository
   */
  static GetShadersRepository(e = Ce.GLSL) {
    return e === Ce.GLSL ? ge.ShadersRepository : ge.ShadersRepositoryWGSL;
  }
  /**
   * Gets the shaders store of a given shader language
   * @param shaderLanguage the shader language
   * @returns the shaders store
   */
  static GetShadersStore(e = Ce.GLSL) {
    return e === Ce.GLSL ? ge.ShadersStore : ge.ShadersStoreWGSL;
  }
  /**
   * Gets the include shaders store of a given shader language
   * @param shaderLanguage the shader language
   * @returns the include shaders store
   */
  static GetIncludesShadersStore(e = Ce.GLSL) {
    return e === Ce.GLSL ? ge.IncludesShadersStore : ge.IncludesShadersStoreWGSL;
  }
}
ge.ShadersRepository = "src/Shaders/";
ge.ShadersStore = {};
ge.IncludesShadersStore = {};
ge.ShadersRepositoryWGSL = "src/ShadersWGSL/";
ge.ShadersStoreWGSL = {};
ge.IncludesShadersStoreWGSL = {};
class Be {
  /**
   * Gets or sets the relative url used to load shaders if using the engine in non-minified mode
   */
  static get ShadersRepository() {
    return ge.ShadersRepository;
  }
  static set ShadersRepository(e) {
    ge.ShadersRepository = e;
  }
  /**
   * Observable that will be called when effect is bound.
   */
  get onBindObservable() {
    return this._onBindObservable || (this._onBindObservable = new w()), this._onBindObservable;
  }
  /**
   * 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)
   */
  constructor(e, t, i, s = null, r, n = null, a = null, o = null, h = null, c, u = "", d = Ce.GLSL) {
    var g, f, m;
    this.name = null, this.defines = "", this.onCompiled = null, this.onError = null, this.onBind = null, this.uniqueId = 0, this.onCompileObservable = new w(), this.onErrorObservable = new w(), this._onBindObservable = null, this._wasPreviouslyReady = !1, this._forceRebindOnNextCall = !1, this._wasPreviouslyUsingInstances = null, this._isDisposed = !1, this._bonesComputationForcedToCPU = !1, this._uniformBuffersNames = {}, this._multiTarget = !1, this._samplers = {}, this._isReady = !1, this._compilationError = "", this._allFallbacksProcessed = !1, this._uniforms = {}, this._key = "", this._fallbacks = null, this._vertexSourceCodeOverride = "", this._fragmentSourceCodeOverride = "", this._transformFeedbackVaryings = null, this._pipelineContext = null, this._vertexSourceCode = "", this._fragmentSourceCode = "", this._vertexSourceCodeBeforeMigration = "", this._fragmentSourceCodeBeforeMigration = "", this._rawVertexSourceCode = "", this._rawFragmentSourceCode = "", this.name = e, this._key = u;
    let b, T = null;
    if (t.attributes) {
      const D = t;
      if (this._engine = i, this._attributesNames = D.attributes, this._uniformsNames = D.uniformsNames.concat(D.samplers), this._samplerList = D.samplers.slice(), this.defines = D.defines, this.onError = D.onError, this.onCompiled = D.onCompiled, this._fallbacks = D.fallbacks, this._indexParameters = D.indexParameters, this._transformFeedbackVaryings = D.transformFeedbackVaryings || null, this._multiTarget = !!D.multiTarget, this._shaderLanguage = (g = D.shaderLanguage) !== null && g !== void 0 ? g : Ce.GLSL, D.uniformBuffersNames) {
        this._uniformBuffersNamesList = D.uniformBuffersNames.slice();
        for (let V = 0; V < D.uniformBuffersNames.length; V++)
          this._uniformBuffersNames[D.uniformBuffersNames[V]] = V;
      }
      T = (f = D.processFinalCode) !== null && f !== void 0 ? f : null, b = (m = D.processCodeAfterIncludes) !== null && m !== void 0 ? m : void 0;
    } else
      this._engine = r, this.defines = n ?? "", this._uniformsNames = i.concat(s), this._samplerList = s ? s.slice() : [], this._attributesNames = t, this._uniformBuffersNamesList = [], this._shaderLanguage = d, this.onError = h, this.onCompiled = o, this._indexParameters = c, this._fallbacks = a;
    this._attributeLocationByName = {}, this.uniqueId = Be._UniqueIdSeed++;
    let M, v;
    const A = Ie() ? this._engine.getHostDocument() : null;
    e.vertexSource ? M = "source:" + e.vertexSource : e.vertexElement ? (M = A ? A.getElementById(e.vertexElement) : null, M || (M = e.vertexElement)) : M = e.vertex || e, e.fragmentSource ? v = "source:" + e.fragmentSource : e.fragmentElement ? (v = A ? A.getElementById(e.fragmentElement) : null, v || (v = e.fragmentElement)) : v = e.fragment || e, this._processingContext = this._engine._getShaderProcessingContext(this._shaderLanguage);
    let E = {
      defines: this.defines.split(`
`),
      indexParameters: this._indexParameters,
      isFragment: !1,
      shouldUseHighPrecisionShader: this._engine._shouldUseHighPrecisionShader,
      processor: this._engine._getShaderProcessor(this._shaderLanguage),
      supportsUniformBuffers: this._engine.supportsUniformBuffers,
      shadersRepository: ge.GetShadersRepository(this._shaderLanguage),
      includesShadersStore: ge.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: b
    };
    const y = [void 0, void 0], x = () => {
      if (y[0] && y[1]) {
        E.isFragment = !0;
        const [D, V] = y;
        xt.Process(V, E, (W, ce) => {
          this._fragmentSourceCodeBeforeMigration = ce, T && (W = T("fragment", W));
          const ee = xt.Finalize(D, W, E);
          E = null, this._useFinalCode(ee.vertexCode, ee.fragmentCode, e);
        }, this._engine);
      }
    };
    this._loadShader(M, "Vertex", "", (D) => {
      xt.Initialize(E), xt.Process(D, E, (V, W) => {
        this._rawVertexSourceCode = D, this._vertexSourceCodeBeforeMigration = W, T && (V = T("vertex", V)), y[0] = V, x();
      }, this._engine);
    }), this._loadShader(v, "Fragment", "Pixel", (D) => {
      this._rawFragmentSourceCode = D, y[1] = D, x();
    });
  }
  _useFinalCode(e, t, i) {
    if (i) {
      const s = i.vertexElement || i.vertex || i.spectorName || i, r = i.fragmentElement || i.fragment || i.spectorName || i;
      this._vertexSourceCode = (this._shaderLanguage === Ce.WGSL ? "//" : "") + "#define SHADER_NAME vertex:" + s + `
` + e, this._fragmentSourceCode = (this._shaderLanguage === Ce.WGSL ? "//" : "") + "#define SHADER_NAME fragment:" + r + `
` + t;
    } else
      this._vertexSourceCode = e, this._fragmentSourceCode = t;
    this._prepareEffect();
  }
  /**
   * 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 !1;
    }
  }
  _isReadyInternal() {
    return this._isReady ? !0 : this._pipelineContext ? this._pipelineContext.isReady : !1;
  }
  /**
   * 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(e) {
    return this._attributes[e];
  }
  /**
   * Returns the attribute based on the name of the variable.
   * @param name of the attribute to look up.
   * @returns the attribute location.
   */
  getAttributeLocationByName(e) {
    return this._attributeLocationByName[e];
  }
  /**
   * 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(e) {
    return this._uniformsNames.indexOf(e);
  }
  /**
   * 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(e) {
    return this._uniforms[e];
  }
  /**
   * 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;
  }
  /**
   * Adds a callback to the onCompiled observable and call the callback immediately if already ready.
   * @param func The callback to be used.
   */
  executeWhenCompiled(e) {
    if (this.isReady()) {
      e(this);
      return;
    }
    this.onCompileObservable.add((t) => {
      e(t);
    }), (!this._pipelineContext || this._pipelineContext.isAsync) && setTimeout(() => {
      this._checkIsReady(null);
    }, 16);
  }
  _checkIsReady(e) {
    try {
      if (this._isReadyInternal())
        return;
    } catch (t) {
      this._processCompilationErrors(t, e);
      return;
    }
    this._isDisposed || setTimeout(() => {
      this._checkIsReady(e);
    }, 16);
  }
  _loadShader(e, t, i, s) {
    if (typeof HTMLElement < "u" && e instanceof HTMLElement) {
      const a = Ii(e);
      s(a);
      return;
    }
    if (e.substr(0, 7) === "source:") {
      s(e.substr(7));
      return;
    }
    if (e.substr(0, 7) === "base64:") {
      const a = window.atob(e.substr(7));
      s(a);
      return;
    }
    const r = ge.GetShadersStore(this._shaderLanguage);
    if (r[e + t + "Shader"]) {
      s(r[e + t + "Shader"]);
      return;
    }
    if (i && r[e + i + "Shader"]) {
      s(r[e + i + "Shader"]);
      return;
    }
    let n;
    e[0] === "." || e[0] === "/" || e.indexOf("http") > -1 ? n = e : n = ge.GetShadersRepository(this._shaderLanguage) + e, this._engine._loadFile(n + "." + t.toLowerCase() + ".fx", s);
  }
  /**
   * 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() {
    var e, t;
    return this._vertexSourceCodeOverride && this._fragmentSourceCodeOverride ? this._vertexSourceCodeOverride : (t = (e = this._pipelineContext) === null || e === void 0 ? void 0 : e._getVertexShaderCode()) !== null && t !== void 0 ? t : 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() {
    var e, t;
    return this._vertexSourceCodeOverride && this._fragmentSourceCodeOverride ? this._fragmentSourceCodeOverride : (t = (e = this._pipelineContext) === null || e === void 0 ? void 0 : e._getFragmentShaderCode()) !== null && t !== void 0 ? t : 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;
  }
  /**
   * 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(e, t, i, s) {
    this._isReady = !1, this._vertexSourceCodeOverride = e, this._fragmentSourceCodeOverride = t, this.onError = (r, n) => {
      s && s(n);
    }, this.onCompiled = () => {
      const r = this.getEngine().scenes;
      if (r)
        for (let n = 0; n < r.length; n++)
          r[n].markAllMaterialsAsDirty(63);
      this._pipelineContext._handlesSpectorRebuildCallback(i);
    }, this._fallbacks = null, this._prepareEffect();
  }
  /**
   * Prepares the effect
   * @internal
   */
  _prepareEffect() {
    const e = this._attributesNames, t = this.defines, i = this._pipelineContext;
    this._isReady = !1;
    try {
      const s = this._engine;
      this._pipelineContext = s.createPipelineContext(this._processingContext), this._pipelineContext._name = this._key;
      const r = this._rebuildProgram.bind(this);
      this._vertexSourceCodeOverride && this._fragmentSourceCodeOverride ? s._preparePipelineContext(this._pipelineContext, this._vertexSourceCodeOverride, this._fragmentSourceCodeOverride, !0, this._rawVertexSourceCode, this._rawFragmentSourceCode, r, null, this._transformFeedbackVaryings, this._key) : s._preparePipelineContext(this._pipelineContext, this._vertexSourceCode, this._fragmentSourceCode, !1, this._rawVertexSourceCode, this._rawFragmentSourceCode, r, t, this._transformFeedbackVaryings, this._key), s._executeWhenRenderingStateIsCompiled(this._pipelineContext, () => {
        if (this._attributes = [], this._pipelineContext._fillEffectInformation(this, this._uniformBuffersNames, this._uniformsNames, this._uniforms, this._samplerList, this._samplers, e, this._attributes), e)
          for (let n = 0; n < e.length; n++) {
            const a = e[n];
            this._attributeLocationByName[a] = this._attributes[n];
          }
        s.bindSamplers(this), this._compilationError = "", this._isReady = !0, this.onCompiled && this.onCompiled(this), this.onCompileObservable.notifyObservers(this), this.onCompileObservable.clear(), this._fallbacks && this._fallbacks.unBindMesh(), i && this.getEngine()._deletePipelineContext(i);
      }), this._pipelineContext.isAsync && this._checkIsReady(i);
    } catch (s) {
      this._processCompilationErrors(s, i);
    }
  }
  _getShaderCodeAndErrorLine(e, t, i) {
    const s = i ? /FRAGMENT SHADER ERROR: 0:(\d+?):/ : /VERTEX SHADER ERROR: 0:(\d+?):/;
    let r = null;
    if (t && e) {
      const n = t.match(s);
      if (n && n.length === 2) {
        const a = parseInt(n[1]), o = e.split(`
`, -1);
        o.length >= a && (r = `Offending line [${a}] in ${i ? "fragment" : "vertex"} code: ${o[a - 1]}`);
      }
    }
    return [e, r];
  }
  _processCompilationErrors(e, t = null) {
    var i, s, r;
    this._compilationError = e.message;
    const n = this._attributesNames, a = this._fallbacks;
    if (S.Error("Unable to compile effect:"), S.Error("Uniforms: " + this._uniformsNames.map(function(h) {
      return " " + h;
    })), S.Error("Attributes: " + n.map(function(h) {
      return " " + h;
    })), S.Error(`Defines:\r
` + this.defines), Be.LogShaderCodeOnCompilationError) {
      let h = null, c = null, u = null;
      !((i = this._pipelineContext) === null || i === void 0) && i._getVertexShaderCode() && ([u, h] = this._getShaderCodeAndErrorLine(this._pipelineContext._getVertexShaderCode(), this._compilationError, !1), u && (S.Error("Vertex code:"), S.Error(u))), !((s = this._pipelineContext) === null || s === void 0) && s._getFragmentShaderCode() && ([u, c] = this._getShaderCodeAndErrorLine((r = this._pipelineContext) === null || r === void 0 ? void 0 : r._getFragmentShaderCode(), this._compilationError, !0), u && (S.Error("Fragment code:"), S.Error(u))), h && S.Error(h), c && S.Error(c);
    }
    S.Error("Error: " + this._compilationError);
    const o = () => {
      this.onError && this.onError(this, this._compilationError), this.onErrorObservable.notifyObservers(this);
    };
    t && (this._pipelineContext = t, this._isReady = !0, o()), a ? (this._pipelineContext = null, a.hasMoreFallbacks ? (this._allFallbacksProcessed = !1, S.Error("Trying next fallback."), this.defines = a.reduce(this.defines, this), this._prepareEffect()) : (this._allFallbacksProcessed = !0, o(), this.onErrorObservable.clear(), this._fallbacks && this._fallbacks.unBindMesh())) : (this._allFallbacksProcessed = !0, t || o());
  }
  /**
   * 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(e, t) {
    this._engine._bindTexture(this._samplers[e], t, e);
  }
  /**
   * 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(e, t) {
    this._engine.setTexture(this._samplers[e], this._uniforms[e], t, e);
  }
  /**
   * Sets a depth stencil texture from a render target on the engine to be used in the shader.
   * @param channel Name of the sampler variable.
   * @param texture Texture to set.
   */
  setDepthStencilTexture(e, t) {
    this._engine.setDepthStencilTexture(this._samplers[e], this._uniforms[e], t, e);
  }
  /**
   * 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(e, t) {
    const i = e + "Ex";
    if (this._samplerList.indexOf(i + "0") === -1) {
      const s = this._samplerList.indexOf(e);
      for (let n = 1; n < t.length; n++) {
        const a = i + (n - 1).toString();
        this._samplerList.splice(s + n, 0, a);
      }
      let r = 0;
      for (const n of this._samplerList)
        this._samplers[n] = r, r += 1;
    }
    this._engine.setTextureArray(this._samplers[e], this._uniforms[e], t, e);
  }
  /**
   * Sets a texture to be the input of the specified post process. (To use the output, pass in the next post process in the pipeline)
   * @param channel Name of the sampler variable.
   * @param postProcess Post process to get the input texture from.
   */
  setTextureFromPostProcess(e, t) {
    this._engine.setTextureFromPostProcess(this._samplers[e], t, e);
  }
  /**
   * (Warning! setTextureFromPostProcessOutput may be desired instead)
   * Sets the input texture of the passed in post process to be input of this effect. (To use the output of the passed in post process use setTextureFromPostProcessOutput)
   * @param channel Name of the sampler variable.
   * @param postProcess Post process to get the output texture from.
   */
  setTextureFromPostProcessOutput(e, t) {
    this._engine.setTextureFromPostProcessOutput(this._samplers[e], t, e);
  }
  /**
   * Binds a buffer to a uniform.
   * @param buffer Buffer to bind.
   * @param name Name of the uniform variable to bind to.
   */
  bindUniformBuffer(e, t) {
    const i = this._uniformBuffersNames[t];
    i === void 0 || Be._BaseCache[i] === e && this._engine._features.useUBOBindingCache || (Be._BaseCache[i] = e, this._engine.bindUniformBufferBase(e, i, t));
  }
  /**
   * Binds block to a uniform.
   * @param blockName Name of the block to bind.
   * @param index Index to bind.
   */
  bindUniformBlock(e, t) {
    this._engine.bindUniformBlock(this._pipelineContext, e, t);
  }
  /**
   * Sets an integer value on a uniform variable.
   * @param uniformName Name of the variable.
   * @param value Value to be set.
   * @returns this effect.
   */
  setInt(e, t) {
    return this._pipelineContext.setInt(e, t), 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(e, t, i) {
    return this._pipelineContext.setInt2(e, t, i), 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(e, t, i, s) {
    return this._pipelineContext.setInt3(e, t, i, s), 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(e, t, i, s, r) {
    return this._pipelineContext.setInt4(e, t, i, s, r), 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(e, t) {
    return this._pipelineContext.setIntArray(e, t), 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(e, t) {
    return this._pipelineContext.setIntArray2(e, t), 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(e, t) {
    return this._pipelineContext.setIntArray3(e, t), 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(e, t) {
    return this._pipelineContext.setIntArray4(e, t), 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(e, t) {
    return this._pipelineContext.setInt(e, t), 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(e, t, i) {
    return this._pipelineContext.setInt2(e, t, i), 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(e, t, i, s) {
    return this._pipelineContext.setInt3(e, t, i, s), 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(e, t, i, s, r) {
    return this._pipelineContext.setInt4(e, t, i, s, r), 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(e, t) {
    return this._pipelineContext.setUIntArray(e, t), 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(e, t) {
    return this._pipelineContext.setUIntArray2(e, t), 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(e, t) {
    return this._pipelineContext.setUIntArray3(e, t), 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(e, t) {
    return this._pipelineContext.setUIntArray4(e, t), 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(e, t) {
    return this._pipelineContext.setArray(e, t), 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(e, t) {
    return this._pipelineContext.setArray2(e, t), 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(e, t) {
    return this._pipelineContext.setArray3(e, t), 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(e, t) {
    return this._pipelineContext.setArray4(e, t), this;
  }
  /**
   * Sets an array on a uniform variable.
   * @param uniformName Name of the variable.
   * @param array array to be set.
   * @returns this effect.
   */
  setArray(e, t) {
    return this._pipelineContext.setArray(e, t), 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(e, t) {
    return this._pipelineContext.setArray2(e, t), 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(e, t) {
    return this._pipelineContext.setArray3(e, t), 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(e, t) {
    return this._pipelineContext.setArray4(e, t), this;
  }
  /**
   * Sets matrices on a uniform variable.
   * @param uniformName Name of the variable.
   * @param matrices matrices to be set.
   * @returns this effect.
   */
  setMatrices(e, t) {
    return this._pipelineContext.setMatrices(e, t), this;
  }
  /**
   * Sets matrix on a uniform variable.
   * @param uniformName Name of the variable.
   * @param matrix matrix to be set.
   * @returns this effect.
   */
  setMatrix(e, t) {
    return this._pipelineContext.setMatrix(e, t), 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(e, t) {
    return this._pipelineContext.setMatrix3x3(e, t), 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(e, t) {
    return this._pipelineContext.setMatrix2x2(e, t), this;
  }
  /**
   * Sets a float on a uniform variable.
   * @param uniformName Name of the variable.
   * @param value value to be set.
   * @returns this effect.
   */
  setFloat(e, t) {
    return this._pipelineContext.setFloat(e, t), this;
  }
  /**
   * Sets a boolean on a uniform variable.
   * @param uniformName Name of the variable.
   * @param bool value to be set.
   * @returns this effect.
   */
  setBool(e, t) {
    return this._pipelineContext.setInt(e, t ? 1 : 0), this;
  }
  /**
   * Sets a Vector2 on a uniform variable.
   * @param uniformName Name of the variable.
   * @param vector2 vector2 to be set.
   * @returns this effect.
   */
  setVector2(e, t) {
    return this._pipelineContext.setVector2(e, t), 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(e, t, i) {
    return this._pipelineContext.setFloat2(e, t, i), this;
  }
  /**
   * Sets a Vector3 on a uniform variable.
   * @param uniformName Name of the variable.
   * @param vector3 Value to be set.
   * @returns this effect.
   */
  setVector3(e, t) {
    return this._pipelineContext.setVector3(e, t), 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(e, t, i, s) {
    return this._pipelineContext.setFloat3(e, t, i, s), this;
  }
  /**
   * Sets a Vector4 on a uniform variable.
   * @param uniformName Name of the variable.
   * @param vector4 Value to be set.
   * @returns this effect.
   */
  setVector4(e, t) {
    return this._pipelineContext.setVector4(e, t), this;
  }
  /**
   * Sets a Quaternion on a uniform variable.
   * @param uniformName Name of the variable.
   * @param quaternion Value to be set.
   * @returns this effect.
   */
  setQuaternion(e, t) {
    return this._pipelineContext.setQuaternion(e, t), 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(e, t, i, s, r) {
    return this._pipelineContext.setFloat4(e, t, i, s, r), this;
  }
  /**
   * Sets a Color3 on a uniform variable.
   * @param uniformName Name of the variable.
   * @param color3 Value to be set.
   * @returns this effect.
   */
  setColor3(e, t) {
    return this._pipelineContext.setColor3(e, t), 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(e, t, i) {
    return this._pipelineContext.setColor4(e, t, i), 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(e, t) {
    return this._pipelineContext.setDirectColor4(e, t), this;
  }
  /**
   * Release all associated resources.
   **/
  dispose() {
    this._pipelineContext && this._pipelineContext.dispose(), this._engine._releaseEffect(this), this._isDisposed = !0;
  }
  /**
   * 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(e, t, i, s = Ce.GLSL) {
    t && (ge.GetShadersStore(s)[`${e}PixelShader`] = t), i && (ge.GetShadersStore(s)[`${e}VertexShader`] = i);
  }
  /**
   * Resets the cache of effects.
   */
  static ResetCache() {
    Be._BaseCache = {};
  }
}
Be.LogShaderCodeOnCompilationError = !0;
Be._UniqueIdSeed = 0;
Be._BaseCache = {};
Be.ShadersStore = ge.ShadersStore;
Be.IncludesShadersStore = ge.IncludesShadersStore;
class Ls {
  /**
   * Initializes the state.
   * @param reset
   */
  constructor(e = !0) {
    this._isDepthTestDirty = !1, this._isDepthMaskDirty = !1, this._isDepthFuncDirty = !1, this._isCullFaceDirty = !1, this._isCullDirty = !1, this._isZOffsetDirty = !1, this._isFrontFaceDirty = !1, e && 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(e) {
    this._zOffset !== e && (this._zOffset = e, this._isZOffsetDirty = !0);
  }
  get zOffsetUnits() {
    return this._zOffsetUnits;
  }
  set zOffsetUnits(e) {
    this._zOffsetUnits !== e && (this._zOffsetUnits = e, this._isZOffsetDirty = !0);
  }
  get cullFace() {
    return this._cullFace;
  }
  set cullFace(e) {
    this._cullFace !== e && (this._cullFace = e, this._isCullFaceDirty = !0);
  }
  get cull() {
    return this._cull;
  }
  set cull(e) {
    this._cull !== e && (this._cull = e, this._isCullDirty = !0);
  }
  get depthFunc() {
    return this._depthFunc;
  }
  set depthFunc(e) {
    this._depthFunc !== e && (this._depthFunc = e, this._isDepthFuncDirty = !0);
  }
  get depthMask() {
    return this._depthMask;
  }
  set depthMask(e) {
    this._depthMask !== e && (this._depthMask = e, this._isDepthMaskDirty = !0);
  }
  get depthTest() {
    return this._depthTest;
  }
  set depthTest(e) {
    this._depthTest !== e && (this._depthTest = e, this._isDepthTestDirty = !0);
  }
  get frontFace() {
    return this._frontFace;
  }
  set frontFace(e) {
    this._frontFace !== e && (this._frontFace = e, this._isFrontFaceDirty = !0);
  }
  reset() {
    this._depthMask = !0, this._depthTest = !0, this._depthFunc = null, this._cullFace = null, this._cull = null, this._zOffset = 0, this._zOffsetUnits = 0, this._frontFace = null, this._isDepthTestDirty = !0, this._isDepthMaskDirty = !0, this._isDepthFuncDirty = !1, this._isCullFaceDirty = !1, this._isCullDirty = !1, this._isZOffsetDirty = !0, this._isFrontFaceDirty = !1;
  }
  apply(e) {
    this.isDirty && (this._isCullDirty && (this.cull ? e.enable(e.CULL_FACE) : e.disable(e.CULL_FACE), this._isCullDirty = !1), this._isCullFaceDirty && (e.cullFace(this.cullFace), this._isCullFaceDirty = !1), this._isDepthMaskDirty && (e.depthMask(this.depthMask), this._isDepthMaskDirty = !1), this._isDepthTestDirty && (this.depthTest ? e.enable(e.DEPTH_TEST) : e.disable(e.DEPTH_TEST), this._isDepthTestDirty = !1), this._isDepthFuncDirty && (e.depthFunc(this.depthFunc), this._isDepthFuncDirty = !1), this._isZOffsetDirty && (this.zOffset || this.zOffsetUnits ? (e.enable(e.POLYGON_OFFSET_FILL), e.polygonOffset(this.zOffset, this.zOffsetUnits)) : e.disable(e.POLYGON_OFFSET_FILL), this._isZOffsetDirty = !1), this._isFrontFaceDirty && (e.frontFace(this.frontFace), this._isFrontFaceDirty = !1));
  }
}
class lt {
  constructor() {
    this.reset();
  }
  reset() {
    this.enabled = !1, this.mask = 255, this.func = lt.ALWAYS, this.funcRef = 1, this.funcMask = 255, this.opStencilFail = lt.KEEP, this.opDepthFail = lt.KEEP, this.opStencilDepthPass = lt.REPLACE;
  }
  get stencilFunc() {
    return this.func;
  }
  set stencilFunc(e) {
    this.func = e;
  }
  get stencilFuncRef() {
    return this.funcRef;
  }
  set stencilFuncRef(e) {
    this.funcRef = e;
  }
  get stencilFuncMask() {
    return this.funcMask;
  }
  set stencilFuncMask(e) {
    this.funcMask = e;
  }
  get stencilOpStencilFail() {
    return this.opStencilFail;
  }
  set stencilOpStencilFail(e) {
    this.opStencilFail = e;
  }
  get stencilOpDepthFail() {
    return this.opDepthFail;
  }
  set stencilOpDepthFail(e) {
    this.opDepthFail = e;
  }
  get stencilOpStencilDepthPass() {
    return this.opStencilDepthPass;
  }
  set stencilOpStencilDepthPass(e) {
    this.opStencilDepthPass = e;
  }
  get stencilMask() {
    return this.mask;
  }
  set stencilMask(e) {
    this.mask = e;
  }
  get stencilTest() {
    return this.enabled;
  }
  set stencilTest(e) {
    this.enabled = e;
  }
}
lt.ALWAYS = 519;
lt.KEEP = 7680;
lt.REPLACE = 7681;
class Us {
  /**
   * Initializes the state.
   */
  constructor() {
    this._blendFunctionParameters = new Array(4), this._blendEquationParameters = new Array(2), this._blendConstants = new Array(4), this._isBlendConstantsDirty = !1, this._alphaBlend = !1, this._isAlphaBlendDirty = !1, this._isBlendFunctionParametersDirty = !1, this._isBlendEquationParametersDirty = !1, this.reset();
  }
  get isDirty() {
    return this._isAlphaBlendDirty || this._isBlendFunctionParametersDirty || this._isBlendEquationParametersDirty;
  }
  get alphaBlend() {
    return this._alphaBlend;
  }
  set alphaBlend(e) {
    this._alphaBlend !== e && (this._alphaBlend = e, this._isAlphaBlendDirty = !0);
  }
  setAlphaBlendConstants(e, t, i, s) {
    this._blendConstants[0] === e && this._blendConstants[1] === t && this._blendConstants[2] === i && this._blendConstants[3] === s || (this._blendConstants[0] = e, this._blendConstants[1] = t, this._blendConstants[2] = i, this._blendConstants[3] = s, this._isBlendConstantsDirty = !0);
  }
  setAlphaBlendFunctionParameters(e, t, i, s) {
    this._blendFunctionParameters[0] === e && this._blendFunctionParameters[1] === t && this._blendFunctionParameters[2] === i && this._blendFunctionParameters[3] === s || (this._blendFunctionParameters[0] = e, this._blendFunctionParameters[1] = t, this._blendFunctionParameters[2] = i, this._blendFunctionParameters[3] = s, this._isBlendFunctionParametersDirty = !0);
  }
  setAlphaEquationParameters(e, t) {
    this._blendEquationParameters[0] === e && this._blendEquationParameters[1] === t || (this._blendEquationParameters[0] = e, this._blendEquationParameters[1] = t, this._isBlendEquationParametersDirty = !0);
  }
  reset() {
    this._alphaBlend = !1, this._blendFunctionParameters[0] = null, this._blendFunctionParameters[1] = null, this._blendFunctionParameters[2] = null, this._blendFunctionParameters[3] = null, this._blendEquationParameters[0] = null, this._blendEquationParameters[1] = null, this._blendConstants[0] = null, this._blendConstants[1] = null, this._blendConstants[2] = null, this._blendConstants[3] = null, this._isAlphaBlendDirty = !0, this._isBlendFunctionParametersDirty = !1, this._isBlendEquationParametersDirty = !1, this._isBlendConstantsDirty = !1;
  }
  apply(e) {
    this.isDirty && (this._isAlphaBlendDirty && (this._alphaBlend ? e.enable(e.BLEND) : e.disable(e.BLEND), this._isAlphaBlendDirty = !1), this._isBlendFunctionParametersDirty && (e.blendFuncSeparate(this._blendFunctionParameters[0], this._blendFunctionParameters[1], this._blendFunctionParameters[2], this._blendFunctionParameters[3]), this._isBlendFunctionParametersDirty = !1), this._isBlendEquationParametersDirty && (e.blendEquationSeparate(this._blendEquationParameters[0], this._blendEquationParameters[1]), this._isBlendEquationParametersDirty = !1), this._isBlendConstantsDirty && (e.blendColor(this._blendConstants[0], this._blendConstants[1], this._blendConstants[2], this._blendConstants[3]), this._isBlendConstantsDirty = !1));
  }
}
class Ns {
  /**
   * | Value | Type               | Description |
   * | ----- | ------------------ | ----------- |
   * | 0     | CLAMP_ADDRESSMODE  |             |
   * | 1     | WRAP_ADDRESSMODE   |             |
   * | 2     | MIRROR_ADDRESSMODE |             |
   */
  get wrapU() {
    return this._cachedWrapU;
  }
  set wrapU(e) {
    this._cachedWrapU = e;
  }
  /**
   * | Value | Type               | Description |
   * | ----- | ------------------ | ----------- |
   * | 0     | CLAMP_ADDRESSMODE  |             |
   * | 1     | WRAP_ADDRESSMODE   |             |
   * | 2     | MIRROR_ADDRESSMODE |             |
   */
  get wrapV() {
    return this._cachedWrapV;
  }
  set wrapV(e) {
    this._cachedWrapV = e;
  }
  /**
   * | Value | Type               | Description |
   * | ----- | ------------------ | ----------- |
   * | 0     | CLAMP_ADDRESSMODE  |             |
   * | 1     | WRAP_ADDRESSMODE   |             |
   * | 2     | MIRROR_ADDRESSMODE |             |
   */
  get wrapR() {
    return this._cachedWrapR;
  }
  set wrapR(e) {
    this._cachedWrapR = e;
  }
  /**
   * 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(e) {
    this._cachedAnisotropicFilteringLevel = e;
  }
  /**
   * Gets or sets the comparison function (513, 514, etc). Set 0 to not use a comparison function
   */
  get comparisonFunction() {
    return this._comparisonFunction;
  }
  set comparisonFunction(e) {
    this._comparisonFunction = e;
  }
  /**
   * 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(e) {
    this._useMipMaps = e;
  }
  /**
   * Creates a Sampler instance
   */
  constructor() {
    this.samplingMode = -1, this._useMipMaps = !0, 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(e = 1, t = 1, i = 1, s = 1, r = 2, n = 0) {
    return this._cachedWrapU = e, this._cachedWrapV = t, this._cachedWrapR = i, this._cachedAnisotropicFilteringLevel = s, this.samplingMode = r, this._comparisonFunction = n, 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(e) {
    return this._cachedWrapU === e._cachedWrapU && this._cachedWrapV === e._cachedWrapV && this._cachedWrapR === e._cachedWrapR && this._cachedAnisotropicFilteringLevel === e._cachedAnisotropicFilteringLevel && this.samplingMode === e.samplingMode && this._comparisonFunction === e._comparisonFunction && this._useMipMaps === e._useMipMaps;
  }
}
var De;
(function(l) {
  l[l.Unknown = 0] = "Unknown", l[l.Url = 1] = "Url", l[l.Temp = 2] = "Temp", l[l.Raw = 3] = "Raw", l[l.Dynamic = 4] = "Dynamic", l[l.RenderTarget = 5] = "RenderTarget", l[l.MultiRenderTarget = 6] = "MultiRenderTarget", l[l.Cube = 7] = "Cube", l[l.CubeRaw = 8] = "CubeRaw", l[l.CubePrefiltered = 9] = "CubePrefiltered", l[l.Raw3D = 10] = "Raw3D", l[l.Raw2DArray = 11] = "Raw2DArray", l[l.DepthStencil = 12] = "DepthStencil", l[l.CubeRawRGBD = 13] = "CubeRawRGBD", l[l.Depth = 14] = "Depth";
})(De || (De = {}));
class It extends Ns {
  /**
   * 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(e) {
    this.generateMipMaps = e;
  }
  /** Gets the unique id of the internal texture */
  get uniqueId() {
    return this._uniqueId;
  }
  /** @internal */
  _setUniqueId(e) {
    this._uniqueId = e;
  }
  /**
   * 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(e, t, i = !1) {
    super(), this.isReady = !1, this.isCube = !1, this.is3D = !1, this.is2DArray = !1, this.isMultiview = !1, this.url = "", this.generateMipMaps = !1, this.samples = 0, this.type = -1, this.format = -1, this.onLoadedObservable = new w(), this.onErrorObservable = new w(), this.onRebuildCallback = null, this.width = 0, this.height = 0, this.depth = 0, this.baseWidth = 0, this.baseHeight = 0, this.baseDepth = 0, this.invertY = !1, this._invertVScale = !1, this._associatedChannel = -1, this._source = De.Unknown, 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 = !1, this._compression = null, this._sphericalPolynomial = null, this._sphericalPolynomialPromise = null, this._sphericalPolynomialComputed = !1, this._lodGenerationScale = 0, this._lodGenerationOffset = 0, this._useSRGBBuffer = !1, this._lodTextureHigh = null, this._lodTextureMid = null, this._lodTextureLow = null, this._isRGBD = !1, this._linearSpecularLOD = !1, this._irradianceTexture = null, this._hardwareTexture = null, this._maxLodLevel = null, this._references = 1, this._gammaSpace = null, this._engine = e, this._source = t, this._uniqueId = It._Counter++, i || (this._hardwareTexture = e._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(e, t, i = 1) {
    this._engine.updateTextureDimensions(this, e, t, i), this.width = e, this.height = t, this.depth = i, this.baseWidth = e, this.baseHeight = t, this.baseDepth = i, this._size = e * t * i;
  }
  /** @internal */
  _rebuild() {
    var e;
    if (this.isReady = !1, this._cachedCoordinatesMode = null, this._cachedWrapU = null, this._cachedWrapV = null, this._cachedWrapR = null, this._cachedAnisotropicFilteringLevel = null, this.onRebuildCallback) {
      const i = this.onRebuildCallback(this), s = (r) => {
        r._swapAndDie(this, !1), this.isReady = i.isReady;
      };
      i.isAsync ? i.proxy.then(s) : s(i.proxy);
      return;
    }
    let t;
    switch (this.source) {
      case De.Temp:
        break;
      case De.Url:
        t = this._engine.createTexture(
          (e = this._originalUrl) !== null && e !== void 0 ? e : 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.
          (i) => {
            i._swapAndDie(this, !1), this.isReady = !0;
          },
          null,
          this._buffer,
          void 0,
          this.format,
          this._extension,
          void 0,
          void 0,
          void 0,
          this._useSRGBBuffer
        );
        return;
      case De.Raw:
        t = this._engine.createRawTexture(this._bufferView, this.baseWidth, this.baseHeight, this.format, this.generateMipMaps, this.invertY, this.samplingMode, this._compression, this.type, void 0, this._useSRGBBuffer), t._swapAndDie(this, !1), this.isReady = !0;
        break;
      case De.Raw3D:
        t = this._engine.createRawTexture3D(this._bufferView, this.baseWidth, this.baseHeight, this.baseDepth, this.format, this.generateMipMaps, this.invertY, this.samplingMode, this._compression, this.type), t._swapAndDie(this, !1), this.isReady = !0;
        break;
      case De.Raw2DArray:
        t = this._engine.createRawTexture2DArray(this._bufferView, this.baseWidth, this.baseHeight, this.baseDepth, this.format, this.generateMipMaps, this.invertY, this.samplingMode, this._compression, this.type), t._swapAndDie(this, !1), this.isReady = !0;
        break;
      case De.Dynamic:
        t = this._engine.createDynamicTexture(this.baseWidth, this.baseHeight, this.generateMipMaps, this.samplingMode), t._swapAndDie(this, !1), this._engine.updateDynamicTexture(this, this._engine.getRenderingCanvas(), this.invertY, void 0, void 0, !0);
        break;
      case De.Cube:
        t = this._engine.createCubeTexture(this.url, null, this._files, !this.generateMipMaps, () => {
          t._swapAndDie(this, !1), this.isReady = !0;
        }, null, this.format, this._extension, !1, 0, 0, null, void 0, this._useSRGBBuffer);
        return;
      case De.CubeRaw:
        t = this._engine.createRawCubeTexture(this._bufferViewArray, this.width, this.format, this.type, this.generateMipMaps, this.invertY, this.samplingMode, this._compression), t._swapAndDie(this, !1), this.isReady = !0;
        break;
      case De.CubeRawRGBD:
        return;
      case De.CubePrefiltered:
        t = this._engine.createPrefilteredCubeTexture(this.url, null, this._lodGenerationScale, this._lodGenerationOffset, (i) => {
          i && i._swapAndDie(this, !1), this.isReady = !0;
        }, null, this.format, this._extension), t._sphericalPolynomial = this._sphericalPolynomial;
        return;
    }
  }
  /**
   * @internal
   */
  _swapAndDie(e, t = !0) {
    var i;
    (i = this._hardwareTexture) === null || i === void 0 || i.setUsage(e._source, this.generateMipMaps, this.isCube, this.width, this.height), e._hardwareTexture = this._hardwareTexture, t && (e._isRGBD = this._isRGBD), this._lodTextureHigh && (e._lodTextureHigh && e._lodTextureHigh.dispose(), e._lodTextureHigh = this._lodTextureHigh), this._lodTextureMid && (e._lodTextureMid && e._lodTextureMid.dispose(), e._lodTextureMid = this._lodTextureMid), this._lodTextureLow && (e._lodTextureLow && e._lodTextureLow.dispose(), e._lodTextureLow = this._lodTextureLow), this._irradianceTexture && (e._irradianceTexture && e._irradianceTexture.dispose(), e._irradianceTexture = this._irradianceTexture);
    const s = this._engine.getLoadedTexturesCache();
    let r = s.indexOf(this);
    r !== -1 && s.splice(r, 1), r = s.indexOf(e), r === -1 && s.push(e);
  }
  /**
   * Dispose the current allocated resources
   */
  dispose() {
    this._references--, this.onLoadedObservable.clear(), this.onErrorObservable.clear(), this._references === 0 && (this._engine._releaseTexture(this), this._hardwareTexture = null);
  }
}
It._Counter = 0;
class ks {
  constructor() {
    this.shaderLanguage = Ce.GLSL;
  }
  postProcessor(e, t, i, s, r) {
    if (!r.getCaps().drawBuffersExtension) {
      const n = /#extension.+GL_EXT_draw_buffers.+(enable|require)/g;
      e = e.replace(n, "");
    }
    return e;
  }
}
class Vs {
  constructor() {
    this.shaderLanguage = Ce.GLSL;
  }
  attributeProcessor(e) {
    return e.replace("attribute", "in");
  }
  varyingProcessor(e, t) {
    return e.replace("varying", t ? "in" : "out");
  }
  postProcessor(e, t, i) {
    const s = e.search(/#extension.+GL_EXT_draw_buffers.+require/) !== -1, r = /#extension.+(GL_OVR_multiview2|GL_OES_standard_derivatives|GL_EXT_shader_texture_lod|GL_EXT_frag_depth|GL_EXT_draw_buffers).+(enable|require)/g;
    if (e = e.replace(r, ""), e = e.replace(/texture2D\s*\(/g, "texture("), i)
      e = e.replace(/texture2DLodEXT\s*\(/g, "textureLod("), e = e.replace(/textureCubeLodEXT\s*\(/g, "textureLod("), e = e.replace(/textureCube\s*\(/g, "texture("), e = e.replace(/gl_FragDepthEXT/g, "gl_FragDepth"), e = e.replace(/gl_FragColor/g, "glFragColor"), e = e.replace(/gl_FragData/g, "glFragData"), e = e.replace(/void\s+?main\s*\(/g, (s ? "" : `layout(location = 0) out vec4 glFragColor;
`) + "void main(");
    else if (t.indexOf("#define MULTIVIEW") !== -1)
      return `#extension GL_OVR_multiview2 : require
layout (num_views = 2) in;
` + e;
    return e;
  }
}
class Kt {
  /**
   * Gets the underlying buffer
   */
  get underlyingResource() {
    return null;
  }
  /**
   * Constructs the buffer
   */
  constructor() {
    this.references = 0, this.capacity = 0, this.is32Bits = !1, this.uniqueId = Kt._Counter++;
  }
}
Kt._Counter = 0;
class Gt extends Kt {
  constructor(e) {
    super(), this._buffer = e;
  }
  get underlyingResource() {
    return this._buffer;
  }
}
class Ws {
  constructor() {
    this._valueCache = {}, this.vertexCompilationError = null, this.fragmentCompilationError = null, this.programLinkError = null, this.programValidationError = null;
  }
  get isAsync() {
    return this.isParallelCompiled;
  }
  get isReady() {
    return this.program ? this.isParallelCompiled ? this.engine._isRenderingStateCompiled(this) : !0 : !1;
  }
  _handlesSpectorRebuildCallback(e) {
    e && this.program && e(this.program);
  }
  _fillEffectInformation(e, t, i, s, r, n, a, o) {
    const h = this.engine;
    if (h.supportsUniformBuffers)
      for (const d in t)
        e.bindUniformBlock(d, t[d]);
    this.engine.getUniforms(this, i).forEach((d, g) => {
      s[i[g]] = d;
    }), this._uniforms = s;
    let u;
    for (u = 0; u < r.length; u++)
      e.getUniform(r[u]) == null && (r.splice(u, 1), u--);
    r.forEach((d, g) => {
      n[d] = g;
    });
    for (const d of h.getAttributes(this, a))
      o.push(d);
  }
  /**
   * Release all associated resources.
   **/
  dispose() {
    this._uniforms = {};
  }
  /**
   * @internal
   */
  _cacheMatrix(e, t) {
    const i = this._valueCache[e], s = t.updateFlag;
    return i !== void 0 && i === s ? !1 : (this._valueCache[e] = s, !0);
  }
  /**
   * @internal
   */
  _cacheFloat2(e, t, i) {
    let s = this._valueCache[e];
    if (!s || s.length !== 2)
      return s = [t, i], this._valueCache[e] = s, !0;
    let r = !1;
    return s[0] !== t && (s[0] = t, r = !0), s[1] !== i && (s[1] = i, r = !0), r;
  }
  /**
   * @internal
   */
  _cacheFloat3(e, t, i, s) {
    let r = this._valueCache[e];
    if (!r || r.length !== 3)
      return r = [t, i, s], this._valueCache[e] = r, !0;
    let n = !1;
    return r[0] !== t && (r[0] = t, n = !0), r[1] !== i && (r[1] = i, n = !0), r[2] !== s && (r[2] = s, n = !0), n;
  }
  /**
   * @internal
   */
  _cacheFloat4(e, t, i, s, r) {
    let n = this._valueCache[e];
    if (!n || n.length !== 4)
      return n = [t, i, s, r], this._valueCache[e] = n, !0;
    let a = !1;
    return n[0] !== t && (n[0] = t, a = !0), n[1] !== i && (n[1] = i, a = !0), n[2] !== s && (n[2] = s, a = !0), n[3] !== r && (n[3] = r, a = !0), a;
  }
  /**
   * Sets an integer value on a uniform variable.
   * @param uniformName Name of the variable.
   * @param value Value to be set.
   */
  setInt(e, t) {
    const i = this._valueCache[e];
    i !== void 0 && i === t || this.engine.setInt(this._uniforms[e], t) && (this._valueCache[e] = t);
  }
  /**
   * 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(e, t, i) {
    this._cacheFloat2(e, t, i) && (this.engine.setInt2(this._uniforms[e], t, i) || (this._valueCache[e] = 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(e, t, i, s) {
    this._cacheFloat3(e, t, i, s) && (this.engine.setInt3(this._uniforms[e], t, i, s) || (this._valueCache[e] = 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(e, t, i, s, r) {
    this._cacheFloat4(e, t, i, s, r) && (this.engine.setInt4(this._uniforms[e], t, i, s, r) || (this._valueCache[e] = null));
  }
  /**
   * Sets an int array on a uniform variable.
   * @param uniformName Name of the variable.
   * @param array array to be set.
   */
  setIntArray(e, t) {
    this._valueCache[e] = null, this.engine.setIntArray(this._uniforms[e], t);
  }
  /**
   * 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(e, t) {
    this._valueCache[e] = null, this.engine.setIntArray2(this._uniforms[e], t);
  }
  /**
   * 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(e, t) {
    this._valueCache[e] = null, this.engine.setIntArray3(this._uniforms[e], t);
  }
  /**
   * 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(e, t) {
    this._valueCache[e] = null, this.engine.setIntArray4(this._uniforms[e], t);
  }
  /**
   * Sets an unsigned integer value on a uniform variable.
   * @param uniformName Name of the variable.
   * @param value Value to be set.
   */
  setUInt(e, t) {
    const i = this._valueCache[e];
    i !== void 0 && i === t || this.engine.setUInt(this._uniforms[e], t) && (this._valueCache[e] = t);
  }
  /**
   * 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(e, t, i) {
    this._cacheFloat2(e, t, i) && (this.engine.setUInt2(this._uniforms[e], t, i) || (this._valueCache[e] = 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(e, t, i, s) {
    this._cacheFloat3(e, t, i, s) && (this.engine.setUInt3(this._uniforms[e], t, i, s) || (this._valueCache[e] = 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(e, t, i, s, r) {
    this._cacheFloat4(e, t, i, s, r) && (this.engine.setUInt4(this._uniforms[e], t, i, s, r) || (this._valueCache[e] = null));
  }
  /**
   * Sets an unsigned int array on a uniform variable.
   * @param uniformName Name of the variable.
   * @param array array to be set.
   */
  setUIntArray(e, t) {
    this._valueCache[e] = null, this.engine.setUIntArray(this._uniforms[e], t);
  }
  /**
   * 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(e, t) {
    this._valueCache[e] = null, this.engine.setUIntArray2(this._uniforms[e], t);
  }
  /**
   * 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(e, t) {
    this._valueCache[e] = null, this.engine.setUIntArray3(this._uniforms[e], t);
  }
  /**
   * 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(e, t) {
    this._valueCache[e] = null, this.engine.setUIntArray4(this._uniforms[e], t);
  }
  /**
   * Sets an array on a uniform variable.
   * @param uniformName Name of the variable.
   * @param array array to be set.
   */
  setArray(e, t) {
    this._valueCache[e] = null, this.engine.setArray(this._uniforms[e], t);
  }
  /**
   * 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(e, t) {
    this._valueCache[e] = null, this.engine.setArray2(this._uniforms[e], t);
  }
  /**
   * 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(e, t) {
    this._valueCache[e] = null, this.engine.setArray3(this._uniforms[e], t);
  }
  /**
   * 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(e, t) {
    this._valueCache[e] = null, this.engine.setArray4(this._uniforms[e], t);
  }
  /**
   * Sets matrices on a uniform variable.
   * @param uniformName Name of the variable.
   * @param matrices matrices to be set.
   */
  setMatrices(e, t) {
    t && (this._valueCache[e] = null, this.engine.setMatrices(this._uniforms[e], t));
  }
  /**
   * Sets matrix on a uniform variable.
   * @param uniformName Name of the variable.
   * @param matrix matrix to be set.
   */
  setMatrix(e, t) {
    this._cacheMatrix(e, t) && (this.engine.setMatrices(this._uniforms[e], t.toArray()) || (this._valueCache[e] = 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(e, t) {
    this._valueCache[e] = null, this.engine.setMatrix3x3(this._uniforms[e], t);
  }
  /**
   * 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(e, t) {
    this._valueCache[e] = null, this.engine.setMatrix2x2(this._uniforms[e], t);
  }
  /**
   * Sets a float on a uniform variable.
   * @param uniformName Name of the variable.
   * @param value value to be set.
   * @returns this effect.
   */
  setFloat(e, t) {
    const i = this._valueCache[e];
    i !== void 0 && i === t || this.engine.setFloat(this._uniforms[e], t) && (this._valueCache[e] = t);
  }
  /**
   * Sets a Vector2 on a uniform variable.
   * @param uniformName Name of the variable.
   * @param vector2 vector2 to be set.
   */
  setVector2(e, t) {
    this._cacheFloat2(e, t.x, t.y) && (this.engine.setFloat2(this._uniforms[e], t.x, t.y) || (this._valueCache[e] = 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(e, t, i) {
    this._cacheFloat2(e, t, i) && (this.engine.setFloat2(this._uniforms[e], t, i) || (this._valueCache[e] = null));
  }
  /**
   * Sets a Vector3 on a uniform variable.
   * @param uniformName Name of the variable.
   * @param vector3 Value to be set.
   */
  setVector3(e, t) {
    this._cacheFloat3(e, t.x, t.y, t.z) && (this.engine.setFloat3(this._uniforms[e], t.x, t.y, t.z) || (this._valueCache[e] = 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(e, t, i, s) {
    this._cacheFloat3(e, t, i, s) && (this.engine.setFloat3(this._uniforms[e], t, i, s) || (this._valueCache[e] = null));
  }
  /**
   * Sets a Vector4 on a uniform variable.
   * @param uniformName Name of the variable.
   * @param vector4 Value to be set.
   */
  setVector4(e, t) {
    this._cacheFloat4(e, t.x, t.y, t.z, t.w) && (this.engine.setFloat4(this._uniforms[e], t.x, t.y, t.z, t.w) || (this._valueCache[e] = null));
  }
  /**
   * Sets a Quaternion on a uniform variable.
   * @param uniformName Name of the variable.
   * @param quaternion Value to be set.
   */
  setQuaternion(e, t) {
    this._cacheFloat4(e, t.x, t.y, t.z, t.w) && (this.engine.setFloat4(this._uniforms[e], t.x, t.y, t.z, t.w) || (this._valueCache[e] = 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.
   * @returns this effect.
   */
  setFloat4(e, t, i, s, r) {
    this._cacheFloat4(e, t, i, s, r) && (this.engine.setFloat4(this._uniforms[e], t, i, s, r) || (this._valueCache[e] = null));
  }
  /**
   * Sets a Color3 on a uniform variable.
   * @param uniformName Name of the variable.
   * @param color3 Value to be set.
   */
  setColor3(e, t) {
    this._cacheFloat3(e, t.r, t.g, t.b) && (this.engine.setFloat3(this._uniforms[e], t.r, t.g, t.b) || (this._valueCache[e] = 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(e, t, i) {
    this._cacheFloat4(e, t.r, t.g, t.b, i) && (this.engine.setFloat4(this._uniforms[e], t.r, t.g, t.b, i) || (this._valueCache[e] = 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(e, t) {
    this._cacheFloat4(e, t.r, t.g, t.b, t.a) && (this.engine.setFloat4(this._uniforms[e], t.r, t.g, t.b, t.a) || (this._valueCache[e] = null));
  }
  _getVertexShaderCode() {
    return this.vertexShader ? this.engine._getShaderSource(this.vertexShader) : null;
  }
  _getFragmentShaderCode() {
    return this.fragmentShader ? this.engine._getShaderSource(this.fragmentShader) : null;
  }
}
class be {
  /**
   * @internal
   */
  static SetMatrixPrecision(e) {
    if (be.MatrixTrackPrecisionChange = !1, e && !be.MatrixUse64Bits && be.MatrixTrackedMatrices)
      for (let t = 0; t < be.MatrixTrackedMatrices.length; ++t) {
        const i = be.MatrixTrackedMatrices[t], s = i._m;
        i._m = new Array(16);
        for (let r = 0; r < 16; ++r)
          i._m[r] = s[r];
      }
    be.MatrixUse64Bits = e, be.MatrixCurrentType = be.MatrixUse64Bits ? Array : Float32Array, be.MatrixTrackedMatrices = null;
  }
}
be.MatrixUse64Bits = !1;
be.MatrixTrackPrecisionChange = !0;
be.MatrixCurrentType = Float32Array;
be.MatrixTrackedMatrices = [];
class rs {
  get underlyingResource() {
    return this._webGLTexture;
  }
  constructor(e = null, t) {
    if (this._MSAARenderBuffers = null, this._context = t, !e && (e = t.createTexture(), !e))
      throw new Error("Unable to create webGL texture");
    this.set(e);
  }
  setUsage() {
  }
  set(e) {
    this._webGLTexture = e;
  }
  reset() {
    this._webGLTexture = null, this._MSAARenderBuffers = null;
  }
  addMSAARenderBuffer(e) {
    this._MSAARenderBuffers || (this._MSAARenderBuffers = []), this._MSAARenderBuffers.push(e);
  }
  releaseMSAARenderBuffers() {
    if (this._MSAARenderBuffers) {
      for (const e of this._MSAARenderBuffers)
        this._context.deleteRenderbuffer(e);
      this._MSAARenderBuffers = null;
    }
  }
  release() {
    this.releaseMSAARenderBuffers(), this._webGLTexture && this._context.deleteTexture(this._webGLTexture), this.reset();
  }
}
class Pi {
  static IsWrapper(e) {
    return e.getPipelineContext === void 0;
  }
  static GetEffect(e) {
    return e.getPipelineContext === void 0 ? e.effect : e;
  }
  constructor(e, t = !0) {
    this.effect = null, this.defines = null, this.drawContext = e.createDrawContext(), t && (this.materialContext = e.createMaterialContext());
  }
  setEffect(e, t, i = !0) {
    var s;
    this.effect = e, t !== void 0 && (this.defines = t), i && ((s = this.drawContext) === null || s === void 0 || s.reset());
  }
  dispose() {
    var e;
    (e = this.drawContext) === null || e === void 0 || e.dispose();
  }
}
class Gs {
  get isDirty() {
    return this._isStencilTestDirty || this._isStencilMaskDirty || this._isStencilFuncDirty || this._isStencilOpDirty;
  }
  get func() {
    return this._func;
  }
  set func(e) {
    this._func !== e && (this._func = e, this._isStencilFuncDirty = !0);
  }
  get funcRef() {
    return this._funcRef;
  }
  set funcRef(e) {
    this._funcRef !== e && (this._funcRef = e, this._isStencilFuncDirty = !0);
  }
  get funcMask() {
    return this._funcMask;
  }
  set funcMask(e) {
    this._funcMask !== e && (this._funcMask = e, this._isStencilFuncDirty = !0);
  }
  get opStencilFail() {
    return this._opStencilFail;
  }
  set opStencilFail(e) {
    this._opStencilFail !== e && (this._opStencilFail = e, this._isStencilOpDirty = !0);
  }
  get opDepthFail() {
    return this._opDepthFail;
  }
  set opDepthFail(e) {
    this._opDepthFail !== e && (this._opDepthFail = e, this._isStencilOpDirty = !0);
  }
  get opStencilDepthPass() {
    return this._opStencilDepthPass;
  }
  set opStencilDepthPass(e) {
    this._opStencilDepthPass !== e && (this._opStencilDepthPass = e, this._isStencilOpDirty = !0);
  }
  get mask() {
    return this._mask;
  }
  set mask(e) {
    this._mask !== e && (this._mask = e, this._isStencilMaskDirty = !0);
  }
  get enabled() {
    return this._enabled;
  }
  set enabled(e) {
    this._enabled !== e && (this._enabled = e, this._isStencilTestDirty = !0);
  }
  constructor(e = !0) {
    this._isStencilTestDirty = !1, this._isStencilMaskDirty = !1, this._isStencilFuncDirty = !1, this._isStencilOpDirty = !1, this.useStencilGlobalOnly = !1, e && this.reset();
  }
  reset() {
    var e;
    this.stencilMaterial = void 0, (e = this.stencilGlobal) === null || e === void 0 || e.reset(), this._isStencilTestDirty = !0, this._isStencilMaskDirty = !0, this._isStencilFuncDirty = !0, this._isStencilOpDirty = !0;
  }
  apply(e) {
    var t;
    if (!e)
      return;
    const i = !this.useStencilGlobalOnly && !!(!((t = this.stencilMaterial) === null || t === void 0) && t.enabled);
    this.enabled = i ? this.stencilMaterial.enabled : this.stencilGlobal.enabled, this.func = i ? this.stencilMaterial.func : this.stencilGlobal.func, this.funcRef = i ? this.stencilMaterial.funcRef : this.stencilGlobal.funcRef, this.funcMask = i ? this.stencilMaterial.funcMask : this.stencilGlobal.funcMask, this.opStencilFail = i ? this.stencilMaterial.opStencilFail : this.stencilGlobal.opStencilFail, this.opDepthFail = i ? this.stencilMaterial.opDepthFail : this.stencilGlobal.opDepthFail, this.opStencilDepthPass = i ? this.stencilMaterial.opStencilDepthPass : this.stencilGlobal.opStencilDepthPass, this.mask = i ? this.stencilMaterial.mask : this.stencilGlobal.mask, this.isDirty && (this._isStencilTestDirty && (this.enabled ? e.enable(e.STENCIL_TEST) : e.disable(e.STENCIL_TEST), this._isStencilTestDirty = !1), this._isStencilMaskDirty && (e.stencilMask(this.mask), this._isStencilMaskDirty = !1), this._isStencilFuncDirty && (e.stencilFunc(this.func, this.funcRef, this.funcMask), this._isStencilFuncDirty = !1), this._isStencilOpDirty && (e.stencilOp(this.opStencilFail, this.opDepthFail, this.opStencilDepthPass), this._isStencilOpDirty = !1));
  }
}
class zs {
}
class se {
  /**
   * Returns the current npm package of the sdk
   */
  // Not mixed with Version for tooling purpose.
  static get NpmPackage() {
    return "babylonjs@5.57.1";
  }
  /**
   * Returns the current version of the framework
   */
  static get Version() {
    return "5.57.1";
  }
  /**
   * Returns a string describing the current engine
   */
  get description() {
    let e = this.name + this.webGLVersion;
    return this._caps.parallelShaderCompile && (e += " - Parallel shader compilation"), e;
  }
  /**
   * Gets or sets the name of the engine
   */
  get name() {
    return this._name;
  }
  set name(e) {
    this._name = e;
  }
  /**
   * Returns the version of the engine
   */
  get version() {
    return this._webGLVersion;
  }
  get isDisposed() {
    return this._isDisposed;
  }
  /**
   * Gets or sets the relative url used to load shaders if using the engine in non-minified mode
   */
  static get ShadersRepository() {
    return Be.ShadersRepository;
  }
  static set ShadersRepository(e) {
    Be.ShadersRepository = e;
  }
  /**
   * @internal
   */
  _getShaderProcessor(e) {
    return this._shaderProcessor;
  }
  /**
   * 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(e) {
    e !== this._useReverseDepthBuffer && (this._useReverseDepthBuffer = e, e ? this._depthCullingState.depthFunc = 518 : this._depthCullingState.depthFunc = 515);
  }
  /**
   * Gets the current frame id
   */
  get frameId() {
    return this._frameId;
  }
  /**
   * 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 the options used for engine creation
   * @returns EngineOptions object
   */
  getCreationOptions() {
    return this._creationOptions;
  }
  /** @internal */
  get _shouldUseHighPrecisionShader() {
    return !!(this._caps.highPrecisionShaderSupported && this._highPrecisionShadersAllowed);
  }
  /**
   * 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;
  }
  /**
   * Gets the list of current active render loop functions
   * @returns an array with the current render loop functions
   */
  get activeRenderLoops() {
    return this._activeRenderLoops;
  }
  /**
   * 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(e) {
    this._doNotHandleContextLost = e;
  }
  get _supportsHardwareTextureRescaling() {
    return !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(e) {
    this._framebufferDimensionsObject = e;
  }
  /**
   * Gets the current viewport
   */
  get currentViewport() {
    return this._cachedViewport;
  }
  /**
   * Gets the default empty texture
   */
  get emptyTexture() {
    return this._emptyTexture || (this._emptyTexture = this.createRawTexture(new Uint8Array(4), 1, 1, 5, !1, !1, 1)), this._emptyTexture;
  }
  /**
   * Gets the default empty 3D texture
   */
  get emptyTexture3D() {
    return this._emptyTexture3D || (this._emptyTexture3D = this.createRawTexture3D(new Uint8Array(4), 1, 1, 1, 5, !1, !1, 1)), this._emptyTexture3D;
  }
  /**
   * Gets the default empty 2D array texture
   */
  get emptyTexture2DArray() {
    return this._emptyTexture2DArray || (this._emptyTexture2DArray = this.createRawTexture2DArray(new Uint8Array(4), 1, 1, 1, 5, !1, !1, 1)), this._emptyTexture2DArray;
  }
  /**
   * Gets the default empty cube texture
   */
  get emptyCubeTexture() {
    if (!this._emptyCubeTexture) {
      const e = new Uint8Array(4), t = [e, e, e, e, e, e];
      this._emptyCubeTexture = this.createRawCubeTexture(t, 1, 5, 0, !1, !1, 1);
    }
    return this._emptyCubeTexture;
  }
  /**
   * Gets a boolean indicating if the engine runs in WebGPU or not.
   */
  get isWebGPU() {
    return this._isWebGPU;
  }
  /**
   * Gets the shader platform name used by the effects.
   */
  get shaderPlatformName() {
    return this._shaderPlatformName;
  }
  /**
   * 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 !1;
  }
  set snapshotRendering(e) {
  }
  /**
   * Gets or sets the snapshot rendering mode
   */
  get snapshotRenderingMode() {
    return this._snapshotRenderingMode;
  }
  set snapshotRenderingMode(e) {
    this._snapshotRenderingMode = e;
  }
  /**
   * Creates a new snapshot at the next frame using the current snapshotRenderingMode
   */
  snapshotRenderingReset() {
    this.snapshotRendering = !1;
  }
  static _CreateCanvas(e, t) {
    if (typeof document > "u")
      return new OffscreenCanvas(e, t);
    const i = document.createElement("canvas");
    return i.width = e, i.height = t, i;
  }
  /**
   * Create a canvas. This method is overridden by other engines
   * @param width width
   * @param height height
   * @returns ICanvas interface
   */
  createCanvas(e, t) {
    return se._CreateCanvas(e, t);
  }
  /**
   * Create an image to use with canvas
   * @returns IImage interface
   */
  createCanvasImage() {
    return document.createElement("img");
  }
  /**
   * 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(e, t, i, s) {
    var r, n, a, o, h, c, u, d, g, f, m;
    this._name = "WebGL", this._isDisposed = !1, this.forcePOTTextures = !1, this.isFullscreen = !1, this.cullBackFaces = null, this.renderEvenInBackground = !0, this.preventCacheWipeBetweenFrames = !1, this.validateShaderPrograms = !1, this._useReverseDepthBuffer = !1, this.isNDCHalfZRange = !1, this.hasOriginBottomLeft = !0, this.disableUniformBuffers = !1, this.onDisposeObservable = new w(), this._frameId = 0, this._uniformBuffers = new Array(), this._storageBuffers = new Array(), this._webGLVersion = 1, this._windowIsBackground = !1, this._highPrecisionShadersAllowed = !0, this._badOS = !1, this._badDesktopOS = !1, this._renderingQueueLaunched = !1, this._activeRenderLoops = new Array(), this.onContextLostObservable = new w(), this.onContextRestoredObservable = new w(), this._contextWasLost = !1, this._doNotHandleContextLost = !1, this.disableVertexArrayObjects = !1, this._colorWrite = !0, this._colorWriteChanged = !0, this._depthCullingState = new Ls(), this._stencilStateComposer = new Gs(), this._stencilState = new lt(), this._alphaState = new Us(), this._alphaMode = 1, this._alphaEquation = 0, this._internalTexturesCache = new Array(), this._renderTargetWrapperCache = new Array(), this._activeChannel = 0, this._currentTextureChannel = -1, this._boundTexturesCache = {}, this._compiledEffects = {}, this._vertexAttribArraysEnabled = [], this._uintIndicesCurrentlySet = !1, this._currentBoundBuffer = new Array(), this._currentFramebuffer = null, this._dummyFramebuffer = null, this._currentBufferPointers = new Array(), this._currentInstanceLocations = new Array(), this._currentInstanceBuffers = new Array(), this._vaoRecordInProgress = !1, this._mustWipeVertexAttributes = !1, this._nextFreeTextureSlots = new Array(), this._maxSimultaneousTextures = 0, this._maxMSAASamplesOverride = null, this._activeRequests = new Array(), this.adaptToDeviceRatio = !1, this._lastDevicePixelRatio = 1, this._transformTextureUrl = null, this.hostInformation = {
      isMobile: !1
    }, this.premultipliedAlpha = !0, this.onBeforeTextureInitObservable = new w(), this._isWebGPU = !1, this._snapshotRenderingMode = 0, this._viewportCached = { x: 0, y: 0, z: 0, w: 0 }, this._unpackFlipYCached = null, this.enableUnpackFlipYCached = !0, this._boundUniforms = {}, this.startTime = Et.Now;
    let b = null;
    i = i || {}, this._creationOptions = i, this.adaptToDeviceRatio = s ?? !1, this._stencilStateComposer.stencilGlobal = this._stencilState, be.SetMatrixPrecision(!!i.useHighPrecisionMatrix), i.antialias = t ?? i.antialias, i.deterministicLockstep = (r = i.deterministicLockstep) !== null && r !== void 0 ? r : !1, i.lockstepMaxSteps = (n = i.lockstepMaxSteps) !== null && n !== void 0 ? n : 4, i.timeStep = (a = i.timeStep) !== null && a !== void 0 ? a : 1 / 60, i.audioEngine = (o = i.audioEngine) !== null && o !== void 0 ? o : !0, i.stencil = (h = i.stencil) !== null && h !== void 0 ? h : !0, this._audioContext = (u = (c = i.audioEngineOptions) === null || c === void 0 ? void 0 : c.audioContext) !== null && u !== void 0 ? u : null, this._audioDestination = (g = (d = i.audioEngineOptions) === null || d === void 0 ? void 0 : d.audioDestination) !== null && g !== void 0 ? g : null, this.premultipliedAlpha = (f = i.premultipliedAlpha) !== null && f !== void 0 ? f : !0, this.useExactSrgbConversions = (m = i.useExactSrgbConversions) !== null && m !== void 0 ? m : !1, this._doNotHandleContextLost = !!i.doNotHandleContextLost, this._isStencilEnable = !!i.stencil, s = s || i.adaptToDeviceRatio || !1;
    const T = Ie() && window.devicePixelRatio || 1, M = i.limitDeviceRatio || T;
    if (this._hardwareScalingLevel = s ? 1 / Math.min(M, T) : 1, this._lastDevicePixelRatio = T, !e)
      return;
    if (e.getContext) {
      if (b = e, this._renderingCanvas = b, i.preserveDrawingBuffer === void 0 && (i.preserveDrawingBuffer = !1), i.xrCompatible === void 0 && (i.xrCompatible = !0), navigator && navigator.userAgent) {
        this._setupMobileChecks();
        const A = navigator.userAgent;
        for (const E of se.ExceptionList) {
          const y = E.key, x = E.targets;
          if (new RegExp(y).test(A)) {
            if (E.capture && E.captureConstraint) {
              const V = E.capture, W = E.captureConstraint, ee = new RegExp(V).exec(A);
              if (ee && ee.length > 0 && parseInt(ee[ee.length - 1]) >= W)
                continue;
            }
            for (const V of x)
              switch (V) {
                case "uniformBuffer":
                  this.disableUniformBuffers = !0;
                  break;
                case "vao":
                  this.disableVertexArrayObjects = !0;
                  break;
                case "antialias":
                  i.antialias = !1;
                  break;
                case "maxMSAASamples":
                  this._maxMSAASamplesOverride = 1;
                  break;
              }
          }
        }
      }
      if (this._doNotHandleContextLost || (this._onContextLost = (A) => {
        A.preventDefault(), this._contextWasLost = !0, S.Warn("WebGL context lost."), this.onContextLostObservable.notifyObservers(this);
      }, this._onContextRestored = () => {
        this._restoreEngineAfterContextLost(this._initGLContext.bind(this));
      }, b.addEventListener("webglcontextlost", this._onContextLost, !1), b.addEventListener("webglcontextrestored", this._onContextRestored, !1), i.powerPreference = i.powerPreference || "high-performance"), this._badDesktopOS = /^((?!chrome|android).)*safari/i.test(navigator.userAgent), this._badDesktopOS && (i.xrCompatible = !1), !i.disableWebGL2Support)
        try {
          this._gl = b.getContext("webgl2", i) || b.getContext("experimental-webgl2", i), this._gl && (this._webGLVersion = 2, this._shaderPlatformName = "WEBGL2", this._gl.deleteQuery || (this._webGLVersion = 1, this._shaderPlatformName = "WEBGL1"));
        } catch {
        }
      if (!this._gl) {
        if (!b)
          throw new Error("The provided canvas is null or undefined.");
        try {
          this._gl = b.getContext("webgl", i) || b.getContext("experimental-webgl", i);
        } catch {
          throw new Error("WebGL not supported");
        }
      }
      if (!this._gl)
        throw new Error("WebGL not supported");
    } else {
      this._gl = e, this._renderingCanvas = this._gl.canvas, this._gl.renderbufferStorageMultisample ? (this._webGLVersion = 2, this._shaderPlatformName = "WEBGL2") : this._shaderPlatformName = "WEBGL1";
      const A = this._gl.getContextAttributes();
      A && (i.stencil = A.stencil);
    }
    this._gl.pixelStorei(this._gl.UNPACK_COLORSPACE_CONVERSION_WEBGL, this._gl.NONE), i.useHighPrecisionFloats !== void 0 && (this._highPrecisionShadersAllowed = i.useHighPrecisionFloats), this.resize(), this._initGLContext(), this._initFeatures();
    for (let A = 0; A < this._caps.maxVertexAttribs; A++)
      this._currentBufferPointers[A] = new zs();
    this._shaderProcessor = this.webGLVersion > 1 ? new Vs() : new ks(), this._badOS = /iPad/i.test(navigator.userAgent) || /iPhone/i.test(navigator.userAgent);
    const v = `Babylon.js v${se.Version}`;
    console.log(v + ` - ${this.description}`), this._renderingCanvas && this._renderingCanvas.setAttribute && this._renderingCanvas.setAttribute("data-engine", v);
  }
  _setupMobileChecks() {
    navigator && navigator.userAgent && (this._checkForMobile = () => {
      const e = navigator.userAgent;
      this.hostInformation.isMobile = e.indexOf("Mobile") !== -1 || // Needed for iOS 13+ detection on iPad (inspired by solution from https://stackoverflow.com/questions/9038625/detect-if-device-is-ios)
      e.indexOf("Mac") !== -1 && Wt() && "ontouchend" in document;
    }, this._checkForMobile(), Ie() && window.addEventListener("resize", this._checkForMobile));
  }
  _restoreEngineAfterContextLost(e) {
    setTimeout(async () => {
      var t;
      this._dummyFramebuffer = null;
      const i = this._depthCullingState.depthTest, s = this._depthCullingState.depthFunc, r = this._depthCullingState.depthMask, n = this._stencilState.stencilTest;
      await e(), this.wipeCaches(!0), this._rebuildEffects(), (t = this._rebuildComputeEffects) === null || t === void 0 || t.call(this), this._rebuildBuffers(), this._rebuildInternalTextures(), this._rebuildRenderTargetWrappers(), this.wipeCaches(!0), this._depthCullingState.depthTest = i, this._depthCullingState.depthFunc = s, this._depthCullingState.depthMask = r, this._stencilState.stencilTest = n, S.Warn(this.name + " context successfully restored."), this.onContextRestoredObservable.notifyObservers(this), this._contextWasLost = !1;
    }, 0);
  }
  /**
   * Shared initialization across engines types.
   * @param canvas The canvas associated with this instance of the engine.
   */
  _sharedInit(e) {
    this._renderingCanvas = e;
  }
  /**
   * @internal
   */
  _getShaderProcessingContext(e) {
    return null;
  }
  _rebuildInternalTextures() {
    const e = this._internalTexturesCache.slice();
    for (const t of e)
      t._rebuild();
  }
  _rebuildRenderTargetWrappers() {
    const e = this._renderTargetWrapperCache.slice();
    for (const t of e)
      t._rebuild();
  }
  _rebuildEffects() {
    for (const e in this._compiledEffects) {
      const t = this._compiledEffects[e];
      t._pipelineContext = null, t._wasPreviouslyReady = !1, t._prepareEffect();
    }
    Be.ResetCache();
  }
  /**
   * Gets a boolean indicating if all created effects are ready
   * @returns true if all effects are ready
   */
  areAllEffectsReady() {
    for (const e in this._compiledEffects)
      if (!this._compiledEffects[e].isReady())
        return !1;
    return !0;
  }
  _rebuildBuffers() {
    for (const e of this._uniformBuffers)
      e._rebuild();
    for (const e of this._storageBuffers)
      e._rebuild();
  }
  _initGLContext() {
    var e;
    this._caps = {
      maxTexturesImageUnits: this._gl.getParameter(this._gl.MAX_TEXTURE_IMAGE_UNITS),
      maxCombinedTexturesImageUnits: this._gl.getParameter(this._gl.MAX_COMBINED_TEXTURE_IMAGE_UNITS),
      maxVertexTextureImageUnits: this._gl.getParameter(this._gl.MAX_VERTEX_TEXTURE_IMAGE_UNITS),
      maxTextureSize: this._gl.getParameter(this._gl.MAX_TEXTURE_SIZE),
      maxSamples: this._webGLVersion > 1 ? this._gl.getParameter(this._gl.MAX_SAMPLES) : 1,
      maxCubemapTextureSize: this._gl.getParameter(this._gl.MAX_CUBE_MAP_TEXTURE_SIZE),
      maxRenderTextureSize: this._gl.getParameter(this._gl.MAX_RENDERBUFFER_SIZE),
      maxVertexAttribs: this._gl.getParameter(this._gl.MAX_VERTEX_ATTRIBS),
      maxVaryingVectors: this._gl.getParameter(this._gl.MAX_VARYING_VECTORS),
      maxFragmentUniformVectors: this._gl.getParameter(this._gl.MAX_FRAGMENT_UNIFORM_VECTORS),
      maxVertexUniformVectors: this._gl.getParameter(this._gl.MAX_VERTEX_UNIFORM_VECTORS),
      parallelShaderCompile: this._gl.getExtension("KHR_parallel_shader_compile") || 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"),
      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: !1,
      timerQuery: this._gl.getExtension("EXT_disjoint_timer_query_webgl2") || this._gl.getExtension("EXT_disjoint_timer_query"),
      supportOcclusionQuery: this._webGLVersion > 1,
      canUseTimestampForTimerQuery: !1,
      drawBuffersExtension: !1,
      maxMSAASamples: 1,
      colorBufferFloat: !!(this._webGLVersion > 1 && this._gl.getExtension("EXT_color_buffer_float")),
      textureFloat: !!(this._webGLVersion > 1 || this._gl.getExtension("OES_texture_float")),
      textureHalfFloat: !!(this._webGLVersion > 1 || this._gl.getExtension("OES_texture_half_float")),
      textureHalfFloatRender: !1,
      textureFloatLinearFiltering: !1,
      textureFloatRender: !1,
      textureHalfFloatLinearFiltering: !1,
      vertexArrayObject: !1,
      instancedArrays: !1,
      textureLOD: !!(this._webGLVersion > 1 || this._gl.getExtension("EXT_shader_texture_lod")),
      texelFetch: this._webGLVersion !== 1,
      blendMinMax: !1,
      multiview: this._gl.getExtension("OVR_multiview2"),
      oculusMultiview: this._gl.getExtension("OCULUS_multiview"),
      depthTextureExtension: !1,
      canUseGLInstanceID: this._webGLVersion > 1,
      canUseGLVertexID: this._webGLVersion > 1,
      supportComputeShaders: !1,
      supportSRGBBuffers: !1,
      supportTransformFeedbacks: this._webGLVersion > 1,
      textureMaxLevel: this._webGLVersion > 1,
      texture2DArrayMaxLayerCount: this._webGLVersion > 1 ? this._gl.getParameter(this._gl.MAX_ARRAY_TEXTURE_LAYERS) : 128,
      disableMorphTargetTexture: !1
    }, this._glVersion = this._gl.getParameter(this._gl.VERSION);
    const t = this._gl.getExtension("WEBGL_debug_renderer_info");
    if (t != null && (this._glRenderer = this._gl.getParameter(t.UNMASKED_RENDERER_WEBGL), this._glVendor = this._gl.getParameter(t.UNMASKED_VENDOR_WEBGL)), this._glVendor || (this._glVendor = this._gl.getParameter(this._gl.VENDOR) || "Unknown vendor"), this._glRenderer || (this._glRenderer = this._gl.getParameter(this._gl.RENDERER) || "Unknown renderer"), this._gl.HALF_FLOAT_OES !== 36193 && (this._gl.HALF_FLOAT_OES = 36193), this._gl.RGBA16F !== 34842 && (this._gl.RGBA16F = 34842), this._gl.RGBA32F !== 34836 && (this._gl.RGBA32F = 34836), this._gl.DEPTH24_STENCIL8 !== 35056 && (this._gl.DEPTH24_STENCIL8 = 35056), this._caps.timerQuery && (this._webGLVersion === 1 && (this._gl.getQuery = this._caps.timerQuery.getQueryEXT.bind(this._caps.timerQuery)), this._caps.canUseTimestampForTimerQuery = ((e = this._gl.getQuery(this._caps.timerQuery.TIMESTAMP_EXT, this._caps.timerQuery.QUERY_COUNTER_BITS_EXT)) !== null && e !== void 0 ? e : 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")), this._caps.textureFloatRender = !!(this._caps.textureFloat && this._canRenderToFloatFramebuffer()), this._caps.textureHalfFloatLinearFiltering = !!(this._webGLVersion > 1 || this._caps.textureHalfFloat && this._gl.getExtension("OES_texture_half_float_linear")), this._caps.astc && (this._gl.COMPRESSED_SRGB8_ALPHA8_ASTC_4x4_KHR = this._caps.astc.COMPRESSED_SRGB8_ALPHA8_ASTC_4x4_KHR), this._caps.bptc && (this._gl.COMPRESSED_SRGB_ALPHA_BPTC_UNORM_EXT = this._caps.bptc.COMPRESSED_SRGB_ALPHA_BPTC_UNORM_EXT), 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), 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), this._webGLVersion > 1 && this._gl.HALF_FLOAT_OES !== 5131 && (this._gl.HALF_FLOAT_OES = 5131), this._caps.textureHalfFloatRender = this._caps.textureHalfFloat && this._canRenderToHalfFloatFramebuffer(), this._webGLVersion > 1)
      this._caps.drawBuffersExtension = !0, this._caps.maxMSAASamples = this._maxMSAASamplesOverride !== null ? this._maxMSAASamplesOverride : this._gl.getParameter(this._gl.MAX_SAMPLES);
    else {
      const i = this._gl.getExtension("WEBGL_draw_buffers");
      if (i !== null) {
        this._caps.drawBuffersExtension = !0, this._gl.drawBuffers = i.drawBuffersWEBGL.bind(i), this._gl.DRAW_FRAMEBUFFER = this._gl.FRAMEBUFFER;
        for (let s = 0; s < 16; s++)
          this._gl["COLOR_ATTACHMENT" + s + "_WEBGL"] = i["COLOR_ATTACHMENT" + s + "_WEBGL"];
      }
    }
    if (this._webGLVersion > 1)
      this._caps.depthTextureExtension = !0;
    else {
      const i = this._gl.getExtension("WEBGL_depth_texture");
      i != null && (this._caps.depthTextureExtension = !0, this._gl.UNSIGNED_INT_24_8 = i.UNSIGNED_INT_24_8_WEBGL);
    }
    if (this.disableVertexArrayObjects)
      this._caps.vertexArrayObject = !1;
    else if (this._webGLVersion > 1)
      this._caps.vertexArrayObject = !0;
    else {
      const i = this._gl.getExtension("OES_vertex_array_object");
      i != null && (this._caps.vertexArrayObject = !0, this._gl.createVertexArray = i.createVertexArrayOES.bind(i), this._gl.bindVertexArray = i.bindVertexArrayOES.bind(i), this._gl.deleteVertexArray = i.deleteVertexArrayOES.bind(i));
    }
    if (this._webGLVersion > 1)
      this._caps.instancedArrays = !0;
    else {
      const i = this._gl.getExtension("ANGLE_instanced_arrays");
      i != null ? (this._caps.instancedArrays = !0, this._gl.drawArraysInstanced = i.drawArraysInstancedANGLE.bind(i), this._gl.drawElementsInstanced = i.drawElementsInstancedANGLE.bind(i), this._gl.vertexAttribDivisor = i.vertexAttribDivisorANGLE.bind(i)) : this._caps.instancedArrays = !1;
    }
    if (this._gl.getShaderPrecisionFormat) {
      const i = this._gl.getShaderPrecisionFormat(this._gl.VERTEX_SHADER, this._gl.HIGH_FLOAT), s = this._gl.getShaderPrecisionFormat(this._gl.FRAGMENT_SHADER, this._gl.HIGH_FLOAT);
      i && s && (this._caps.highPrecisionShaderSupported = i.precision !== 0 && s.precision !== 0);
    }
    if (this._webGLVersion > 1)
      this._caps.blendMinMax = !0;
    else {
      const i = this._gl.getExtension("EXT_blend_minmax");
      i != null && (this._caps.blendMinMax = !0, this._gl.MAX = i.MAX_EXT, this._gl.MIN = i.MIN_EXT);
    }
    if (!this._caps.supportSRGBBuffers) {
      if (this._webGLVersion > 1)
        this._caps.supportSRGBBuffers = !0;
      else {
        const i = this._gl.getExtension("EXT_sRGB");
        i != null && (this._caps.supportSRGBBuffers = !0, this._gl.SRGB = i.SRGB_EXT, this._gl.SRGB8 = i.SRGB_ALPHA_EXT, this._gl.SRGB8_ALPHA8 = i.SRGB_ALPHA_EXT);
      }
      this._caps.supportSRGBBuffers = this._caps.supportSRGBBuffers && !!(this._creationOptions && this._creationOptions.forceSRGBBufferSupportState);
    }
    this._depthCullingState.depthTest = !0, this._depthCullingState.depthFunc = this._gl.LEQUAL, this._depthCullingState.depthMask = !0, this._maxSimultaneousTextures = this._caps.maxCombinedTexturesImageUnits;
    for (let i = 0; i < this._maxSimultaneousTextures; i++)
      this._nextFreeTextureSlots.push(i);
    this._glRenderer === "Mali-G72" && (this._caps.disableMorphTargetTexture = !0);
  }
  _initFeatures() {
    this._features = {
      forceBitmapOverHTMLImageElement: !1,
      supportRenderAndCopyToLodForFloatTextures: this._webGLVersion !== 1,
      supportDepthStencilTexture: this._webGLVersion !== 1,
      supportShadowSamplers: this._webGLVersion !== 1,
      uniformBufferHardCheckMatrix: !1,
      allowTexturePrefiltering: this._webGLVersion !== 1,
      trackUbosInFrame: !1,
      checkUbosContentBeforeUpload: !1,
      supportCSM: this._webGLVersion !== 1,
      basisNeedsPOT: this._webGLVersion === 1,
      support3DTextures: this._webGLVersion !== 1,
      needTypeSuffixInShaderConstants: this._webGLVersion !== 1,
      supportMSAA: this._webGLVersion !== 1,
      supportSSAO2: this._webGLVersion !== 1,
      supportExtendedTextureFormats: this._webGLVersion !== 1,
      supportSwitchCaseInShader: this._webGLVersion !== 1,
      supportSyncTextureRead: !0,
      needsInvertingBitmap: !0,
      useUBOBindingCache: !0,
      needShaderCodeInlining: !1,
      needToAlwaysBindUniformBuffers: !1,
      supportRenderPasses: !1,
      supportSpriteInstancing: !0,
      _collectUbosUpdatedInFrame: !1
    };
  }
  /**
   * 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";
  }
  /**
   * Returns true if the stencil buffer has been enabled through the creation option of the context.
   */
  get isStencilEnable() {
    return this._isStencilEnable;
  }
  /** @internal */
  _prepareWorkingCanvas() {
    if (this._workingCanvas)
      return;
    this._workingCanvas = this.createCanvas(1, 1);
    const e = this._workingCanvas.getContext("2d");
    e && (this._workingContext = e);
  }
  /**
   * Reset the texture cache to empty state
   */
  resetTextureCache() {
    for (const e in this._boundTexturesCache)
      Object.prototype.hasOwnProperty.call(this._boundTexturesCache, e) && (this._boundTexturesCache[e] = null);
    this._currentTextureChannel = -1;
  }
  /**
   * 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
    };
  }
  /**
   * 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(e) {
    this._hardwareScalingLevel = e, 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 the list of loaded textures
   * @returns an array containing all loaded textures
   */
  getLoadedTexturesCache() {
    return this._internalTexturesCache;
  }
  /**
   * Gets the object containing all engine capabilities
   * @returns the EngineCapabilities object
   */
  getCaps() {
    return this._caps;
  }
  /**
   * stop executing a render loop function and remove it from the execution array
   * @param renderFunction defines the function to be removed. If not provided all functions will be removed.
   */
  stopRenderLoop(e) {
    if (!e) {
      this._activeRenderLoops.length = 0;
      return;
    }
    const t = this._activeRenderLoops.indexOf(e);
    t >= 0 && this._activeRenderLoops.splice(t, 1);
  }
  /** @internal */
  _renderLoop() {
    if (!this._contextWasLost) {
      let e = !0;
      if ((this._isDisposed || !this.renderEvenInBackground && this._windowIsBackground) && (e = !1), e) {
        this.beginFrame();
        for (let t = 0; t < this._activeRenderLoops.length; t++) {
          const i = this._activeRenderLoops[t];
          i();
        }
        this.endFrame();
      }
    }
    this._activeRenderLoops.length > 0 ? this._frameHandler = this._queueNewFrame(this._boundRenderFunction, this.getHostWindow()) : this._renderingQueueLaunched = !1;
  }
  /**
   * 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
   * @returns an Audio Context
   */
  getAudioContext() {
    return this._audioContext;
  }
  /**
   * Gets the audio destination specified in engine initialization options
   * @returns an audio destination node
   */
  getAudioDestination() {
    return this._audioDestination;
  }
  /**
   * Gets host window
   * @returns the host window object
   */
  getHostWindow() {
    return Ie() ? this._renderingCanvas && this._renderingCanvas.ownerDocument && this._renderingCanvas.ownerDocument.defaultView ? this._renderingCanvas.ownerDocument.defaultView : window : null;
  }
  /**
   * 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(e = !1) {
    return !e && this._currentRenderTarget ? this._currentRenderTarget.width : 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(e = !1) {
    return !e && this._currentRenderTarget ? this._currentRenderTarget.height : this._framebufferDimensionsObject ? this._framebufferDimensionsObject.framebufferHeight : this._gl.drawingBufferHeight;
  }
  /**
   * Can be used to override the current requestAnimationFrame requester.
   * @internal
   */
  _queueNewFrame(e, t) {
    return se.QueueNewFrame(e, t);
  }
  /**
   * Register and execute a render loop. The engine can have more than one render function
   * @param renderFunction defines the function to continuously execute
   */
  runRenderLoop(e) {
    this._activeRenderLoops.indexOf(e) === -1 && (this._activeRenderLoops.push(e), this._renderingQueueLaunched || (this._renderingQueueLaunched = !0, this._boundRenderFunction = this._renderLoop.bind(this), this._frameHandler = this._queueNewFrame(this._boundRenderFunction, this.getHostWindow())));
  }
  /**
   * Clear the current render buffer or the current render target (if any is set up)
   * @param color defines the color to use
   * @param backBuffer defines if the back buffer must be cleared
   * @param depth defines if the depth buffer must be cleared
   * @param stencil defines if the stencil buffer must be cleared
   */
  clear(e, t, i, s = !1) {
    const r = this.stencilStateComposer.useStencilGlobalOnly;
    this.stencilStateComposer.useStencilGlobalOnly = !0, this.applyStates(), this.stencilStateComposer.useStencilGlobalOnly = r;
    let n = 0;
    t && e && (this._gl.clearColor(e.r, e.g, e.b, e.a !== void 0 ? e.a : 1), n |= this._gl.COLOR_BUFFER_BIT), i && (this.useReverseDepthBuffer ? (this._depthCullingState.depthFunc = this._gl.GEQUAL, this._gl.clearDepth(0)) : this._gl.clearDepth(1), n |= this._gl.DEPTH_BUFFER_BIT), s && (this._gl.clearStencil(0), n |= this._gl.STENCIL_BUFFER_BIT), this._gl.clear(n);
  }
  /**
   * @internal
   */
  _viewport(e, t, i, s) {
    (e !== this._viewportCached.x || t !== this._viewportCached.y || i !== this._viewportCached.z || s !== this._viewportCached.w) && (this._viewportCached.x = e, this._viewportCached.y = t, this._viewportCached.z = i, this._viewportCached.w = s, this._gl.viewport(e, t, i, s));
  }
  /**
   * 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(e, t, i) {
    const s = t || this.getRenderWidth(), r = i || this.getRenderHeight(), n = e.x || 0, a = e.y || 0;
    this._cachedViewport = e, this._viewport(n * s, a * r, s * e.width, r * e.height);
  }
  /**
   * Begin a new frame
   */
  beginFrame() {
  }
  /**
   * Enf the current frame
   */
  endFrame() {
    this._badOS && this.flushFramebuffer(), this._frameId++;
  }
  /**
   * Resize the view according to the canvas' size
   * @param forceSetSize true to force setting the sizes of the underlying canvas
   */
  resize(e = !1) {
    let t, i;
    if (this.adaptToDeviceRatio) {
      const s = Ie() && window.devicePixelRatio || 1, r = this._lastDevicePixelRatio / s;
      this._lastDevicePixelRatio = s, this._hardwareScalingLevel *= r;
    }
    Ie() ? (t = this._renderingCanvas ? this._renderingCanvas.clientWidth || this._renderingCanvas.width : window.innerWidth, i = this._renderingCanvas ? this._renderingCanvas.clientHeight || this._renderingCanvas.height : window.innerHeight) : (t = this._renderingCanvas ? this._renderingCanvas.width : 100, i = this._renderingCanvas ? this._renderingCanvas.height : 100), this.setSize(t / this._hardwareScalingLevel, i / this._hardwareScalingLevel, e);
  }
  /**
   * 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(e, t, i = !1) {
    return !this._renderingCanvas || (e = e | 0, t = t | 0, !i && this._renderingCanvas.width === e && this._renderingCanvas.height === t) ? !1 : (this._renderingCanvas.width = e, this._renderingCanvas.height = t, !0);
  }
  /**
   * 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(e, t = 0, i, s, r, n = 0, a = 0) {
    var o, h, c, u, d;
    const g = e;
    this._currentRenderTarget && this.unBindFramebuffer(this._currentRenderTarget), this._currentRenderTarget = e, this._bindUnboundFramebuffer(g._MSAAFramebuffer ? g._MSAAFramebuffer : g._framebuffer);
    const f = this._gl;
    e.isMulti || (e.is2DArray ? f.framebufferTextureLayer(f.FRAMEBUFFER, f.COLOR_ATTACHMENT0, (o = e.texture._hardwareTexture) === null || o === void 0 ? void 0 : o.underlyingResource, n, a) : e.isCube && f.framebufferTexture2D(f.FRAMEBUFFER, f.COLOR_ATTACHMENT0, f.TEXTURE_CUBE_MAP_POSITIVE_X + t, (h = e.texture._hardwareTexture) === null || h === void 0 ? void 0 : h.underlyingResource, n));
    const m = e._depthStencilTexture;
    if (m) {
      const b = e._depthStencilTextureWithStencil ? f.DEPTH_STENCIL_ATTACHMENT : f.DEPTH_ATTACHMENT;
      e.is2DArray ? f.framebufferTextureLayer(f.FRAMEBUFFER, b, (c = m._hardwareTexture) === null || c === void 0 ? void 0 : c.underlyingResource, n, a) : e.isCube ? f.framebufferTexture2D(f.FRAMEBUFFER, b, f.TEXTURE_CUBE_MAP_POSITIVE_X + t, (u = m._hardwareTexture) === null || u === void 0 ? void 0 : u.underlyingResource, n) : f.framebufferTexture2D(f.FRAMEBUFFER, b, f.TEXTURE_2D, (d = m._hardwareTexture) === null || d === void 0 ? void 0 : d.underlyingResource, n);
    }
    this._cachedViewport && !r ? this.setViewport(this._cachedViewport, i, s) : (i || (i = e.width, n && (i = i / Math.pow(2, n))), s || (s = e.height, n && (s = s / Math.pow(2, n))), this._viewport(0, 0, i, s)), this.wipeCaches();
  }
  /**
   * 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(e, t = 0, i, s = !1, r, n, a = 0) {
    var o, h;
    (this._depthCullingState.cull !== e || i) && (this._depthCullingState.cull = e);
    const c = !((h = (o = this.cullBackFaces) !== null && o !== void 0 ? o : r) !== null && h !== void 0) || h ? this._gl.BACK : this._gl.FRONT;
    (this._depthCullingState.cullFace !== c || i) && (this._depthCullingState.cullFace = c), this.setZOffset(t), this.setZOffsetUnits(a);
    const u = s ? this._gl.CW : this._gl.CCW;
    (this._depthCullingState.frontFace !== u || i) && (this._depthCullingState.frontFace = u), this._stencilStateComposer.stencilMaterial = n;
  }
  /**
   * 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(e) {
    this._depthCullingState.depthTest = e;
  }
  /**
   * Set the z offset Factor to apply to current rendering
   * @param value defines the offset to apply
   */
  setZOffset(e) {
    this._depthCullingState.zOffset = this.useReverseDepthBuffer ? -e : e;
  }
  /**
   * Gets the current value of the zOffset Factor
   * @returns the current zOffset Factor state
   */
  getZOffset() {
    const e = this._depthCullingState.zOffset;
    return this.useReverseDepthBuffer ? -e : e;
  }
  /**
   * Set the z offset Units to apply to current rendering
   * @param value defines the offset to apply
   */
  setZOffsetUnits(e) {
    this._depthCullingState.zOffsetUnits = this.useReverseDepthBuffer ? -e : e;
  }
  /**
   * Gets the current value of the zOffset Units
   * @returns the current zOffset Units state
   */
  getZOffsetUnits() {
    const e = this._depthCullingState.zOffsetUnits;
    return this.useReverseDepthBuffer ? -e : e;
  }
  /**
   * @internal
   */
  _bindUnboundFramebuffer(e) {
    this._currentFramebuffer !== e && (this._gl.bindFramebuffer(this._gl.FRAMEBUFFER, e), this._currentFramebuffer = e);
  }
  /** @internal */
  _currentFrameBufferIsDefaultFrameBuffer() {
    return this._currentFramebuffer === null;
  }
  /**
   * Generates the mipmaps for a texture
   * @param texture texture to generate the mipmaps for
   */
  generateMipmaps(e) {
    this._bindTextureDirectly(this._gl.TEXTURE_2D, e, !0), this._gl.generateMipmap(this._gl.TEXTURE_2D), this._bindTextureDirectly(this._gl.TEXTURE_2D, 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(e, t = !1, i) {
    var s;
    const r = e;
    this._currentRenderTarget = null;
    const n = this._gl;
    if (r._MSAAFramebuffer) {
      if (e.isMulti) {
        this.unBindMultiColorAttachmentFramebuffer(e, t, i);
        return;
      }
      n.bindFramebuffer(n.READ_FRAMEBUFFER, r._MSAAFramebuffer), n.bindFramebuffer(n.DRAW_FRAMEBUFFER, r._framebuffer), n.blitFramebuffer(0, 0, e.width, e.height, 0, 0, e.width, e.height, n.COLOR_BUFFER_BIT, n.NEAREST);
    }
    !((s = e.texture) === null || s === void 0) && s.generateMipMaps && !t && !e.isCube && this.generateMipmaps(e.texture), i && (r._MSAAFramebuffer && this._bindUnboundFramebuffer(r._framebuffer), i()), this._bindUnboundFramebuffer(null);
  }
  /**
   * 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() {
    this._currentRenderTarget ? this.unBindFramebuffer(this._currentRenderTarget) : this._bindUnboundFramebuffer(null), 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 for the vertex buffer
   * @returns the new WebGL static buffer
   */
  createVertexBuffer(e) {
    return this._createVertexBuffer(e, this._gl.STATIC_DRAW);
  }
  _createVertexBuffer(e, t) {
    const i = this._gl.createBuffer();
    if (!i)
      throw new Error("Unable to create vertex buffer");
    const s = new Gt(i);
    return this.bindArrayBuffer(s), e instanceof Array ? this._gl.bufferData(this._gl.ARRAY_BUFFER, new Float32Array(e), t) : this._gl.bufferData(this._gl.ARRAY_BUFFER, e, t), this._resetVertexBufferBinding(), s.references = 1, s;
  }
  /**
   * Creates a dynamic vertex buffer
   * @param data the data for the dynamic vertex buffer
   * @returns the new WebGL dynamic buffer
   */
  createDynamicVertexBuffer(e) {
    return this._createVertexBuffer(e, 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
   * @returns a new webGL buffer
   */
  createIndexBuffer(e, t) {
    const i = this._gl.createBuffer(), s = new Gt(i);
    if (!i)
      throw new Error("Unable to create index buffer");
    this.bindIndexBuffer(s);
    const r = this._normalizeIndexData(e);
    return this._gl.bufferData(this._gl.ELEMENT_ARRAY_BUFFER, r, t ? this._gl.DYNAMIC_DRAW : this._gl.STATIC_DRAW), this._resetIndexBufferBinding(), s.references = 1, s.is32Bits = r.BYTES_PER_ELEMENT === 4, s;
  }
  _normalizeIndexData(e) {
    if (e.BYTES_PER_ELEMENT === 2)
      return e;
    if (this._caps.uintIndices) {
      if (e instanceof Uint32Array)
        return e;
      for (let i = 0; i < e.length; i++)
        if (e[i] >= 65535)
          return new Uint32Array(e);
      return new Uint16Array(e);
    }
    return new Uint16Array(e);
  }
  /**
   * Bind a webGL buffer to the webGL context
   * @param buffer defines the buffer to bind
   */
  bindArrayBuffer(e) {
    this._vaoRecordInProgress || this._unbindVertexArrayObject(), this._bindBuffer(e, 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(e, t, i) {
    const s = e.program, r = this._gl.getUniformBlockIndex(s, t);
    this._gl.uniformBlockBinding(s, r, i);
  }
  // eslint-disable-next-line @typescript-eslint/naming-convention
  bindIndexBuffer(e) {
    this._vaoRecordInProgress || this._unbindVertexArrayObject(), this._bindBuffer(e, this._gl.ELEMENT_ARRAY_BUFFER);
  }
  _bindBuffer(e, t) {
    (this._vaoRecordInProgress || this._currentBoundBuffer[t] !== e) && (this._gl.bindBuffer(t, e ? e.underlyingResource : null), this._currentBoundBuffer[t] = e);
  }
  /**
   * update the bound buffer with the given data
   * @param data defines the data to update
   */
  updateArrayBuffer(e) {
    this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, e);
  }
  _vertexAttribPointer(e, t, i, s, r, n, a) {
    const o = this._currentBufferPointers[t];
    if (!o)
      return;
    let h = !1;
    o.active ? (o.buffer !== e && (o.buffer = e, h = !0), o.size !== i && (o.size = i, h = !0), o.type !== s && (o.type = s, h = !0), o.normalized !== r && (o.normalized = r, h = !0), o.stride !== n && (o.stride = n, h = !0), o.offset !== a && (o.offset = a, h = !0)) : (h = !0, o.active = !0, o.index = t, o.size = i, o.type = s, o.normalized = r, o.stride = n, o.offset = a, o.buffer = e), (h || this._vaoRecordInProgress) && (this.bindArrayBuffer(e), s === this._gl.UNSIGNED_INT || s === this._gl.INT ? this._gl.vertexAttribIPointer(t, i, s, n, a) : this._gl.vertexAttribPointer(t, i, s, r, n, a));
  }
  /**
   * @internal
   */
  _bindIndexBufferWithCache(e) {
    e != null && this._cachedIndexBuffer !== e && (this._cachedIndexBuffer = e, this.bindIndexBuffer(e), this._uintIndicesCurrentlySet = e.is32Bits);
  }
  _bindVertexBuffersAttributes(e, t, i) {
    const s = t.getAttributesNames();
    this._vaoRecordInProgress || this._unbindVertexArrayObject(), this.unbindAllAttributes();
    for (let r = 0; r < s.length; r++) {
      const n = t.getAttributeLocation(r);
      if (n >= 0) {
        const a = s[r];
        let o = null;
        if (i && (o = i[a]), o || (o = e[a]), !o)
          continue;
        this._gl.enableVertexAttribArray(n), this._vaoRecordInProgress || (this._vertexAttribArraysEnabled[n] = !0);
        const h = o.getBuffer();
        h && (this._vertexAttribPointer(h, n, o.getSize(), o.type, o.normalized, o.byteStride, o.byteOffset), o.getIsInstanced() && (this._gl.vertexAttribDivisor(n, o.getInstanceDivisor()), this._vaoRecordInProgress || (this._currentInstanceLocations.push(n), this._currentInstanceBuffers.push(h))));
      }
    }
  }
  /**
   * 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(e, t, i, s) {
    const r = this._gl.createVertexArray();
    if (!r)
      throw new Error("Unable to create VAO");
    return this._vaoRecordInProgress = !0, this._gl.bindVertexArray(r), this._mustWipeVertexAttributes = !0, this._bindVertexBuffersAttributes(e, i, s), this.bindIndexBuffer(t), this._vaoRecordInProgress = !1, this._gl.bindVertexArray(null), r;
  }
  /**
   * 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(e, t) {
    this._cachedVertexArrayObject !== e && (this._cachedVertexArrayObject = e, this._gl.bindVertexArray(e), this._cachedVertexBuffers = null, this._cachedIndexBuffer = null, this._uintIndicesCurrentlySet = t != null && t.is32Bits, this._mustWipeVertexAttributes = !0);
  }
  /**
   * 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(e, t, i, s, r) {
    if (this._cachedVertexBuffers !== e || this._cachedEffectForVertexBuffers !== r) {
      this._cachedVertexBuffers = e, this._cachedEffectForVertexBuffers = r;
      const n = r.getAttributesCount();
      this._unbindVertexArrayObject(), this.unbindAllAttributes();
      let a = 0;
      for (let o = 0; o < n; o++)
        if (o < i.length) {
          const h = r.getAttributeLocation(o);
          h >= 0 && (this._gl.enableVertexAttribArray(h), this._vertexAttribArraysEnabled[h] = !0, this._vertexAttribPointer(e, h, i[o], this._gl.FLOAT, !1, s, a)), a += i[o] * 4;
        }
    }
    this._bindIndexBufferWithCache(t);
  }
  _unbindVertexArrayObject() {
    this._cachedVertexArrayObject && (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(e, t, i, s) {
    (this._cachedVertexBuffers !== e || this._cachedEffectForVertexBuffers !== i) && (this._cachedVertexBuffers = e, this._cachedEffectForVertexBuffers = i, this._bindVertexBuffersAttributes(e, i, s)), this._bindIndexBufferWithCache(t);
  }
  /**
   * Unbind all instance attributes
   */
  unbindInstanceAttributes() {
    let e;
    for (let t = 0, i = this._currentInstanceLocations.length; t < i; t++) {
      const s = this._currentInstanceBuffers[t];
      e != s && s.references && (e = s, this.bindArrayBuffer(s));
      const r = this._currentInstanceLocations[t];
      this._gl.vertexAttribDivisor(r, 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(e) {
    this._gl.deleteVertexArray(e);
  }
  /**
   * @internal
   */
  _releaseBuffer(e) {
    return e.references--, e.references === 0 ? (this._deleteBuffer(e), !0) : !1;
  }
  _deleteBuffer(e) {
    this._gl.deleteBuffer(e.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(e, t, i) {
    if (this.bindArrayBuffer(e), t && this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, t), i[0].index !== void 0)
      this.bindInstancesBuffer(e, i, !0);
    else
      for (let s = 0; s < 4; s++) {
        const r = i[s];
        this._vertexAttribArraysEnabled[r] || (this._gl.enableVertexAttribArray(r), this._vertexAttribArraysEnabled[r] = !0), this._vertexAttribPointer(e, r, 4, this._gl.FLOAT, !1, 64, s * 16), this._gl.vertexAttribDivisor(r, 1), this._currentInstanceLocations.push(r), this._currentInstanceBuffers.push(e);
      }
  }
  /**
   * 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(e, t, i = !0) {
    this.bindArrayBuffer(e);
    let s = 0;
    if (i)
      for (let r = 0; r < t.length; r++) {
        const n = t[r];
        s += n.attributeSize * 4;
      }
    for (let r = 0; r < t.length; r++) {
      const n = t[r];
      n.index === void 0 && (n.index = this._currentEffect.getAttributeLocationByName(n.attributeName)), !(n.index < 0) && (this._vertexAttribArraysEnabled[n.index] || (this._gl.enableVertexAttribArray(n.index), this._vertexAttribArraysEnabled[n.index] = !0), this._vertexAttribPointer(e, n.index, n.attributeSize, n.attributeType || this._gl.FLOAT, n.normalized || !1, s, n.offset), this._gl.vertexAttribDivisor(n.index, n.divisor === void 0 ? 1 : n.divisor), this._currentInstanceLocations.push(n.index), this._currentInstanceBuffers.push(e));
    }
  }
  /**
   * Disable the instance attribute corresponding to the name in parameter
   * @param name defines the name of the attribute to disable
   */
  disableInstanceAttributeByName(e) {
    if (!this._currentEffect)
      return;
    const t = this._currentEffect.getAttributeLocationByName(e);
    this.disableInstanceAttribute(t);
  }
  /**
   * Disable the instance attribute corresponding to the location in parameter
   * @param attributeLocation defines the attribute location of the attribute to disable
   */
  disableInstanceAttribute(e) {
    let t = !1, i;
    for (; (i = this._currentInstanceLocations.indexOf(e)) !== -1; )
      this._currentInstanceLocations.splice(i, 1), this._currentInstanceBuffers.splice(i, 1), t = !0, i = this._currentInstanceLocations.indexOf(e);
    t && (this._gl.vertexAttribDivisor(e, 0), this.disableAttributeByIndex(e));
  }
  /**
   * Disable the attribute corresponding to the location in parameter
   * @param attributeLocation defines the attribute location of the attribute to disable
   */
  disableAttributeByIndex(e) {
    this._gl.disableVertexAttribArray(e), this._vertexAttribArraysEnabled[e] = !1, this._currentBufferPointers[e].active = !1;
  }
  /**
   * 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(e, t, i, s) {
    this.drawElementsType(e ? 0 : 1, t, i, s);
  }
  /**
   * 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(e, t, i) {
    this.drawArraysType(2, e, t, i);
  }
  /**
   * 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(e, t, i, s) {
    this.drawArraysType(e ? 0 : 1, t, i, s);
  }
  /**
   * 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(e, t, i, s) {
    this.applyStates(), this._reportDrawCall();
    const r = this._drawMode(e), n = this._uintIndicesCurrentlySet ? this._gl.UNSIGNED_INT : this._gl.UNSIGNED_SHORT, a = this._uintIndicesCurrentlySet ? 4 : 2;
    s ? this._gl.drawElementsInstanced(r, i, n, t * a, s) : this._gl.drawElements(r, i, n, t * a);
  }
  /**
   * 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(e, t, i, s) {
    this.applyStates(), this._reportDrawCall();
    const r = this._drawMode(e);
    s ? this._gl.drawArraysInstanced(r, t, i, s) : this._gl.drawArrays(r, t, i);
  }
  _drawMode(e) {
    switch (e) {
      case 0:
        return this._gl.TRIANGLES;
      case 2:
        return this._gl.POINTS;
      case 1:
        return this._gl.LINES;
      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;
    }
  }
  /** @internal */
  _reportDrawCall() {
  }
  // Shaders
  /**
   * @internal
   */
  _releaseEffect(e) {
    this._compiledEffects[e._key] && delete this._compiledEffects[e._key];
    const t = e.getPipelineContext();
    t && this._deletePipelineContext(t);
  }
  /**
   * @internal
   */
  _deletePipelineContext(e) {
    const t = e;
    t && t.program && (t.program.__SPECTOR_rebuildProgram = null, this._gl.deleteProgram(t.program));
  }
  /** @internal */
  _getGlobalDefines(e) {
    if (e) {
      this.isNDCHalfZRange ? e.IS_NDC_HALF_ZRANGE = "" : delete e.IS_NDC_HALF_ZRANGE, this.useReverseDepthBuffer ? e.USE_REVERSE_DEPTHBUFFER = "" : delete e.USE_REVERSE_DEPTHBUFFER, this.useExactSrgbConversions ? e.USE_EXACT_SRGB_CONVERSIONS = "" : delete e.USE_EXACT_SRGB_CONVERSIONS;
      return;
    } else {
      let t = "";
      return this.isNDCHalfZRange && (t += "#define IS_NDC_HALF_ZRANGE"), this.useReverseDepthBuffer && (t && (t += `
`), t += "#define USE_REVERSE_DEPTHBUFFER"), this.useExactSrgbConversions && (t && (t += `
`), t += "#define USE_EXACT_SRGB_CONVERSIONS"), t;
    }
  }
  /**
   * 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)
   * @returns the new Effect
   */
  createEffect(e, t, i, s, r, n, a, o, h, c = Ce.GLSL) {
    var u;
    const d = e.vertexElement || e.vertex || e.vertexToken || e.vertexSource || e, g = e.fragmentElement || e.fragment || e.fragmentToken || e.fragmentSource || e, f = this._getGlobalDefines();
    let m = (u = r ?? t.defines) !== null && u !== void 0 ? u : "";
    f && (m += f);
    const b = d + "+" + g + "@" + m;
    if (this._compiledEffects[b]) {
      const M = this._compiledEffects[b];
      return a && M.isReady() && a(M), M;
    }
    const T = new Be(e, t, i, s, this, r, n, a, o, h, b, c);
    return this._compiledEffects[b] = T, T;
  }
  // eslint-disable-next-line @typescript-eslint/naming-convention
  static _ConcatenateShader(e, t, i = "") {
    return i + (t ? t + `
` : "") + e;
  }
  _compileShader(e, t, i, s) {
    return this._compileRawShader(se._ConcatenateShader(e, i, s), t);
  }
  _compileRawShader(e, t) {
    const i = this._gl, s = i.createShader(t === "vertex" ? i.VERTEX_SHADER : i.FRAGMENT_SHADER);
    if (!s) {
      let r = i.NO_ERROR, n = i.NO_ERROR;
      for (; (n = i.getError()) !== i.NO_ERROR; )
        r = n;
      throw new Error(`Something went wrong while creating a gl ${t} shader object. gl error=${r}, gl isContextLost=${i.isContextLost()}, _contextWasLost=${this._contextWasLost}`);
    }
    return i.shaderSource(s, e), i.compileShader(s), s;
  }
  /**
   * @internal
   */
  _getShaderSource(e) {
    return this._gl.getShaderSource(e);
  }
  /**
   * 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(e, t, i, s, r = null) {
    s = s || this._gl;
    const n = this._compileRawShader(t, "vertex"), a = this._compileRawShader(i, "fragment");
    return this._createShaderProgram(e, n, a, s, r);
  }
  /**
   * 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(e, t, i, s, r, n = null) {
    r = r || this._gl;
    const a = this._webGLVersion > 1 ? `#version 300 es
#define WEBGL2 
` : "", o = this._compileShader(t, "vertex", s, a), h = this._compileShader(i, "fragment", s, a);
    return this._createShaderProgram(e, o, h, r, n);
  }
  /**
   * Inline functions in shader code that are marked to be inlined
   * @param code code to inline
   * @returns inlined code
   */
  inlineShaderCode(e) {
    return e;
  }
  /**
   * Creates a new pipeline context
   * @param shaderProcessingContext defines the shader processing context used during the processing if available
   * @returns the new pipeline
   */
  createPipelineContext(e) {
    const t = new Ws();
    return t.engine = this, this._caps.parallelShaderCompile && (t.isParallelCompiled = !0), t;
  }
  /**
   * Creates a new material context
   * @returns the new context
   */
  createMaterialContext() {
  }
  /**
   * Creates a new draw context
   * @returns the new context
   */
  createDrawContext() {
  }
  _createShaderProgram(e, t, i, s, r = null) {
    const n = s.createProgram();
    if (e.program = n, !n)
      throw new Error("Unable to create program");
    return s.attachShader(n, t), s.attachShader(n, i), s.linkProgram(n), e.context = s, e.vertexShader = t, e.fragmentShader = i, e.isParallelCompiled || this._finalizePipelineContext(e), n;
  }
  _finalizePipelineContext(e) {
    const t = e.context, i = e.vertexShader, s = e.fragmentShader, r = e.program;
    if (!t.getProgramParameter(r, t.LINK_STATUS)) {
      if (!this._gl.getShaderParameter(i, this._gl.COMPILE_STATUS)) {
        const o = this._gl.getShaderInfoLog(i);
        if (o)
          throw e.vertexCompilationError = o, new Error("VERTEX SHADER " + o);
      }
      if (!this._gl.getShaderParameter(s, this._gl.COMPILE_STATUS)) {
        const o = this._gl.getShaderInfoLog(s);
        if (o)
          throw e.fragmentCompilationError = o, new Error("FRAGMENT SHADER " + o);
      }
      const a = t.getProgramInfoLog(r);
      if (a)
        throw e.programLinkError = a, new Error(a);
    }
    if (this.validateShaderPrograms && (t.validateProgram(r), !t.getProgramParameter(r, t.VALIDATE_STATUS))) {
      const o = t.getProgramInfoLog(r);
      if (o)
        throw e.programValidationError = o, new Error(o);
    }
    t.deleteShader(i), t.deleteShader(s), e.vertexShader = void 0, e.fragmentShader = void 0, e.onCompiled && (e.onCompiled(), e.onCompiled = void 0);
  }
  /**
   * @internal
   */
  _preparePipelineContext(e, t, i, s, r, n, a, o, h, c) {
    const u = e;
    s ? u.program = this.createRawShaderProgram(u, t, i, void 0, h) : u.program = this.createShaderProgram(u, t, i, o, void 0, h), u.program.__SPECTOR_rebuildProgram = a;
  }
  /**
   * @internal
   */
  _isRenderingStateCompiled(e) {
    const t = e;
    return this._gl.getProgramParameter(t.program, this._caps.parallelShaderCompile.COMPLETION_STATUS_KHR) ? (this._finalizePipelineContext(t), !0) : !1;
  }
  /**
   * @internal
   */
  _executeWhenRenderingStateIsCompiled(e, t) {
    const i = e;
    if (!i.isParallelCompiled) {
      t();
      return;
    }
    const s = i.onCompiled;
    s ? i.onCompiled = () => {
      s(), t();
    } : i.onCompiled = t;
  }
  /**
   * 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(e, t) {
    const i = new Array(), s = e;
    for (let r = 0; r < t.length; r++)
      i.push(this._gl.getUniformLocation(s.program, t[r]));
    return i;
  }
  /**
   * 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(e, t) {
    const i = [], s = e;
    for (let r = 0; r < t.length; r++)
      try {
        i.push(this._gl.getAttribLocation(s.program, t[r]));
      } catch {
        i.push(-1);
      }
    return i;
  }
  /**
   * Activates an effect, making it the current one (ie. the one used for rendering)
   * @param effect defines the effect to activate
   */
  enableEffect(e) {
    e = e !== null && Pi.IsWrapper(e) ? e.effect : e, !(!e || e === this._currentEffect) && (this._stencilStateComposer.stencilMaterial = void 0, e = e, this.bindSamplers(e), this._currentEffect = e, e.onBind && e.onBind(e), e._onBindObservable && e._onBindObservable.notifyObservers(e));
  }
  /**
   * 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(e, t) {
    return e ? (this._gl.uniform1i(e, t), !0) : !1;
  }
  /**
   * 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(e, t, i) {
    return e ? (this._gl.uniform2i(e, t, i), !0) : !1;
  }
  /**
   * 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(e, t, i, s) {
    return e ? (this._gl.uniform3i(e, t, i, s), !0) : !1;
  }
  /**
   * 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(e, t, i, s, r) {
    return e ? (this._gl.uniform4i(e, t, i, s, r), !0) : !1;
  }
  /**
   * 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(e, t) {
    return e ? (this._gl.uniform1iv(e, t), !0) : !1;
  }
  /**
   * 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(e, t) {
    return !e || t.length % 2 !== 0 ? !1 : (this._gl.uniform2iv(e, t), !0);
  }
  /**
   * 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(e, t) {
    return !e || t.length % 3 !== 0 ? !1 : (this._gl.uniform3iv(e, t), !0);
  }
  /**
   * 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(e, t) {
    return !e || t.length % 4 !== 0 ? !1 : (this._gl.uniform4iv(e, t), !0);
  }
  /**
   * 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(e, t) {
    return e ? (this._gl.uniform1ui(e, t), !0) : !1;
  }
  /**
   * 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(e, t, i) {
    return e ? (this._gl.uniform2ui(e, t, i), !0) : !1;
  }
  /**
   * 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(e, t, i, s) {
    return e ? (this._gl.uniform3ui(e, t, i, s), !0) : !1;
  }
  /**
   * 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(e, t, i, s, r) {
    return e ? (this._gl.uniform4ui(e, t, i, s, r), !0) : !1;
  }
  /**
   * 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(e, t) {
    return e ? (this._gl.uniform1uiv(e, t), !0) : !1;
  }
  /**
   * 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(e, t) {
    return !e || t.length % 2 !== 0 ? !1 : (this._gl.uniform2uiv(e, t), !0);
  }
  /**
   * 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(e, t) {
    return !e || t.length % 3 !== 0 ? !1 : (this._gl.uniform3uiv(e, t), !0);
  }
  /**
   * 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(e, t) {
    return !e || t.length % 4 !== 0 ? !1 : (this._gl.uniform4uiv(e, t), !0);
  }
  /**
   * 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(e, t) {
    return !e || t.length < 1 ? !1 : (this._gl.uniform1fv(e, t), !0);
  }
  /**
   * 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(e, t) {
    return !e || t.length % 2 !== 0 ? !1 : (this._gl.uniform2fv(e, t), !0);
  }
  /**
   * 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(e, t) {
    return !e || t.length % 3 !== 0 ? !1 : (this._gl.uniform3fv(e, t), !0);
  }
  /**
   * 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(e, t) {
    return !e || t.length % 4 !== 0 ? !1 : (this._gl.uniform4fv(e, t), !0);
  }
  /**
   * 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(e, t) {
    return e ? (this._gl.uniformMatrix4fv(e, !1, t), !0) : !1;
  }
  /**
   * 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(e, t) {
    return e ? (this._gl.uniformMatrix3fv(e, !1, t), !0) : !1;
  }
  /**
   * 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(e, t) {
    return e ? (this._gl.uniformMatrix2fv(e, !1, t), !0) : !1;
  }
  /**
   * 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(e, t) {
    return e ? (this._gl.uniform1f(e, t), !0) : !1;
  }
  /**
   * 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(e, t, i) {
    return e ? (this._gl.uniform2f(e, t, i), !0) : !1;
  }
  /**
   * 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(e, t, i, s) {
    return e ? (this._gl.uniform3f(e, t, i, s), !0) : !1;
  }
  /**
   * 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(e, t, i, s, r) {
    return e ? (this._gl.uniform4f(e, t, i, s, r), !0) : !1;
  }
  // States
  /**
   * Apply all cached states (depth, culling, stencil and alpha)
   */
  applyStates() {
    if (this._depthCullingState.apply(this._gl), this._stencilStateComposer.apply(this._gl), this._alphaState.apply(this._gl), this._colorWriteChanged) {
      this._colorWriteChanged = !1;
      const e = this._colorWrite;
      this._gl.colorMask(e, e, e, e);
    }
  }
  /**
   * Enable or disable color writing
   * @param enable defines the state to set
   */
  setColorWrite(e) {
    e !== this._colorWrite && (this._colorWriteChanged = !0, this._colorWrite = e);
  }
  /**
   * 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;
  }
  // Textures
  /**
   * Clears the list of texture accessible through engine.
   * This can help preventing texture load conflict due to name collision.
   */
  clearInternalTexturesCache() {
    this._internalTexturesCache.length = 0;
  }
  /**
   * 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(e) {
    this.preventCacheWipeBetweenFrames && !e || (this._currentEffect = null, this._viewportCached.x = 0, this._viewportCached.y = 0, this._viewportCached.z = 0, this._viewportCached.w = 0, this._unbindVertexArrayObject(), e && (this._currentProgram = null, this.resetTextureCache(), this._stencilStateComposer.reset(), this._depthCullingState.reset(), this._depthCullingState.depthFunc = this._gl.LEQUAL, this._alphaState.reset(), this._alphaMode = 1, this._alphaEquation = 0, this._colorWrite = !0, this._colorWriteChanged = !0, 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 = !0, this.unbindAllAttributes()), this._resetVertexBufferBinding(), this._cachedIndexBuffer = null, this._cachedEffectForVertexBuffers = null, this.bindIndexBuffer(null));
  }
  /**
   * @internal
   */
  _getSamplingParameters(e, t) {
    const i = this._gl;
    let s = i.NEAREST, r = i.NEAREST;
    switch (e) {
      case 11:
        s = i.LINEAR, t ? r = i.LINEAR_MIPMAP_NEAREST : r = i.LINEAR;
        break;
      case 3:
        s = i.LINEAR, t ? r = i.LINEAR_MIPMAP_LINEAR : r = i.LINEAR;
        break;
      case 8:
        s = i.NEAREST, t ? r = i.NEAREST_MIPMAP_LINEAR : r = i.NEAREST;
        break;
      case 4:
        s = i.NEAREST, t ? r = i.NEAREST_MIPMAP_NEAREST : r = i.NEAREST;
        break;
      case 5:
        s = i.NEAREST, t ? r = i.LINEAR_MIPMAP_NEAREST : r = i.LINEAR;
        break;
      case 6:
        s = i.NEAREST, t ? r = i.LINEAR_MIPMAP_LINEAR : r = i.LINEAR;
        break;
      case 7:
        s = i.NEAREST, r = i.LINEAR;
        break;
      case 1:
        s = i.NEAREST, r = i.NEAREST;
        break;
      case 9:
        s = i.LINEAR, t ? r = i.NEAREST_MIPMAP_NEAREST : r = i.NEAREST;
        break;
      case 10:
        s = i.LINEAR, t ? r = i.NEAREST_MIPMAP_LINEAR : r = i.NEAREST;
        break;
      case 2:
        s = i.LINEAR, r = i.LINEAR;
        break;
      case 12:
        s = i.LINEAR, r = i.NEAREST;
        break;
    }
    return {
      min: r,
      mag: s
    };
  }
  /** @internal */
  _createTexture() {
    const e = this._gl.createTexture();
    if (!e)
      throw new Error("Unable to create texture");
    return e;
  }
  /** @internal */
  _createHardwareTexture() {
    return new rs(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(e, t, i = !0, s = De.Unknown) {
    var r;
    let n = !1, a = 0, o = 3, h = 5, c = !1, u = 1, d;
    t !== void 0 && typeof t == "object" ? (n = !!t.generateMipMaps, a = t.type === void 0 ? 0 : t.type, o = t.samplingMode === void 0 ? 3 : t.samplingMode, h = t.format === void 0 ? 5 : t.format, c = t.useSRGBBuffer === void 0 ? !1 : t.useSRGBBuffer, u = (r = t.samples) !== null && r !== void 0 ? r : 1, d = t.label) : n = !!t, c && (c = this._caps.supportSRGBBuffers && (this.webGLVersion > 1 || this.isWebGPU)), (a === 1 && !this._caps.textureFloatLinearFiltering || a === 2 && !this._caps.textureHalfFloatLinearFiltering) && (o = 1), a === 1 && !this._caps.textureFloat && (a = 0, S.Warn("Float textures are not supported. Type forced to TEXTURETYPE_UNSIGNED_BYTE"));
    const g = this._gl, f = new It(this, s), m = e.width || e, b = e.height || e, T = e.layers || 0, M = this._getSamplingParameters(o, n), v = T !== 0 ? g.TEXTURE_2D_ARRAY : g.TEXTURE_2D, A = this._getRGBABufferInternalSizedFormat(a, h, c), E = this._getInternalFormat(h), y = this._getWebGLTextureType(a);
    return this._bindTextureDirectly(v, f), T !== 0 ? (f.is2DArray = !0, g.texImage3D(v, 0, A, m, b, T, 0, E, y, null)) : g.texImage2D(v, 0, A, m, b, 0, E, y, null), g.texParameteri(v, g.TEXTURE_MAG_FILTER, M.mag), g.texParameteri(v, g.TEXTURE_MIN_FILTER, M.min), g.texParameteri(v, g.TEXTURE_WRAP_S, g.CLAMP_TO_EDGE), g.texParameteri(v, g.TEXTURE_WRAP_T, g.CLAMP_TO_EDGE), n && this._gl.generateMipmap(v), this._bindTextureDirectly(v, null), f._useSRGBBuffer = c, f.baseWidth = m, f.baseHeight = b, f.width = m, f.height = b, f.depth = T, f.isReady = !0, f.samples = u, f.generateMipMaps = n, f.samplingMode = o, f.type = a, f.format = h, f.label = d, this._internalTexturesCache.push(f), f;
  }
  /**
   * @internal
   */
  _getUseSRGBBuffer(e, t) {
    return e && this._caps.supportSRGBBuffers && (this.webGLVersion > 1 || this.isWebGPU || t);
  }
  _createTextureBase(e, t, i, s, r = 3, n = null, a = null, o, h, c = null, u = null, d = null, g = null, f, m, b) {
    e = e || "";
    const T = e.substr(0, 5) === "data:", M = e.substr(0, 5) === "blob:", v = T && e.indexOf(";base64,") !== -1, A = u || new It(this, De.Url);
    A !== u && (A.label = e.substring(0, 60));
    const E = e;
    this._transformTextureUrl && !v && !u && !c && (e = this._transformTextureUrl(e)), E !== e && (A._originalUrl = E);
    const y = e.lastIndexOf(".");
    let x = g || (y > -1 ? e.substring(y).toLowerCase() : ""), D = null;
    x.indexOf("?") > -1 && (x = x.split("?")[0]);
    for (const ee of se._TextureLoaders)
      if (ee.canLoad(x, f)) {
        D = ee;
        break;
      }
    s && s.addPendingData(A), A.url = e, A.generateMipMaps = !t, A.samplingMode = r, A.invertY = i, A._useSRGBBuffer = this._getUseSRGBBuffer(!!b, t), this._doNotHandleContextLost || (A._buffer = c);
    let W = null;
    n && !u && (W = A.onLoadedObservable.add(n)), u || this._internalTexturesCache.push(A);
    const ce = (ee, oe) => {
      s && s.removePendingData(A), e === E ? (W && A.onLoadedObservable.remove(W), J.UseFallbackTexture && this._createTextureBase(J.FallbackTexture, t, A.invertY, s, r, null, a, o, h, c, A), ee = (ee || "Unknown error") + (J.UseFallbackTexture ? " - Fallback texture was used" : ""), A.onErrorObservable.notifyObservers({ message: ee, exception: oe }), a && a(ee, oe)) : (S.Warn(`Failed to load ${e}, falling back to ${E}`), this._createTextureBase(E, t, A.invertY, s, r, n, a, o, h, c, A, d, g, f, m, b));
    };
    if (D) {
      const ee = (oe) => {
        D.loadData(oe, A, ($, Pe, Ae, Fe, Te, Me) => {
          Me ? ce("TextureLoader failed to load data") : o(A, x, s, { width: $, height: Pe }, A.invertY, !Ae, Fe, () => (Te(), !1), r);
        }, m);
      };
      c ? c instanceof ArrayBuffer ? ee(new Uint8Array(c)) : ArrayBuffer.isView(c) ? ee(c) : a && a("Unable to load: only ArrayBuffer or ArrayBufferView is supported", null) : this._loadFile(e, (oe) => ee(new Uint8Array(oe)), void 0, s ? s.offlineProvider : void 0, !0, (oe, $) => {
        ce("Unable to load " + (oe && oe.responseURL, $));
      });
    } else {
      const ee = (oe) => {
        M && !this._doNotHandleContextLost && (A._buffer = oe), o(A, x, s, oe, A.invertY, t, !1, h, r);
      };
      !T || v ? c && (typeof c.decoding == "string" || c.close) ? ee(c) : se._FileToolsLoadImage(e, ee, ce, s ? s.offlineProvider : null, f, A.invertY && this._features.needsInvertingBitmap ? { imageOrientation: "flipY" } : void 0) : typeof c == "string" || c instanceof ArrayBuffer || ArrayBuffer.isView(c) || c instanceof Blob ? se._FileToolsLoadImage(c, ee, ce, s ? s.offlineProvider : null, f, A.invertY && this._features.needsInvertingBitmap ? { imageOrientation: "flipY" } : void 0) : c && ee(c);
    }
    return A;
  }
  /**
   * 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(e, t, i, s, r = 3, n = null, a = null, o = null, h = null, c = null, u = null, d, g, f, m) {
    return this._createTextureBase(e, t, i, s, r, n, a, this._prepareWebGLTexture.bind(this), (b, T, M, v, A, E) => {
      const y = this._gl, x = M.width === b && M.height === T, D = c ? this._getInternalFormat(c, A._useSRGBBuffer) : v === ".jpg" && !A._useSRGBBuffer ? y.RGB : A._useSRGBBuffer ? y.SRGB8_ALPHA8 : y.RGBA;
      let V = c ? this._getInternalFormat(c) : v === ".jpg" && !A._useSRGBBuffer ? y.RGB : y.RGBA;
      if (A._useSRGBBuffer && this.webGLVersion === 1 && (V = D), x)
        return y.texImage2D(y.TEXTURE_2D, 0, D, V, y.UNSIGNED_BYTE, M), !1;
      const W = this._caps.maxTextureSize;
      if (M.width > W || M.height > W || !this._supportsHardwareTextureRescaling)
        return this._prepareWorkingCanvas(), !this._workingCanvas || !this._workingContext || (this._workingCanvas.width = b, this._workingCanvas.height = T, this._workingContext.drawImage(M, 0, 0, M.width, M.height, 0, 0, b, T), y.texImage2D(y.TEXTURE_2D, 0, D, V, y.UNSIGNED_BYTE, this._workingCanvas), A.width = b, A.height = T), !1;
      {
        const ce = new It(this, De.Temp);
        this._bindTextureDirectly(y.TEXTURE_2D, ce, !0), y.texImage2D(y.TEXTURE_2D, 0, D, V, y.UNSIGNED_BYTE, M), this._rescaleTexture(ce, A, s, D, () => {
          this._releaseTexture(ce), this._bindTextureDirectly(y.TEXTURE_2D, A, !0), E();
        });
      }
      return !0;
    }, o, h, c, u, d, g, m);
  }
  /**
   * 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
   * @internal
   */
  static _FileToolsLoadImage(e, t, i, s, r, n) {
    throw Y("FileTools");
  }
  /**
   * @internal
   */
  _rescaleTexture(e, t, i, s, r) {
  }
  /**
   * Creates a raw texture
   * @param data defines the data to store in the texture
   * @param width defines the width of the texture
   * @param height defines the height of the texture
   * @param format defines the format of the data
   * @param generateMipMaps defines if the engine should generate the mip levels
   * @param invertY defines if data must be stored with Y axis inverted
   * @param samplingMode defines the required sampling mode (Texture.NEAREST_SAMPLINGMODE by default)
   * @param compression defines the compression used (null by default)
   * @param type defines the type fo the data (Engine.TEXTURETYPE_UNSIGNED_INT by default)
   * @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(e, t, i, s, r, n, a, o = null, h = 0, c = 0, u = !1) {
    throw Y("Engine.RawTexture");
  }
  /**
   * Creates a new raw cube texture
   * @param data defines the array of data to use to create each face
   * @param size defines the size of the textures
   * @param format defines the format of the data
   * @param type defines the type of the data (like Engine.TEXTURETYPE_UNSIGNED_INT)
   * @param generateMipMaps  defines if the engine should generate the mip levels
   * @param invertY defines if data must be stored with Y axis inverted
   * @param samplingMode defines the required sampling mode (like Texture.NEAREST_SAMPLINGMODE)
   * @param compression defines the compression used (null by default)
   * @returns the cube texture as an InternalTexture
   */
  createRawCubeTexture(e, t, i, s, r, n, a, o = null) {
    throw Y("Engine.RawTexture");
  }
  /**
   * Creates a new raw 3D texture
   * @param data defines the data used to create the texture
   * @param width defines the width of the texture
   * @param height defines the height of the texture
   * @param depth defines the depth of the texture
   * @param format defines the format of the texture
   * @param generateMipMaps defines if the engine must generate mip levels
   * @param invertY defines if data must be stored with Y axis inverted
   * @param samplingMode defines the required sampling mode (like Texture.NEAREST_SAMPLINGMODE)
   * @param compression defines the compressed used (can be null)
   * @param textureType defines the compressed used (can be null)
   * @returns a new raw 3D texture (stored in an InternalTexture)
   */
  createRawTexture3D(e, t, i, s, r, n, a, o, h = null, c = 0) {
    throw Y("Engine.RawTexture");
  }
  /**
   * Creates a new raw 2D array texture
   * @param data defines the data used to create the texture
   * @param width defines the width of the texture
   * @param height defines the height of the texture
   * @param depth defines the number of layers of the texture
   * @param format defines the format of the texture
   * @param generateMipMaps defines if the engine must generate mip levels
   * @param invertY defines if data must be stored with Y axis inverted
   * @param samplingMode defines the required sampling mode (like Texture.NEAREST_SAMPLINGMODE)
   * @param compression defines the compressed used (can be null)
   * @param textureType defines the compressed used (can be null)
   * @returns a new raw 2D array texture (stored in an InternalTexture)
   */
  createRawTexture2DArray(e, t, i, s, r, n, a, o, h = null, c = 0) {
    throw Y("Engine.RawTexture");
  }
  /**
   * @internal
   */
  _unpackFlipY(e) {
    this._unpackFlipYCached !== e && (this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, e ? 1 : 0), this.enableUnpackFlipYCached && (this._unpackFlipYCached = e));
  }
  /** @internal */
  _getUnpackAlignement() {
    return this._gl.getParameter(this._gl.UNPACK_ALIGNMENT);
  }
  _getTextureTarget(e) {
    return e.isCube ? this._gl.TEXTURE_CUBE_MAP : e.is3D ? this._gl.TEXTURE_3D : e.is2DArray || e.isMultiview ? this._gl.TEXTURE_2D_ARRAY : 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(e, t, i = !1) {
    const s = this._getTextureTarget(t), r = this._getSamplingParameters(e, t.useMipMaps || i);
    this._setTextureParameterInteger(s, this._gl.TEXTURE_MAG_FILTER, r.mag, t), this._setTextureParameterInteger(s, this._gl.TEXTURE_MIN_FILTER, r.min), i && (t.generateMipMaps = !0, this._gl.generateMipmap(s)), this._bindTextureDirectly(s, null), t.samplingMode = e;
  }
  /**
   * 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(e, t, i, s = 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(e, t, i = null, s = null) {
    const r = this._getTextureTarget(e);
    t !== null && (this._setTextureParameterInteger(r, this._gl.TEXTURE_WRAP_S, this._getTextureWrapMode(t), e), e._cachedWrapU = t), i !== null && (this._setTextureParameterInteger(r, this._gl.TEXTURE_WRAP_T, this._getTextureWrapMode(i), e), e._cachedWrapV = i), (e.is2DArray || e.is3D) && s !== null && (this._setTextureParameterInteger(r, this._gl.TEXTURE_WRAP_R, this._getTextureWrapMode(s), e), e._cachedWrapR = s), this._bindTextureDirectly(r, null);
  }
  /**
   * @internal
   */
  _setupDepthStencilTexture(e, t, i, s, r, n = 1) {
    const a = t.width || t, o = t.height || t, h = t.layers || 0;
    e.baseWidth = a, e.baseHeight = o, e.width = a, e.height = o, e.is2DArray = h > 0, e.depth = h, e.isReady = !0, e.samples = n, e.generateMipMaps = !1, e.samplingMode = s ? 2 : 1, e.type = 0, e._comparisonFunction = r;
    const c = this._gl, u = this._getTextureTarget(e), d = this._getSamplingParameters(e.samplingMode, !1);
    c.texParameteri(u, c.TEXTURE_MAG_FILTER, d.mag), c.texParameteri(u, c.TEXTURE_MIN_FILTER, d.min), c.texParameteri(u, c.TEXTURE_WRAP_S, c.CLAMP_TO_EDGE), c.texParameteri(u, c.TEXTURE_WRAP_T, c.CLAMP_TO_EDGE), this.webGLVersion > 1 && (r === 0 ? (c.texParameteri(u, c.TEXTURE_COMPARE_FUNC, 515), c.texParameteri(u, c.TEXTURE_COMPARE_MODE, c.NONE)) : (c.texParameteri(u, c.TEXTURE_COMPARE_FUNC, r), c.texParameteri(u, c.TEXTURE_COMPARE_MODE, c.COMPARE_REF_TO_TEXTURE)));
  }
  /**
   * @internal
   */
  _uploadCompressedDataToTextureDirectly(e, t, i, s, r, n = 0, a = 0) {
    const o = this._gl;
    let h = o.TEXTURE_2D;
    if (e.isCube && (h = o.TEXTURE_CUBE_MAP_POSITIVE_X + n), e._useSRGBBuffer)
      switch (t) {
        case 37492:
        case 36196:
          this._caps.etc2 ? t = o.COMPRESSED_SRGB8_ETC2 : e._useSRGBBuffer = !1;
          break;
        case 37496:
          this._caps.etc2 ? t = o.COMPRESSED_SRGB8_ALPHA8_ETC2_EAC : e._useSRGBBuffer = !1;
          break;
        case 36492:
          t = o.COMPRESSED_SRGB_ALPHA_BPTC_UNORM_EXT;
          break;
        case 37808:
          t = o.COMPRESSED_SRGB8_ALPHA8_ASTC_4x4_KHR;
          break;
        case 33776:
          this._caps.s3tc_srgb ? t = o.COMPRESSED_SRGB_S3TC_DXT1_EXT : e._useSRGBBuffer = !1;
          break;
        case 33777:
          this._caps.s3tc_srgb ? t = o.COMPRESSED_SRGB_ALPHA_S3TC_DXT1_EXT : e._useSRGBBuffer = !1;
          break;
        case 33779:
          this._caps.s3tc_srgb ? t = o.COMPRESSED_SRGB_ALPHA_S3TC_DXT5_EXT : e._useSRGBBuffer = !1;
          break;
        default:
          e._useSRGBBuffer = !1;
          break;
      }
    this._gl.compressedTexImage2D(h, a, t, i, s, 0, r);
  }
  /**
   * @internal
   */
  _uploadDataToTextureDirectly(e, t, i = 0, s = 0, r, n = !1) {
    const a = this._gl, o = this._getWebGLTextureType(e.type), h = this._getInternalFormat(e.format), c = r === void 0 ? this._getRGBABufferInternalSizedFormat(e.type, e.format, e._useSRGBBuffer) : this._getInternalFormat(r, e._useSRGBBuffer);
    this._unpackFlipY(e.invertY);
    let u = a.TEXTURE_2D;
    e.isCube && (u = a.TEXTURE_CUBE_MAP_POSITIVE_X + i);
    const d = Math.round(Math.log(e.width) * Math.LOG2E), g = Math.round(Math.log(e.height) * Math.LOG2E), f = n ? e.width : Math.pow(2, Math.max(d - s, 0)), m = n ? e.height : Math.pow(2, Math.max(g - s, 0));
    a.texImage2D(u, s, c, f, m, 0, h, o, t);
  }
  /**
   * 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(e, t, i, s, r, n, a = 0, o = 0, h = !1) {
    const c = this._gl, u = this._getWebGLTextureType(e.type), d = this._getInternalFormat(e.format);
    this._unpackFlipY(e.invertY);
    let g = c.TEXTURE_2D, f = c.TEXTURE_2D;
    e.isCube && (f = c.TEXTURE_CUBE_MAP_POSITIVE_X + a, g = c.TEXTURE_CUBE_MAP), this._bindTextureDirectly(g, e, !0), c.texSubImage2D(f, o, i, s, r, n, d, u, t), h && this._gl.generateMipmap(f), this._bindTextureDirectly(g, null);
  }
  /**
   * @internal
   */
  _uploadArrayBufferViewToTexture(e, t, i = 0, s = 0) {
    const r = this._gl, n = e.isCube ? r.TEXTURE_CUBE_MAP : r.TEXTURE_2D;
    this._bindTextureDirectly(n, e, !0), this._uploadDataToTextureDirectly(e, t, i, s), this._bindTextureDirectly(n, null, !0);
  }
  _prepareWebGLTextureContinuation(e, t, i, s, r) {
    const n = this._gl;
    if (!n)
      return;
    const a = this._getSamplingParameters(r, !i);
    n.texParameteri(n.TEXTURE_2D, n.TEXTURE_MAG_FILTER, a.mag), n.texParameteri(n.TEXTURE_2D, n.TEXTURE_MIN_FILTER, a.min), !i && !s && n.generateMipmap(n.TEXTURE_2D), this._bindTextureDirectly(n.TEXTURE_2D, null), t && t.removePendingData(e), e.onLoadedObservable.notifyObservers(e), e.onLoadedObservable.clear();
  }
  _prepareWebGLTexture(e, t, i, s, r, n, a, o, h = 3) {
    const c = this.getCaps().maxTextureSize, u = Math.min(c, this.needPOTTextures ? se.GetExponentOfTwo(s.width, c) : s.width), d = Math.min(c, this.needPOTTextures ? se.GetExponentOfTwo(s.height, c) : s.height), g = this._gl;
    if (g) {
      if (!e._hardwareTexture) {
        i && i.removePendingData(e);
        return;
      }
      this._bindTextureDirectly(g.TEXTURE_2D, e, !0), this._unpackFlipY(r === void 0 ? !0 : !!r), e.baseWidth = s.width, e.baseHeight = s.height, e.width = u, e.height = d, e.isReady = !0, !o(u, d, s, t, e, () => {
        this._prepareWebGLTextureContinuation(e, i, n, a, h);
      }) && this._prepareWebGLTextureContinuation(e, i, n, a, h);
    }
  }
  /**
   * @internal
   */
  _setupFramebufferDepthAttachments(e, t, i, s, r = 1) {
    const n = this._gl;
    if (e && t)
      return this._createRenderBuffer(i, s, r, n.DEPTH_STENCIL, n.DEPTH24_STENCIL8, n.DEPTH_STENCIL_ATTACHMENT);
    if (t) {
      let a = n.DEPTH_COMPONENT16;
      return this._webGLVersion > 1 && (a = n.DEPTH_COMPONENT32F), this._createRenderBuffer(i, s, r, a, a, n.DEPTH_ATTACHMENT);
    }
    return e ? this._createRenderBuffer(i, s, r, n.STENCIL_INDEX8, n.STENCIL_INDEX8, n.STENCIL_ATTACHMENT) : null;
  }
  /**
   * @internal
   */
  _createRenderBuffer(e, t, i, s, r, n, a = !0) {
    const h = this._gl.createRenderbuffer();
    return this._updateRenderBuffer(h, e, t, i, s, r, n, a);
  }
  _updateRenderBuffer(e, t, i, s, r, n, a, o = !0) {
    const h = this._gl;
    return h.bindRenderbuffer(h.RENDERBUFFER, e), s > 1 && h.renderbufferStorageMultisample ? h.renderbufferStorageMultisample(h.RENDERBUFFER, s, n, t, i) : h.renderbufferStorage(h.RENDERBUFFER, r, t, i), h.framebufferRenderbuffer(h.FRAMEBUFFER, a, h.RENDERBUFFER, e), o && h.bindRenderbuffer(h.RENDERBUFFER, null), e;
  }
  /**
   * @internal
   */
  _releaseTexture(e) {
    var t;
    this._deleteTexture((t = e._hardwareTexture) === null || t === void 0 ? void 0 : t.underlyingResource), this.unbindAllTextures();
    const i = this._internalTexturesCache.indexOf(e);
    i !== -1 && this._internalTexturesCache.splice(i, 1), e._lodTextureHigh && e._lodTextureHigh.dispose(), e._lodTextureMid && e._lodTextureMid.dispose(), e._lodTextureLow && e._lodTextureLow.dispose(), e._irradianceTexture && e._irradianceTexture.dispose();
  }
  /**
   * @internal
   */
  _releaseRenderTargetWrapper(e) {
    const t = this._renderTargetWrapperCache.indexOf(e);
    t !== -1 && this._renderTargetWrapperCache.splice(t, 1);
  }
  _deleteTexture(e) {
    e && this._gl.deleteTexture(e);
  }
  _setProgram(e) {
    this._currentProgram !== e && (this._gl.useProgram(e), this._currentProgram = e);
  }
  /**
   * Binds an effect to the webGL context
   * @param effect defines the effect to bind
   */
  bindSamplers(e) {
    const t = e.getPipelineContext();
    this._setProgram(t.program);
    const i = e.getSamplers();
    for (let s = 0; s < i.length; s++) {
      const r = e.getUniform(i[s]);
      r && (this._boundUniforms[s] = r);
    }
    this._currentEffect = null;
  }
  _activateCurrentTexture() {
    this._currentTextureChannel !== this._activeChannel && (this._gl.activeTexture(this._gl.TEXTURE0 + this._activeChannel), this._currentTextureChannel = this._activeChannel);
  }
  /**
   * @internal
   */
  _bindTextureDirectly(e, t, i = !1, s = !1) {
    var r, n;
    let a = !1;
    const o = t && t._associatedChannel > -1;
    if (i && o && (this._activeChannel = t._associatedChannel), this._boundTexturesCache[this._activeChannel] !== t || s) {
      if (this._activateCurrentTexture(), t && t.isMultiview)
        throw console.error(e, t), "_bindTextureDirectly called with a multiview texture!";
      this._gl.bindTexture(e, (n = (r = t == null ? void 0 : t._hardwareTexture) === null || r === void 0 ? void 0 : r.underlyingResource) !== null && n !== void 0 ? n : null), this._boundTexturesCache[this._activeChannel] = t, t && (t._associatedChannel = this._activeChannel);
    } else
      i && (a = !0, this._activateCurrentTexture());
    return o && !i && this._bindSamplerUniformToChannel(t._associatedChannel, this._activeChannel), a;
  }
  /**
   * @internal
   */
  _bindTexture(e, t, i) {
    if (e === void 0)
      return;
    t && (t._associatedChannel = e), this._activeChannel = e;
    const s = t ? this._getTextureTarget(t) : this._gl.TEXTURE_2D;
    this._bindTextureDirectly(s, t);
  }
  /**
   * Unbind all textures from the webGL context
   */
  unbindAllTextures() {
    for (let e = 0; e < this._maxSimultaneousTextures; e++)
      this._activeChannel = e, this._bindTextureDirectly(this._gl.TEXTURE_2D, null), this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null), 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(e, t, i, s) {
    e !== void 0 && (t && (this._boundUniforms[e] = t), this._setTexture(e, i));
  }
  _bindSamplerUniformToChannel(e, t) {
    const i = this._boundUniforms[e];
    !i || i._currentState === t || (this._gl.uniform1i(i, t), i._currentState = t);
  }
  _getTextureWrapMode(e) {
    switch (e) {
      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(e, t, i = !1, s = !1, r = "") {
    if (!t)
      return this._boundTexturesCache[e] != null && (this._activeChannel = e, this._bindTextureDirectly(this._gl.TEXTURE_2D, null), this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null), this.webGLVersion > 1 && (this._bindTextureDirectly(this._gl.TEXTURE_3D, null), this._bindTextureDirectly(this._gl.TEXTURE_2D_ARRAY, null))), !1;
    if (t.video)
      this._activeChannel = e, t.update();
    else if (t.delayLoadState === 4)
      return t.delayLoad(), !1;
    let n;
    s ? n = t.depthStencilTexture : t.isReady() ? n = t.getInternalTexture() : t.isCube ? n = this.emptyCubeTexture : t.is3D ? n = this.emptyTexture3D : t.is2DArray ? n = this.emptyTexture2DArray : n = this.emptyTexture, !i && n && (n._associatedChannel = e);
    let a = !0;
    this._boundTexturesCache[e] === n && (i || this._bindSamplerUniformToChannel(n._associatedChannel, e), a = !1), this._activeChannel = e;
    const o = this._getTextureTarget(n);
    if (a && this._bindTextureDirectly(o, n, i), n && !n.isMultiview) {
      if (n.isCube && n._cachedCoordinatesMode !== t.coordinatesMode) {
        n._cachedCoordinatesMode = t.coordinatesMode;
        const h = t.coordinatesMode !== 3 && t.coordinatesMode !== 5 ? 1 : 0;
        t.wrapU = h, t.wrapV = h;
      }
      n._cachedWrapU !== t.wrapU && (n._cachedWrapU = t.wrapU, this._setTextureParameterInteger(o, this._gl.TEXTURE_WRAP_S, this._getTextureWrapMode(t.wrapU), n)), n._cachedWrapV !== t.wrapV && (n._cachedWrapV = t.wrapV, this._setTextureParameterInteger(o, this._gl.TEXTURE_WRAP_T, this._getTextureWrapMode(t.wrapV), n)), n.is3D && n._cachedWrapR !== t.wrapR && (n._cachedWrapR = t.wrapR, this._setTextureParameterInteger(o, this._gl.TEXTURE_WRAP_R, this._getTextureWrapMode(t.wrapR), n)), this._setAnisotropicLevel(o, n, t.anisotropicFilteringLevel);
    }
    return !0;
  }
  /**
   * 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(e, t, i, s) {
    if (!(e === void 0 || !t)) {
      (!this._textureUnits || this._textureUnits.length !== i.length) && (this._textureUnits = new Int32Array(i.length));
      for (let r = 0; r < i.length; r++) {
        const n = i[r].getInternalTexture();
        n ? (this._textureUnits[r] = e + r, n._associatedChannel = e + r) : this._textureUnits[r] = -1;
      }
      this._gl.uniform1iv(t, this._textureUnits);
      for (let r = 0; r < i.length; r++)
        this._setTexture(this._textureUnits[r], i[r], !0);
    }
  }
  /**
   * @internal
   */
  _setAnisotropicLevel(e, t, i) {
    const s = this._caps.textureAnisotropicFilterExtension;
    t.samplingMode !== 11 && t.samplingMode !== 3 && t.samplingMode !== 2 && (i = 1), s && t._cachedAnisotropicFilteringLevel !== i && (this._setTextureParameterFloat(e, s.TEXTURE_MAX_ANISOTROPY_EXT, Math.min(i, this._caps.maxAnisotropy), t), t._cachedAnisotropicFilteringLevel = i);
  }
  _setTextureParameterFloat(e, t, i, s) {
    this._bindTextureDirectly(e, s, !0, !0), this._gl.texParameterf(e, t, i);
  }
  _setTextureParameterInteger(e, t, i, s) {
    s && this._bindTextureDirectly(e, s, !0, !0), this._gl.texParameteri(e, t, i);
  }
  /**
   * Unbind all vertex attributes from the webGL context
   */
  unbindAllAttributes() {
    if (this._mustWipeVertexAttributes) {
      this._mustWipeVertexAttributes = !1;
      for (let e = 0; e < this._caps.maxVertexAttribs; e++)
        this.disableAttributeByIndex(e);
      return;
    }
    for (let e = 0, t = this._vertexAttribArraysEnabled.length; e < t; e++)
      e >= this._caps.maxVertexAttribs || !this._vertexAttribArraysEnabled[e] || this.disableAttributeByIndex(e);
  }
  /**
   * 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() {
    for (const e in this._compiledEffects) {
      const t = this._compiledEffects[e].getPipelineContext();
      this._deletePipelineContext(t);
    }
    this._compiledEffects = {};
  }
  /**
   * Dispose and release all associated resources
   */
  dispose() {
    var e;
    this._isDisposed = !0, this.stopRenderLoop(), this.onBeforeTextureInitObservable && this.onBeforeTextureInitObservable.clear(), this._emptyTexture && (this._releaseTexture(this._emptyTexture), this._emptyTexture = null), this._emptyCubeTexture && (this._releaseTexture(this._emptyCubeTexture), this._emptyCubeTexture = null), this._dummyFramebuffer && this._gl.deleteFramebuffer(this._dummyFramebuffer), this.releaseEffects(), (e = this.releaseComputeEffects) === null || e === void 0 || e.call(this), this.unbindAllAttributes(), this._boundUniforms = {}, Ie() && this._renderingCanvas && (this._doNotHandleContextLost || (this._renderingCanvas.removeEventListener("webglcontextlost", this._onContextLost), this._renderingCanvas.removeEventListener("webglcontextrestored", this._onContextRestored)), window.removeEventListener("resize", this._checkForMobile)), this._workingCanvas = null, this._workingContext = null, this._currentBufferPointers.length = 0, this._renderingCanvas = null, this._currentProgram = null, this._boundRenderFunction = null, Be.ResetCache();
    for (const t of this._activeRequests)
      t.abort();
    this.onDisposeObservable.notifyObservers(this), this.onDisposeObservable.clear();
  }
  /**
   * Attach a new callback raised when context lost event is fired
   * @param callback defines the callback to call
   */
  attachContextLostEvent(e) {
    this._renderingCanvas && this._renderingCanvas.addEventListener("webglcontextlost", e, !1);
  }
  /**
   * Attach a new callback raised when context restored event is fired
   * @param callback defines the callback to call
   */
  attachContextRestoredEvent(e) {
    this._renderingCanvas && this._renderingCanvas.addEventListener("webglcontextrestored", e, !1);
  }
  /**
   * 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() {
    return this._webGLVersion > 1 ? this._caps.colorBufferFloat : this._canRenderToFramebuffer(1);
  }
  _canRenderToHalfFloatFramebuffer() {
    return this._webGLVersion > 1 ? this._caps.colorBufferFloat : this._canRenderToFramebuffer(2);
  }
  // Thank you : http://stackoverflow.com/questions/28827511/webgl-ios-render-to-floating-point-texture
  _canRenderToFramebuffer(e) {
    const t = this._gl;
    for (; t.getError() !== t.NO_ERROR; )
      ;
    let i = !0;
    const s = t.createTexture();
    t.bindTexture(t.TEXTURE_2D, s), t.texImage2D(t.TEXTURE_2D, 0, this._getRGBABufferInternalSizedFormat(e), 1, 1, 0, t.RGBA, this._getWebGLTextureType(e), null), t.texParameteri(t.TEXTURE_2D, t.TEXTURE_MIN_FILTER, t.NEAREST), t.texParameteri(t.TEXTURE_2D, t.TEXTURE_MAG_FILTER, t.NEAREST);
    const r = t.createFramebuffer();
    t.bindFramebuffer(t.FRAMEBUFFER, r), t.framebufferTexture2D(t.FRAMEBUFFER, t.COLOR_ATTACHMENT0, t.TEXTURE_2D, s, 0);
    const n = t.checkFramebufferStatus(t.FRAMEBUFFER);
    if (i = i && n === t.FRAMEBUFFER_COMPLETE, i = i && t.getError() === t.NO_ERROR, i && (t.clear(t.COLOR_BUFFER_BIT), i = i && t.getError() === t.NO_ERROR), i) {
      t.bindFramebuffer(t.FRAMEBUFFER, null);
      const a = t.RGBA, o = t.UNSIGNED_BYTE, h = new Uint8Array(4);
      t.readPixels(0, 0, 1, 1, a, o, h), i = i && t.getError() === t.NO_ERROR;
    }
    for (t.deleteTexture(s), t.deleteFramebuffer(r), t.bindFramebuffer(t.FRAMEBUFFER, null); !i && t.getError() !== t.NO_ERROR; )
      ;
    return i;
  }
  /**
   * @internal
   */
  _getWebGLTextureType(e) {
    if (this._webGLVersion === 1) {
      switch (e) {
        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 (e) {
      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(e, t = !1) {
    let i = t ? this._gl.SRGB8_ALPHA8 : this._gl.RGBA;
    switch (e) {
      case 0:
        i = this._gl.ALPHA;
        break;
      case 1:
        i = this._gl.LUMINANCE;
        break;
      case 2:
        i = this._gl.LUMINANCE_ALPHA;
        break;
      case 6:
        i = this._gl.RED;
        break;
      case 7:
        i = this._gl.RG;
        break;
      case 4:
        i = t ? this._gl.SRGB : this._gl.RGB;
        break;
      case 5:
        i = t ? this._gl.SRGB8_ALPHA8 : this._gl.RGBA;
        break;
    }
    if (this._webGLVersion > 1)
      switch (e) {
        case 8:
          i = this._gl.RED_INTEGER;
          break;
        case 9:
          i = this._gl.RG_INTEGER;
          break;
        case 10:
          i = this._gl.RGB_INTEGER;
          break;
        case 11:
          i = this._gl.RGBA_INTEGER;
          break;
      }
    return i;
  }
  /**
   * @internal
   */
  _getRGBABufferInternalSizedFormat(e, t, i = !1) {
    if (this._webGLVersion === 1) {
      if (t !== void 0)
        switch (t) {
          case 0:
            return this._gl.ALPHA;
          case 1:
            return this._gl.LUMINANCE;
          case 2:
            return this._gl.LUMINANCE_ALPHA;
          case 4:
            return i ? this._gl.SRGB : this._gl.RGB;
        }
      return this._gl.RGBA;
    }
    switch (e) {
      case 3:
        switch (t) {
          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 (t) {
          case 6:
            return this._gl.R8;
          case 7:
            return this._gl.RG8;
          case 4:
            return i ? this._gl.SRGB8 : this._gl.RGB8;
          case 5:
            return i ? this._gl.SRGB8_ALPHA8 : this._gl.RGBA8;
          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 (t) {
          case 8:
            return this._gl.R16I;
          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 (t) {
          case 8:
            return this._gl.R16UI;
          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 (t) {
          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 (t) {
          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 (t) {
          case 6:
            return this._gl.R32F;
          case 7:
            return this._gl.RG32F;
          case 4:
            return this._gl.RGB32F;
          case 5:
            return this._gl.RGBA32F;
          default:
            return this._gl.RGBA32F;
        }
      case 2:
        switch (t) {
          case 6:
            return this._gl.R16F;
          case 7:
            return this._gl.RG16F;
          case 4:
            return this._gl.RGB16F;
          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 (t) {
          case 5:
            return this._gl.RGB10_A2;
          case 11:
            return this._gl.RGB10_A2UI;
          default:
            return this._gl.RGB10_A2;
        }
    }
    return i ? this._gl.SRGB8_ALPHA8 : this._gl.RGBA8;
  }
  /**
   * @internal
   */
  _getRGBAMultiSampleBufferFormat(e) {
    return e === 1 ? this._gl.RGBA32F : e === 2 ? this._gl.RGBA16F : this._gl.RGBA8;
  }
  /**
   * @internal
   */
  _loadFile(e, t, i, s, r, n) {
    const a = se._FileToolsLoadFile(e, t, i, s, r, n);
    return this._activeRequests.push(a), a.onCompleteObservable.add((o) => {
      this._activeRequests.splice(this._activeRequests.indexOf(o), 1);
    }), a;
  }
  /**
   * 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(e, t, i, s, r, n) {
    throw Y("FileTools");
  }
  /**
   * Reads pixels from the current frame buffer. Please note that this function can be slow
   * @param x defines the x coordinate of the rectangle where pixels must be read
   * @param y defines the y coordinate of the rectangle where pixels must be read
   * @param width defines the width of the rectangle where pixels must be read
   * @param height defines the height of the rectangle where pixels must be read
   * @param hasAlpha defines whether the output should have alpha or not (defaults to true)
   * @param flushRenderer true to flush the renderer from the pending commands before reading the pixels
   * @returns a ArrayBufferView promise (Uint8Array) containing RGBA colors
   */
  readPixels(e, t, i, s, r = !0, n = !0) {
    const a = r ? 4 : 3, o = r ? this._gl.RGBA : this._gl.RGB, h = new Uint8Array(s * i * a);
    return n && this.flushFramebuffer(), this._gl.readPixels(e, t, i, s, o, this._gl.UNSIGNED_BYTE, h), Promise.resolve(h);
  }
  /**
   * Gets a Promise<boolean> indicating if the engine can be instantiated (ie. if a webGL context can be found)
   */
  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
   * @ignorenaming
   */
  // eslint-disable-next-line @typescript-eslint/naming-convention
  static isSupported() {
    if (this._HasMajorPerformanceCaveat !== null)
      return !this._HasMajorPerformanceCaveat;
    if (this._IsSupported === null)
      try {
        const e = this._CreateCanvas(1, 1), t = e.getContext("webgl") || e.getContext("experimental-webgl");
        this._IsSupported = t != null && !!window.WebGLRenderingContext;
      } catch {
        this._IsSupported = !1;
      }
    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 e = this._CreateCanvas(1, 1), t = e.getContext("webgl", { failIfMajorPerformanceCaveat: !0 }) || e.getContext("experimental-webgl", { failIfMajorPerformanceCaveat: !0 });
        this._HasMajorPerformanceCaveat = !t;
      } catch {
        this._HasMajorPerformanceCaveat = !1;
      }
    return this._HasMajorPerformanceCaveat;
  }
  /**
   * Find the next highest power of two.
   * @param x Number to start search from.
   * @returns Next highest power of two.
   */
  static CeilingPOT(e) {
    return e--, e |= e >> 1, e |= e >> 2, e |= e >> 4, e |= e >> 8, e |= e >> 16, e++, e;
  }
  /**
   * Find the next lowest power of two.
   * @param x Number to start search from.
   * @returns Next lowest power of two.
   */
  static FloorPOT(e) {
    return e = e | e >> 1, e = e | e >> 2, e = e | e >> 4, e = e | e >> 8, e = e | e >> 16, e - (e >> 1);
  }
  /**
   * Find the nearest power of two.
   * @param x Number to start search from.
   * @returns Next nearest power of two.
   */
  static NearestPOT(e) {
    const t = se.CeilingPOT(e), i = se.FloorPOT(e);
    return t - e > e - i ? i : t;
  }
  /**
   * Get the closest exponent of two
   * @param value defines the value to approximate
   * @param max defines the maximum value to return
   * @param mode defines how to define the closest value
   * @returns closest exponent of two of the given value
   */
  static GetExponentOfTwo(e, t, i = 2) {
    let s;
    switch (i) {
      case 1:
        s = se.FloorPOT(e);
        break;
      case 2:
        s = se.NearestPOT(e);
        break;
      case 3:
      default:
        s = se.CeilingPOT(e);
        break;
    }
    return Math.min(s, t);
  }
  /**
   * Queue a new function into the requested animation frame pool (ie. this function will be executed by the browser (or the javascript engine) for the next frame)
   * @param func - the function to be called
   * @param requester - the object that will request the next frame. Falls back to window.
   * @returns frame number
   */
  static QueueNewFrame(e, t) {
    if (Ie()) {
      const { requestPostAnimationFrame: i, requestAnimationFrame: s } = t || window;
      if (typeof i == "function")
        return i(e);
      if (typeof s == "function")
        return s(e);
    } else if (typeof requestAnimationFrame == "function")
      return requestAnimationFrame(e);
    return setTimeout(e, 16);
  }
  /**
   * Gets host document
   * @returns the host document object
   */
  getHostDocument() {
    return this._renderingCanvas && this._renderingCanvas.ownerDocument ? this._renderingCanvas.ownerDocument : Wt() ? document : null;
  }
}
se.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"] },
  // 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"] }
];
se._TextureLoaders = [];
se.CollisionsEpsilon = 1e-3;
se._IsSupported = null;
se._HasMajorPerformanceCaveat = null;
class ns {
  /**
   * Polyfill for setImmediate
   * @param action defines the action to execute after the current execution block
   */
  static SetImmediate(e) {
    Ie() && window.setImmediate ? window.setImmediate(e) : setTimeout(e, 1);
  }
}
const as = new RegExp(/^data:([^,]+\/[^,]+)?;base64,/i);
class ei extends ct {
  /**
   * Creates a new LoadFileError
   * @param message defines the message of the error
   * @param object defines the optional web request
   */
  constructor(e, t) {
    super(e, vt.LoadFileError), this.name = "LoadFileError", Ot._setPrototypeOf(this, ei.prototype), t instanceof He ? this.request = t : this.file = t;
  }
}
class ti extends ct {
  /**
   * Creates a new LoadFileError
   * @param message defines the message of the error
   * @param request defines the optional web request
   */
  constructor(e, t) {
    super(e, vt.RequestFileError), this.request = t, this.name = "RequestFileError", Ot._setPrototypeOf(this, ti.prototype);
  }
}
class Si extends ct {
  /**
   * Creates a new ReadFileError
   * @param message defines the message of the error
   * @param file defines the optional file
   */
  constructor(e, t) {
    super(e, vt.ReadFileError), this.file = t, this.name = "ReadFileError", Ot._setPrototypeOf(this, Si.prototype);
  }
}
const xe = {
  /**
   * 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: Es.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
   */
  PreprocessUrl: (l) => l
}, os = (l) => (l = l.replace(/#/gm, "%23"), l), Di = (l, e) => {
  if (!(l && l.indexOf("data:") === 0) && xe.CorsBehavior)
    if (typeof xe.CorsBehavior == "string" || xe.CorsBehavior instanceof String)
      e.crossOrigin = xe.CorsBehavior;
    else {
      const t = xe.CorsBehavior(l);
      t && (e.crossOrigin = t);
    }
}, Fi = (l, e, t, i, s = "", r) => {
  var n;
  let a, o = !1;
  l instanceof ArrayBuffer || ArrayBuffer.isView(l) ? typeof Blob < "u" && typeof URL < "u" ? (a = URL.createObjectURL(new Blob([l], { type: s })), o = !0) : a = `data:${s};base64,` + vs(l) : l instanceof Blob ? (a = URL.createObjectURL(l), o = !0) : (a = os(l), a = xe.PreprocessUrl(l));
  const h = J.LastCreatedEngine, c = (y) => {
    if (t) {
      const x = a || l.toString();
      t(`Error while trying to load image: ${x.indexOf("http") === 0 || x.length <= 128 ? x : x.slice(0, 128) + "..."}`, y);
    }
  };
  if (typeof Image > "u" || (n = h == null ? void 0 : h._features.forceBitmapOverHTMLImageElement) !== null && n !== void 0 && n)
    return bt(a, (y) => {
      h.createImageBitmap(new Blob([y], { type: s }), { premultiplyAlpha: "none", ...r }).then((x) => {
        e(x), o && URL.revokeObjectURL(a);
      }).catch((x) => {
        t && t("Error while trying to load image: " + l, x);
      });
    }, void 0, i || void 0, !0, (y, x) => {
      c(x);
    }), null;
  const u = new Image();
  Di(a, u);
  const d = [], g = () => {
    d.forEach((y) => {
      y.target.addEventListener(y.name, y.handler);
    });
  }, f = () => {
    d.forEach((y) => {
      y.target.removeEventListener(y.name, y.handler);
    }), d.length = 0;
  }, m = () => {
    f(), e(u), o && u.src && URL.revokeObjectURL(u.src);
  }, b = (y) => {
    f(), c(y), o && u.src && URL.revokeObjectURL(u.src);
  }, T = (y) => {
    if (y.blockedURI !== u.src)
      return;
    f();
    const x = new Error(`CSP violation of policy ${y.effectiveDirective} ${y.blockedURI}. Current policy is ${y.originalPolicy}`);
    J.UseFallbackTexture = !1, c(x), o && u.src && URL.revokeObjectURL(u.src), u.src = "";
  };
  d.push({ target: u, name: "load", handler: m }), d.push({ target: u, name: "error", handler: b }), d.push({ target: document, name: "securitypolicyviolation", handler: T }), g();
  const M = a.substring(0, 5) === "blob:", v = a.substring(0, 5) === "data:", A = () => {
    M || v ? u.src = a : bt(a, (y, x, D) => {
      const V = !s && D ? D : s, W = new Blob([y], { type: V }), ce = URL.createObjectURL(W);
      o = !0, u.src = ce;
    }, void 0, i || void 0, !0, (y, x) => {
      c(x);
    });
  }, E = () => {
    i && i.loadImage(a, u);
  };
  if (!M && !v && i && i.enableTexturesOffline)
    i.open(E, A);
  else {
    if (a.indexOf("file:") !== -1) {
      const y = decodeURIComponent(a.substring(5).toLowerCase());
      if (kt.FilesToLoad[y] && typeof URL < "u") {
        try {
          let x;
          try {
            x = URL.createObjectURL(kt.FilesToLoad[y]);
          } catch {
            x = URL.createObjectURL(kt.FilesToLoad[y]);
          }
          u.src = x, o = !0;
        } catch {
          u.src = "";
        }
        return u;
      }
    }
    A();
  }
  return u;
}, zt = (l, e, t, i, s) => {
  const r = new FileReader(), n = {
    onCompleteObservable: new w(),
    abort: () => r.abort()
  };
  return r.onloadend = () => n.onCompleteObservable.notifyObservers(n), s && (r.onerror = () => {
    s(new Si(`Unable to read ${l.name}`, l));
  }), r.onload = (a) => {
    e(a.target.result);
  }, t && (r.onprogress = t), i ? r.readAsArrayBuffer(l) : r.readAsText(l), n;
}, bt = (l, e, t, i, s, r, n) => {
  if (l.name)
    return zt(l, e, t, s, r ? (c) => {
      r(void 0, c);
    } : void 0);
  const a = l;
  if (a.indexOf("file:") !== -1) {
    let c = decodeURIComponent(a.substring(5).toLowerCase());
    c.indexOf("./") === 0 && (c = c.substring(2));
    const u = kt.FilesToLoad[c];
    if (u)
      return zt(u, e, t, s, r ? (d) => r(void 0, new ei(d.message, d.file)) : void 0);
  }
  const { match: o, type: h } = Ks(a);
  if (o) {
    const c = {
      onCompleteObservable: new w(),
      abort: () => () => {
      }
    };
    try {
      const u = s ? Bi(a) : ls(a);
      e(u, void 0, h);
    } catch (u) {
      r ? r(void 0, u) : S.Error(u.message || "Failed to parse the Data URL");
    }
    return ns.SetImmediate(() => {
      c.onCompleteObservable.notifyObservers(c);
    }), c;
  }
  return wi(a, (c, u) => {
    e(c, u == null ? void 0 : u.responseURL, u == null ? void 0 : u.getResponseHeader("content-type"));
  }, t, i, s, r ? (c) => {
    r(c.request, new ei(c.message, c.request));
  } : void 0, n);
}, wi = (l, e, t, i, s, r, n) => {
  l = os(l), l = xe.PreprocessUrl(l);
  const a = xe.BaseUrl + l;
  let o = !1;
  const h = {
    onCompleteObservable: new w(),
    abort: () => o = !0
  }, c = () => {
    let u = new He(), d = null, g;
    const f = () => {
      u && (t && u.removeEventListener("progress", t), g && u.removeEventListener("readystatechange", g), u.removeEventListener("loadend", m));
    };
    let m = () => {
      f(), h.onCompleteObservable.notifyObservers(h), h.onCompleteObservable.clear(), t = void 0, g = null, m = null, r = void 0, n = void 0, e = void 0;
    };
    h.abort = () => {
      o = !0, m && m(), u && u.readyState !== (XMLHttpRequest.DONE || 4) && u.abort(), d !== null && (clearTimeout(d), d = null), u = null;
    };
    const b = (M) => {
      const v = M.message || "Unknown error";
      r && u ? r(new ti(v, u)) : S.Error(v);
    }, T = (M) => {
      if (u) {
        if (u.open("GET", a), n)
          try {
            n(u);
          } catch (v) {
            b(v);
            return;
          }
        s && (u.responseType = "arraybuffer"), t && u.addEventListener("progress", t), m && u.addEventListener("loadend", m), g = () => {
          if (!(o || !u) && u.readyState === (XMLHttpRequest.DONE || 4)) {
            if (g && u.removeEventListener("readystatechange", g), u.status >= 200 && u.status < 300 || u.status === 0 && (!Ie() || hs())) {
              try {
                e && e(s ? u.response : u.responseText, u);
              } catch (E) {
                b(E);
              }
              return;
            }
            const v = xe.DefaultRetryStrategy;
            if (v) {
              const E = v(a, u, M);
              if (E !== -1) {
                f(), u = new He(), d = setTimeout(() => T(M + 1), E);
                return;
              }
            }
            const A = new ti("Error status: " + u.status + " " + u.statusText + " - Unable to load " + a, u);
            r && r(A);
          }
        }, u.addEventListener("readystatechange", g), u.send();
      }
    };
    T(0);
  };
  if (i && i.enableSceneOffline) {
    const u = (g) => {
      g && g.status > 400 ? r && r(g) : c();
    }, d = () => {
      i && i.loadFile(xe.BaseUrl + l, (g) => {
        !o && e && e(g), h.onCompleteObservable.notifyObservers(h);
      }, t ? (g) => {
        !o && t && t(g);
      } : void 0, u, s);
    };
    i.open(d, u);
  } else
    c();
  return h;
}, hs = () => typeof location < "u" && location.protocol === "file:", Oi = (l) => as.test(l), Ks = (l) => {
  const e = as.exec(l);
  return e === null || e.length === 0 ? { match: !1, type: "" } : { match: !0, type: e[0].replace("data:", "").replace("base64,", "") };
};
function Bi(l) {
  return Is(l.split(",")[1]);
}
const ls = (l) => ss(l.split(",")[1]), Hs = () => {
  se._FileToolsLoadImage = Fi, se._FileToolsLoadFile = bt, xt._FileToolsLoadFile = bt;
};
Hs();
let Nt;
const Xs = (l, e, t, i, s, r, n, a, o, h) => {
  Nt = {
    DecodeBase64UrlToBinary: l,
    DecodeBase64UrlToString: e,
    DefaultRetryStrategy: t.DefaultRetryStrategy,
    BaseUrl: t.BaseUrl,
    CorsBehavior: t.CorsBehavior,
    PreprocessUrl: t.PreprocessUrl,
    IsBase64DataUrl: i,
    IsFileURL: s,
    LoadFile: r,
    LoadImage: n,
    ReadFile: a,
    RequestFile: o,
    SetCorsBehavior: h
  }, Object.defineProperty(Nt, "DefaultRetryStrategy", {
    get: function() {
      return t.DefaultRetryStrategy;
    },
    set: function(c) {
      t.DefaultRetryStrategy = c;
    }
  }), Object.defineProperty(Nt, "BaseUrl", {
    get: function() {
      return t.BaseUrl;
    },
    set: function(c) {
      t.BaseUrl = c;
    }
  }), Object.defineProperty(Nt, "PreprocessUrl", {
    get: function() {
      return t.PreprocessUrl;
    },
    set: function(c) {
      t.PreprocessUrl = c;
    }
  }), Object.defineProperty(Nt, "CorsBehavior", {
    get: function() {
      return t.CorsBehavior;
    },
    set: function(c) {
      t.CorsBehavior = c;
    }
  });
};
Xs(Bi, ls, xe, Oi, hs, bt, Fi, zt, wi, Di);
const cs = {};
function dt(l, e) {
  cs[l] = e;
}
function ii(l) {
  return cs[l];
}
class $t {
  /**
   * 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(e) {
    if (this.RegisteredExternalClasses && this.RegisteredExternalClasses[e])
      return this.RegisteredExternalClasses[e];
    const t = ii(e);
    if (t)
      return t;
    S.Warn(e + " not found, you may have missed an import.");
    const i = e.split(".");
    let s = window || this;
    for (let r = 0, n = i.length; r < n; r++)
      s = s[i[r]];
    return typeof s != "function" ? null : s;
  }
}
$t.RegisteredExternalClasses = {};
function Ys() {
  return "xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g, (l) => {
    const e = Math.random() * 16 | 0;
    return (l === "x" ? e : e & 3 | 8).toString(16);
  });
}
class k {
  /**
   * Gets or sets the base URL to use to load assets
   */
  static get BaseUrl() {
    return xe.BaseUrl;
  }
  static set BaseUrl(e) {
    xe.BaseUrl = e;
  }
  /**
   * Gets or sets the retry strategy to apply when an error happens while loading an asset
   */
  static get DefaultRetryStrategy() {
    return xe.DefaultRetryStrategy;
  }
  static set DefaultRetryStrategy(e) {
    xe.DefaultRetryStrategy = e;
  }
  /**
   * 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)
   */
  static get CorsBehavior() {
    return xe.CorsBehavior;
  }
  static set CorsBehavior(e) {
    xe.CorsBehavior = e;
  }
  /**
   * Gets or sets a global variable indicating if fallback texture must be used when a texture cannot be loaded
   * @ignorenaming
   */
  static get UseFallbackTexture() {
    return J.UseFallbackTexture;
  }
  static set UseFallbackTexture(e) {
    J.UseFallbackTexture = e;
  }
  /**
   * Use this object to register external classes like custom textures or material
   * to allow the loaders to instantiate them
   */
  static get RegisteredExternalClasses() {
    return $t.RegisteredExternalClasses;
  }
  static set RegisteredExternalClasses(e) {
    $t.RegisteredExternalClasses = e;
  }
  /**
   * Texture content used if a texture cannot loaded
   * @ignorenaming
   */
  // eslint-disable-next-line @typescript-eslint/naming-convention
  static get fallbackTexture() {
    return J.FallbackTexture;
  }
  // eslint-disable-next-line @typescript-eslint/naming-convention
  static set fallbackTexture(e) {
    J.FallbackTexture = e;
  }
  /**
   * 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(e, t, i, s, r, n) {
    const a = Math.abs(e) * i % i | 0, o = Math.abs(t) * s % s | 0, h = (a + o * i) * 4;
    n.r = r[h] / 255, n.g = r[h + 1] / 255, n.b = r[h + 2] / 255, n.a = r[h + 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(e, t, i) {
    return e * (1 - i) + t * i;
  }
  /**
   * 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(e) {
    return $t.Instantiate(e);
  }
  /**
   * Polyfill for setImmediate
   * @param action defines the action to execute after the current execution block
   */
  static SetImmediate(e) {
    ns.SetImmediate(e);
  }
  /**
   * 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(e) {
    let t = 1;
    do
      t *= 2;
    while (t < e);
    return t === e;
  }
  /**
   * 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(e) {
    return Math.fround ? Math.fround(e) : (k._TmpFloatArray[0] = e, k._TmpFloatArray[0]);
  }
  /**
   * Extracts the filename from a path
   * @param path defines the path to use
   * @returns the filename
   */
  static GetFilename(e) {
    const t = e.lastIndexOf("/");
    return t < 0 ? e : e.substring(t + 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(e, t = !1) {
    const i = e.lastIndexOf("/");
    return i < 0 ? t ? e : "" : e.substring(0, i + 1);
  }
  /**
   * Convert an angle in radians to degrees
   * @param angle defines the angle to convert
   * @returns the angle in degrees
   */
  static ToDegrees(e) {
    return e * 180 / Math.PI;
  }
  /**
   * Convert an angle in degrees to radians
   * @param angle defines the angle to convert
   * @returns the angle in radians
   */
  static ToRadians(e) {
    return e * 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(e, t, i = 0.9) {
    const s = this.ToRadians(e), r = this.ToRadians(t);
    return this.ToDegrees(Math.atan2((1 - i) * Math.sin(r) + i * Math.sin(s), (1 - i) * Math.cos(r) + i * Math.cos(s)));
  }
  /**
   * 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(e, t) {
    return t !== !0 && (e === void 0 || e == null) ? null : Array.isArray(e) ? e : [e];
  }
  /**
   * 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(e) {
    let t = "pointer";
    return Ie() && !window.PointerEvent && (t = "mouse"), e._badDesktopOS && !e._badOS && // And not ipad pros who claim to be macs...
    !(document && "ontouchend" in document) && (t = "mouse"), t;
  }
  /**
   * 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(e, t) {
    Di(e, t);
  }
  /**
   * 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(e, t) {
    t.referrerPolicy = e;
  }
  // External files
  /**
   * Removes unwanted characters from an url
   * @param url defines the url to clean
   * @returns the cleaned url
   */
  static CleanUrl(e) {
    return e = e.replace(/#/gm, "%23"), e;
  }
  /**
   * Gets or sets a function used to pre-process url before using them to load assets
   */
  static get PreprocessUrl() {
    return xe.PreprocessUrl;
  }
  static set PreprocessUrl(e) {
    xe.PreprocessUrl = e;
  }
  /**
   * 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(e, t, i, s, r, n) {
    return Fi(e, t, i, s, r, n);
  }
  /**
   * 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(e, t, i, s, r, n) {
    return bt(e, t, i, s, r, n);
  }
  /**
   * 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 LoadFileAsync(e, t = !0) {
    return new Promise((i, s) => {
      bt(e, (r) => {
        i(r);
      }, void 0, void 0, t, (r, n) => {
        s(n);
      });
    });
  }
  /**
   * 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 laod
   * @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 LoadScript(e, t, i, s) {
    if (typeof importScripts == "function") {
      try {
        importScripts(e), t();
      } catch (a) {
        i == null || i(`Unable to load script '${e}' in worker`, a);
      }
      return;
    } else if (!Ie()) {
      i == null || i(`Cannot load script '${e}' outside of a window or a worker`);
      return;
    }
    const r = document.getElementsByTagName("head")[0], n = document.createElement("script");
    n.setAttribute("type", "text/javascript"), n.setAttribute("src", e), s && (n.id = s), n.onload = () => {
      t && t();
    }, n.onerror = (a) => {
      i && i(`Unable to load script '${e}'`, a);
    }, r.appendChild(n);
  }
  /**
   * 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 LoadScriptAsync(e) {
    return new Promise((t, i) => {
      this.LoadScript(e, () => {
        t();
      }, (s, r) => {
        i(r || new Error(s));
      });
    });
  }
  /**
   * 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(e, t, i) {
    const s = new FileReader(), r = {
      onCompleteObservable: new w(),
      abort: () => s.abort()
    };
    return s.onloadend = () => {
      r.onCompleteObservable.notifyObservers(r);
    }, s.onload = (n) => {
      t(n.target.result);
    }, s.onprogress = i, s.readAsDataURL(e), r;
  }
  /**
   * 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(e, t, i, s, r) {
    return zt(e, t, i, s, r);
  }
  /**
   * Creates a data url from a given string content
   * @param content defines the content to convert
   * @returns the new data url link
   */
  static FileAsURL(e) {
    const t = new Blob([e]);
    return window.URL.createObjectURL(t);
  }
  /**
   * 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(e, t = 2) {
    return e.toFixed(t);
  }
  /**
   * 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(e, t, i, s) {
    Ci.DeepCopy(e, t, i, s);
  }
  /**
   * 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(e) {
    for (const t in e)
      if (Object.prototype.hasOwnProperty.call(e, t))
        return !1;
    return !0;
  }
  /**
   * 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(e, t) {
    for (let i = 0; i < t.length; i++) {
      const s = t[i];
      e.addEventListener(s.name, s.handler, !1);
      try {
        window.parent && window.parent.addEventListener(s.name, s.handler, !1);
      } catch {
      }
    }
  }
  /**
   * 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(e, t) {
    for (let i = 0; i < t.length; i++) {
      const s = t[i];
      e.removeEventListener(s.name, s.handler);
      try {
        e.parent && e.parent.removeEventListener(s.name, s.handler);
      } catch {
      }
    }
  }
  /**
   * 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
   * @returns a void promise
   */
  static async DumpFramebuffer(e, t, i, s, r = "image/png", n) {
    throw Y("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 defines the quality of the result
   */
  static DumpData(e, t, i, s, r = "image/png", n, a = !1, o = !1, h) {
    throw Y("DumpTools");
  }
  /**
   * 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 defines the quality of the result
   * @returns a promise that resolve to the final data
   */
  static DumpDataAsync(e, t, i, s = "image/png", r, n = !1, a = !1, o) {
    throw Y("DumpTools");
  }
  /**
   * 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
   * @param successCallback Defines the callback triggered once the data are available
   * @param mimeType Defines the mime type of the result
   * @param quality defines the quality of the result
   */
  static ToBlob(e, t, i = "image/png", s) {
    e.toBlob || (e.toBlob = function(r, n, a) {
      setTimeout(() => {
        const o = atob(this.toDataURL(n, a).split(",")[1]), h = o.length, c = new Uint8Array(h);
        for (let u = 0; u < h; u++)
          c[u] = o.charCodeAt(u);
        r(new Blob([c]));
      });
    }), e.toBlob(function(r) {
      t(r);
    }, i, s);
  }
  /**
   * Download a Blob object
   * @param blob the Blob object
   * @param fileName the file name to download
   * @returns
   */
  static DownloadBlob(e, t) {
    if ("download" in document.createElement("a")) {
      if (!t) {
        const i = /* @__PURE__ */ new Date();
        t = "screenshot_" + ((i.getFullYear() + "-" + (i.getMonth() + 1)).slice(2) + "-" + i.getDate() + "_" + i.getHours() + "-" + ("0" + i.getMinutes()).slice(-2)) + ".png";
      }
      k.Download(e, t);
    } else if (e && typeof URL < "u") {
      const i = URL.createObjectURL(e), s = window.open("");
      if (!s)
        return;
      const r = s.document.createElement("img");
      r.onload = function() {
        URL.revokeObjectURL(i);
      }, r.src = i, s.document.body.appendChild(r);
    }
  }
  /**
   * Encodes the canvas data to base 64 or automatically download the result if filename is defined
   * @param canvas canvas to get the data from.
   * @param successCallback defines the callback triggered once the data are available
   * @param mimeType defines the mime type of the result
   * @param fileName defines he filename to download. If present, the result will automatically be downloaded
   * @param quality defines the quality of the result
   */
  static EncodeScreenshotCanvasData(e, t, i = "image/png", s, r) {
    if (t) {
      const n = e.toDataURL(i, r);
      t(n);
    } else
      this.ToBlob(e, function(n) {
        n && k.DownloadBlob(n, s);
      }, i, r);
  }
  /**
   * Downloads a blob in the browser
   * @param blob defines the blob to download
   * @param fileName defines the name of the downloaded file
   */
  static Download(e, t) {
    if (typeof URL > "u")
      return;
    const i = window.URL.createObjectURL(e), s = document.createElement("a");
    document.body.appendChild(s), s.style.display = "none", s.href = i, s.download = t, s.addEventListener("click", () => {
      s.parentElement && s.parentElement.removeChild(s);
    }), s.click(), window.URL.revokeObjectURL(i);
  }
  /**
   * 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(e) {
    return typeof e[0] == "boolean" ? e[0] : typeof e[1] == "boolean" ? e[1] : !1;
  }
  /**
   * 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 <img> to display it
   * @param mimeType defines the MIME type of the screenshot image (default: image/png).
   * Check your browser for supported MIME types
   */
  // eslint-disable-next-line @typescript-eslint/no-unused-vars
  static CreateScreenshot(e, t, i, s, r = "image/png") {
    throw Y("ScreenshotTools");
  }
  /**
   * 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
   * @returns screenshot as a string of base64-encoded characters. This string can be assigned
   * to the src parameter of an <img> to display it
   */
  // eslint-disable-next-line @typescript-eslint/no-unused-vars
  static CreateScreenshotAsync(e, t, i, s = "image/png") {
    throw Y("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 <img> 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.
   */
  // eslint-disable-next-line @typescript-eslint/no-unused-vars
  static CreateScreenshotUsingRenderTarget(e, t, i, s, r = "image/png", n = 1, a = !1, o) {
    throw Y("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 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.
   * @returns screenshot as a string of base64-encoded characters. This string can be assigned
   * to the src parameter of an <img> to display it
   */
  // eslint-disable-next-line @typescript-eslint/no-unused-vars
  static CreateScreenshotUsingRenderTargetAsync(e, t, i, s = "image/png", r = 1, n = !1, a) {
    throw Y("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 Ys();
  }
  /**
   * 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(e) {
    return Oi(e);
  }
  /**
   * Decode the given base64 uri.
   * @deprecated Please use FileTools.DecodeBase64UrlToBinary instead.
   * @param uri The uri to decode
   * @returns The decoded base64 data.
   */
  static DecodeBase64(e) {
    return Bi(e);
  }
  /**
   * Gets a value indicating the number of loading errors
   * @ignorenaming
   */
  // eslint-disable-next-line @typescript-eslint/naming-convention
  static get errorsCount() {
    return S.errorsCount;
  }
  /**
   * Log a message to the console
   * @param message defines the message to log
   */
  static Log(e) {
    S.Log(e);
  }
  /**
   * Write a warning message to the console
   * @param message defines the message to log
   */
  static Warn(e) {
    S.Warn(e);
  }
  /**
   * Write an error message to the console
   * @param message defines the message to log
   */
  static Error(e) {
    S.Error(e);
  }
  /**
   * Gets current log cache (list of logs)
   */
  static get LogCache() {
    return S.LogCache;
  }
  /**
   * Clears the log cache
   */
  static ClearLogCache() {
    S.ClearLogCache();
  }
  /**
   * Sets the current log level (MessageLogLevel / WarningLogLevel / ErrorLogLevel)
   */
  static set LogLevels(e) {
    S.LogLevels = e;
  }
  /**
   * Sets the current performance log level
   */
  static set PerformanceLogLevel(e) {
    if ((e & k.PerformanceUserMarkLogLevel) === k.PerformanceUserMarkLogLevel) {
      k.StartPerformanceCounter = k._StartUserMark, k.EndPerformanceCounter = k._EndUserMark;
      return;
    }
    if ((e & k.PerformanceConsoleLogLevel) === k.PerformanceConsoleLogLevel) {
      k.StartPerformanceCounter = k._StartPerformanceConsole, k.EndPerformanceCounter = k._EndPerformanceConsole;
      return;
    }
    k.StartPerformanceCounter = k._StartPerformanceCounterDisabled, k.EndPerformanceCounter = k._EndPerformanceCounterDisabled;
  }
  // eslint-disable-next-line @typescript-eslint/no-unused-vars
  static _StartPerformanceCounterDisabled(e, t) {
  }
  // eslint-disable-next-line @typescript-eslint/no-unused-vars
  static _EndPerformanceCounterDisabled(e, t) {
  }
  static _StartUserMark(e, t = !0) {
    if (!k._Performance) {
      if (!Ie())
        return;
      k._Performance = window.performance;
    }
    !t || !k._Performance.mark || k._Performance.mark(e + "-Begin");
  }
  static _EndUserMark(e, t = !0) {
    !t || !k._Performance.mark || (k._Performance.mark(e + "-End"), k._Performance.measure(e, e + "-Begin", e + "-End"));
  }
  static _StartPerformanceConsole(e, t = !0) {
    t && (k._StartUserMark(e, t), console.time && console.time(e));
  }
  static _EndPerformanceConsole(e, t = !0) {
    t && (k._EndUserMark(e, t), console.timeEnd(e));
  }
  /**
   * Gets either window.performance.now() if supported or Date.now() else
   */
  static get Now() {
    return Et.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(e, t = !1) {
    let i = null;
    return !t && e.getClassName ? i = e.getClassName() : (e instanceof Object && (i = (t ? e : Object.getPrototypeOf(e)).constructor.__bjsclassName__), i || (i = typeof e)), i;
  }
  /**
   * 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(e, t) {
    for (const i of e)
      if (t(i))
        return i;
    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(e, t = !1) {
    let i = null, s = null;
    if (!t && e.getClassName)
      i = e.getClassName();
    else {
      if (e instanceof Object) {
        const r = t ? e : Object.getPrototypeOf(e);
        i = r.constructor.__bjsclassName__, s = r.constructor.__bjsmoduleName__;
      }
      i || (i = typeof e);
    }
    return i ? (s != null ? s + "." : "") + i : null;
  }
  /**
   * 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 DelayAsync(e) {
    return new Promise((t) => {
      setTimeout(() => {
        t();
      }, e);
    });
  }
  /**
   * Utility function to detect if the current user agent is Safari
   * @returns whether or not the current user agent is safari
   */
  static IsSafari() {
    return vi() ? /^((?!chrome|android).)*safari/i.test(navigator.userAgent) : !1;
  }
}
k.UseCustomRequestHeaders = !1;
k.CustomRequestHeaders = He.CustomRequestHeaders;
k._TmpFloatArray = new Float32Array(1);
k.GetDOMTextContent = Ii;
k.GetAbsoluteUrl = typeof document == "object" ? (l) => {
  const e = document.createElement("a");
  return e.href = l, e.href;
} : typeof URL == "function" && typeof location == "object" ? (l) => new URL(l, location.origin).href : () => {
  throw new Error("Unable to get absolute URL. Override BABYLON.Tools.GetAbsoluteUrl to a custom implementation for the current context.");
};
k.NoneLogLevel = S.NoneLogLevel;
k.MessageLogLevel = S.MessageLogLevel;
k.WarningLogLevel = S.WarningLogLevel;
k.ErrorLogLevel = S.ErrorLogLevel;
k.AllLogLevel = S.AllLogLevel;
k.IsWindowObjectExist = Ie;
k.PerformanceNoneLogLevel = 0;
k.PerformanceUserMarkLogLevel = 1;
k.PerformanceConsoleLogLevel = 2;
k.StartPerformanceCounter = k._StartPerformanceCounterDisabled;
k.EndPerformanceCounter = k._EndPerformanceCounterDisabled;
class si {
  /**
   * 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(e, t, i, s = 0) {
    this.iterations = e, this.index = s - 1, this._done = !1, this._fn = t, this._successCallback = i;
  }
  /**
   * Execute the next iteration. Must be called after the last iteration was finished.
   */
  executeNext() {
    this._done || (this.index + 1 < this.iterations ? (++this.index, this._fn(this)) : this.breakLoop());
  }
  /**
   * Break the loop and run the success callback.
   */
  breakLoop() {
    this._done = !0, 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(e, t, i, s = 0) {
    const r = new si(e, t, i, s);
    return r.executeNext(), r;
  }
  /**
   * 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(e, t, i, s, r, n = 0) {
    return si.Run(Math.ceil(e / t), (a) => {
      r && r() ? a.breakLoop() : setTimeout(() => {
        for (let o = 0; o < t; ++o) {
          const h = a.index * t + o;
          if (h >= e)
            break;
          if (i(h), r && r()) {
            a.breakLoop();
            break;
          }
        }
        a.executeNext();
      }, n);
    }, s);
  }
}
J.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";
class We {
  /**
   * Instantiates a Smart Array.
   * @param capacity defines the default capacity of the array.
   */
  constructor(e) {
    this.length = 0, this.data = new Array(e), this._id = We._GlobalId++;
  }
  /**
   * Pushes a value at the end of the active data.
   * @param value defines the object to push in the array.
   */
  push(e) {
    this.data[this.length++] = e, 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(e) {
    for (let t = 0; t < this.length; t++)
      e(this.data[t]);
  }
  /**
   * Sorts the full sets of data.
   * @param compareFn defines the comparison function to apply.
   */
  sort(e) {
    this.data.sort(e);
  }
  /**
   * 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(), this.data && (this.data.length = 0);
  }
  /**
   * Concats the active data with a given array.
   * @param array defines the data to concatenate with.
   */
  concat(e) {
    if (e.length !== 0) {
      this.length + e.length > this.data.length && (this.data.length = (this.length + e.length) * 2);
      for (let t = 0; t < e.length; t++)
        this.data[this.length++] = (e.data || e)[t];
    }
  }
  /**
   * 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(e) {
    const t = this.data.indexOf(e);
    return t >= this.length ? -1 : t;
  }
  /**
   * 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(e) {
    return this.indexOf(e) !== -1;
  }
}
We._GlobalId = 0;
class Tt extends We {
  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(e) {
    super.push(e), e.__smartArrayFlags || (e.__smartArrayFlags = {}), e.__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(e) {
    return e.__smartArrayFlags && e.__smartArrayFlags[this._id] === this._duplicateId ? !1 : (this.push(e), !0);
  }
  /**
   * 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(e) {
    if (e.length !== 0) {
      this.length + e.length > this.data.length && (this.data.length = (this.length + e.length) * 2);
      for (let t = 0; t < e.length; t++) {
        const i = (e.data || e)[t];
        this.pushNoDuplicate(i);
      }
    }
  }
}
class Vi {
  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(e) {
    this.clear(), e.forEach((t, i) => this.add(t, i));
  }
  /**
   * 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(e) {
    const t = this._data[e];
    if (t !== void 0)
      return t;
  }
  /**
   * 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(e, t) {
    let i = this.get(e);
    return i !== void 0 || (i = t(e), i && this.add(e, i)), i;
  }
  /**
   * 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(e, t) {
    const i = this.get(e);
    return i !== void 0 ? i : (this.add(e, t), t);
  }
  /**
   * 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(e) {
    return this._data[e] !== 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(e, t) {
    return this._data[e] !== void 0 ? !1 : (this._data[e] = t, ++this._count, !0);
  }
  /**
   * 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(e, t) {
    return this._data[e] === void 0 ? !1 : (this._data[e] = t, !0);
  }
  /**
   * 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(e) {
    const t = this.get(e);
    return t !== void 0 ? (delete this._data[e], --this._count, t) : 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(e) {
    return this.contains(e) ? (delete this._data[e], --this._count, !0) : !1;
  }
  /**
   * 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(e) {
    for (const t in this._data) {
      const i = this._data[t];
      e(t, i);
    }
  }
  /**
   * 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
   */
  first(e) {
    for (const t in this._data) {
      const i = this._data[t], s = e(t, i);
      if (s)
        return s;
    }
    return null;
  }
}
class At {
  /**
   * 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(e, t) {
    return e.match(/\([^()]*\)/g) ? e = e.replace(/\([^()]*\)/g, (i) => (i = i.slice(1, i.length - 1), At._HandleParenthesisContent(i, t))) : e = At._HandleParenthesisContent(e, t), e === "true" ? !0 : e === "false" ? !1 : At.Eval(e, t);
  }
  static _HandleParenthesisContent(e, t) {
    t = t || ((r) => r === "true");
    let i;
    const s = e.split("||");
    for (const r in s)
      if (Object.prototype.hasOwnProperty.call(s, r)) {
        let n = At._SimplifyNegation(s[r].trim());
        const a = n.split("&&");
        if (a.length > 1)
          for (let o = 0; o < a.length; ++o) {
            const h = At._SimplifyNegation(a[o].trim());
            if (h !== "true" && h !== "false" ? h[0] === "!" ? i = !t(h.substring(1)) : i = t(h) : i = h === "true", !i) {
              n = "false";
              break;
            }
          }
        if (i || n === "true") {
          i = !0;
          break;
        }
        n !== "true" && n !== "false" ? n[0] === "!" ? i = !t(n.substring(1)) : i = t(n) : i = n === "true";
      }
    return i ? "true" : "false";
  }
  static _SimplifyNegation(e) {
    return e = e.replace(/^[\s!]+/, (t) => (t = t.replace(/[\s]/g, () => ""), t.length % 2 ? "!" : "")), e = e.trim(), e === "!true" ? e = "false" : e === "!false" && (e = "true"), e;
  }
}
class re {
  /**
   * Adds support for tags on the given object
   * @param obj defines the object to use
   */
  static EnableFor(e) {
    e._tags = e._tags || {}, e.hasTags = () => re.HasTags(e), e.addTags = (t) => re.AddTagsTo(e, t), e.removeTags = (t) => re.RemoveTagsFrom(e, t), e.matchesTagsQuery = (t) => re.MatchesQuery(e, t);
  }
  /**
   * Removes tags support
   * @param obj defines the object to use
   */
  static DisableFor(e) {
    delete e._tags, delete e.hasTags, delete e.addTags, delete e.removeTags, delete e.matchesTagsQuery;
  }
  /**
   * Gets a boolean indicating if the given object has tags
   * @param obj defines the object to use
   * @returns a boolean
   */
  static HasTags(e) {
    if (!e._tags)
      return !1;
    const t = e._tags;
    for (const i in t)
      if (Object.prototype.hasOwnProperty.call(t, i))
        return !0;
    return !1;
  }
  /**
   * 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(e, t = !0) {
    if (!e._tags)
      return null;
    if (t) {
      const i = [];
      for (const s in e._tags)
        Object.prototype.hasOwnProperty.call(e._tags, s) && e._tags[s] === !0 && i.push(s);
      return i.join(" ");
    } else
      return e._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(e, t) {
    if (!t || typeof t != "string")
      return;
    t.split(" ").forEach(function(s) {
      re._AddTagTo(e, s);
    });
  }
  /**
   * @internal
   */
  static _AddTagTo(e, t) {
    t = t.trim(), !(t === "" || t === "true" || t === "false") && (t.match(/[\s]/) || t.match(/^([!]|([|]|[&]){2})/) || (re.EnableFor(e), e._tags[t] = !0));
  }
  /**
   * Removes specific tags from a specific object
   * @param obj defines the object to use
   * @param tagsString defines the tags to remove
   */
  static RemoveTagsFrom(e, t) {
    if (!re.HasTags(e))
      return;
    const i = t.split(" ");
    for (const s in i)
      re._RemoveTagFrom(e, i[s]);
  }
  /**
   * @internal
   */
  static _RemoveTagFrom(e, t) {
    delete e._tags[t];
  }
  /**
   * 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(e, t) {
    return t === void 0 ? !0 : t === "" ? re.HasTags(e) : At.Eval(t, (i) => re.HasTags(e) && e._tags[i]);
  }
}
class H {
  /**
   * Boolean : true if the absolute difference between a and b is lower than epsilon (default = 1.401298E-45)
   * @param a number
   * @param b number
   * @param epsilon (default = 1.401298E-45)
   * @returns true if the absolute difference between a and b is lower than epsilon (default = 1.401298E-45)
   */
  static WithinEpsilon(e, t, i = 1401298e-51) {
    return Math.abs(e - t) <= i;
  }
  /**
   * Returns a string : the upper case translation of the number i to hexadecimal.
   * @param i number
   * @returns the upper case translation of the number i to hexadecimal.
   */
  static ToHex(e) {
    const t = e.toString(16);
    return e <= 15 ? ("0" + t).toUpperCase() : t.toUpperCase();
  }
  /**
   * Returns -1 if value is negative and +1 is value is positive.
   * @param value the value
   * @returns the value itself if it's equal to zero.
   */
  static Sign(e) {
    return e = +e, e === 0 || isNaN(e) ? e : e > 0 ? 1 : -1;
  }
  /**
   * Returns the value itself if it's between min and max.
   * Returns min if the value is lower than min.
   * Returns max if the value is greater than max.
   * @param value the value to clmap
   * @param min the min value to clamp to (default: 0)
   * @param max the max value to clamp to (default: 1)
   * @returns the clamped value
   */
  static Clamp(e, t = 0, i = 1) {
    return Math.min(i, Math.max(t, e));
  }
  /**
   * the log2 of value.
   * @param value the value to compute log2 of
   * @returns the log2 of value.
   */
  static Log2(e) {
    return Math.log(e) * Math.LOG2E;
  }
  /**
   * the floor part of a log2 value.
   * @param value the value to compute log2 of
   * @returns the log2 of value.
   */
  static ILog2(e) {
    if (Math.log2)
      return Math.floor(Math.log2(e));
    if (e < 0)
      return NaN;
    if (e === 0)
      return -1 / 0;
    let t = 0;
    if (e < 1) {
      for (; e < 1; )
        t++, e = e * 2;
      t = -t;
    } else if (e > 1)
      for (; e > 1; )
        t++, e = Math.floor(e / 2);
    return t;
  }
  /**
   * Loops the value, so that it is never larger than length and never smaller than 0.
   *
   * This is similar to the modulo operator but it works with floating point numbers.
   * For example, using 3.0 for t and 2.5 for length, the result would be 0.5.
   * With t = 5 and length = 2.5, the result would be 0.0.
   * Note, however, that the behaviour is not defined for negative numbers as it is for the modulo operator
   * @param value the value
   * @param length the length
   * @returns the looped value
   */
  static Repeat(e, t) {
    return e - Math.floor(e / t) * t;
  }
  /**
   * Normalize the value between 0.0 and 1.0 using min and max values
   * @param value value to normalize
   * @param min max to normalize between
   * @param max min to normalize between
   * @returns the normalized value
   */
  static Normalize(e, t, i) {
    return (e - t) / (i - t);
  }
  /**
   * Denormalize the value from 0.0 and 1.0 using min and max values
   * @param normalized value to denormalize
   * @param min max to denormalize between
   * @param max min to denormalize between
   * @returns the denormalized value
   */
  static Denormalize(e, t, i) {
    return e * (i - t) + t;
  }
  /**
   * Calculates the shortest difference between two given angles given in degrees.
   * @param current current angle in degrees
   * @param target target angle in degrees
   * @returns the delta
   */
  static DeltaAngle(e, t) {
    let i = H.Repeat(t - e, 360);
    return i > 180 && (i -= 360), i;
  }
  /**
   * PingPongs the value t, so that it is never larger than length and never smaller than 0.
   * @param tx value
   * @param length length
   * @returns The returned value will move back and forth between 0 and length
   */
  static PingPong(e, t) {
    const i = H.Repeat(e, t * 2);
    return t - Math.abs(i - t);
  }
  /**
   * Interpolates between min and max with smoothing at the limits.
   *
   * This function interpolates between min and max in a similar way to Lerp. However, the interpolation will gradually speed up
   * from the start and slow down toward the end. This is useful for creating natural-looking animation, fading and other transitions.
   * @param from from
   * @param to to
   * @param tx value
   * @returns the smooth stepped value
   */
  static SmoothStep(e, t, i) {
    let s = H.Clamp(i);
    return s = -2 * s * s * s + 3 * s * s, t * s + e * (1 - s);
  }
  /**
   * Moves a value current towards target.
   *
   * This is essentially the same as Mathf.Lerp but instead the function will ensure that the speed never exceeds maxDelta.
   * Negative values of maxDelta pushes the value away from target.
   * @param current current value
   * @param target target value
   * @param maxDelta max distance to move
   * @returns resulting value
   */
  static MoveTowards(e, t, i) {
    let s = 0;
    return Math.abs(t - e) <= i ? s = t : s = e + H.Sign(t - e) * i, s;
  }
  /**
   * Same as MoveTowards but makes sure the values interpolate correctly when they wrap around 360 degrees.
   *
   * Variables current and target are assumed to be in degrees. For optimization reasons, negative values of maxDelta
   *  are not supported and may cause oscillation. To push current away from a target angle, add 180 to that angle instead.
   * @param current current value
   * @param target target value
   * @param maxDelta max distance to move
   * @returns resulting angle
   */
  static MoveTowardsAngle(e, t, i) {
    const s = H.DeltaAngle(e, t);
    let r = 0;
    return -i < s && s < i ? r = t : (t = e + s, r = H.MoveTowards(e, t, i)), r;
  }
  /**
   * Creates a new scalar with values linearly interpolated of "amount" between the start scalar and the end scalar.
   * @param start start value
   * @param end target value
   * @param amount amount to lerp between
   * @returns the lerped value
   */
  static Lerp(e, t, i) {
    return e + (t - e) * i;
  }
  /**
   * Same as Lerp but makes sure the values interpolate correctly when they wrap around 360 degrees.
   * The parameter t is clamped to the range [0, 1]. Variables a and b are assumed to be in degrees.
   * @param start start value
   * @param end target value
   * @param amount amount to lerp between
   * @returns the lerped value
   */
  static LerpAngle(e, t, i) {
    let s = H.Repeat(t - e, 360);
    return s > 180 && (s -= 360), e + s * H.Clamp(i);
  }
  /**
   * Calculates the linear parameter t that produces the interpolant value within the range [a, b].
   * @param a start value
   * @param b target value
   * @param value value between a and b
   * @returns the inverseLerp value
   */
  static InverseLerp(e, t, i) {
    let s = 0;
    return e != t ? s = H.Clamp((i - e) / (t - e)) : s = 0, s;
  }
  /**
   * Returns a new scalar located for "amount" (float) on the Hermite spline defined by the scalars "value1", "value3", "tangent1", "tangent2".
   * @see http://mathworld.wolfram.com/HermitePolynomial.html
   * @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 amount defines the amount on the interpolation spline (between 0 and 1)
   * @returns hermite result
   */
  static Hermite(e, t, i, s, r) {
    const n = r * r, a = r * n, o = 2 * a - 3 * n + 1, h = -2 * a + 3 * n, c = a - 2 * n + r, u = a - n;
    return e * o + i * h + t * c + s * u;
  }
  /**
   * Returns a new scalar which is the 1st derivative of the Hermite spline defined by the scalars "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(e, t, i, s, r) {
    const n = r * r;
    return (n - r) * 6 * e + (3 * n - 4 * r + 1) * t + (-n + r) * 6 * i + (3 * n - 2 * r) * s;
  }
  /**
   * Returns a random float number between and min and max values
   * @param min min value of random
   * @param max max value of random
   * @returns random value
   */
  static RandomRange(e, t) {
    return e === t ? e : Math.random() * (t - e) + e;
  }
  /**
   * This function returns percentage of a number in a given range.
   *
   * RangeToPercent(40,20,60) will return 0.5 (50%)
   * RangeToPercent(34,0,100) will return 0.34 (34%)
   * @param number to convert to percentage
   * @param min min range
   * @param max max range
   * @returns the percentage
   */
  static RangeToPercent(e, t, i) {
    return (e - t) / (i - t);
  }
  /**
   * This function returns number that corresponds to the percentage in a given range.
   *
   * PercentToRange(0.34,0,100) will return 34.
   * @param percent to convert to number
   * @param min min range
   * @param max max range
   * @returns the number
   */
  static PercentToRange(e, t, i) {
    return (i - t) * e + t;
  }
  /**
   * Returns the angle converted to equivalent value between -Math.PI and Math.PI radians.
   * @param angle The angle to normalize in radian.
   * @returns The converted angle.
   */
  static NormalizeRadians(e) {
    return e -= H.TwoPi * Math.floor((e + Math.PI) / H.TwoPi), e;
  }
  /**
   * Returns the highest common factor of two integers.
   * @param a first parameter
   * @param b second parameter
   * @returns HCF of a and b
   */
  static HCF(e, t) {
    const i = e % t;
    return i === 0 ? t : H.HCF(t, i);
  }
}
H.TwoPi = Math.PI * 2;
const qs = 1 / 2.2, Zs = 2.2, ye = 1e-3;
class Ee {
  /**
   * Returns an array of the given size filled with elements built from the given constructor and the parameters.
   * @param size the number of element to construct and put in the array.
   * @param itemBuilder a callback responsible for creating new instance of item. Called once per array entry.
   * @returns a new array filled with new objects.
   */
  static BuildArray(e, t) {
    const i = [];
    for (let s = 0; s < e; ++s)
      i.push(t());
    return i;
  }
  /**
   * Returns a tuple of the given size filled with elements built from the given constructor and the parameters.
   * @param size he number of element to construct and put in the tuple.
   * @param itemBuilder a callback responsible for creating new instance of item. Called once per tuple entry.
   * @returns a new tuple filled with new objects.
   */
  static BuildTuple(e, t) {
    return Ee.BuildArray(e, t);
  }
}
function js(l, e, t) {
  const i = l[e];
  if (typeof i != "function")
    return null;
  const s = function() {
    const r = l.length, n = s.previous.apply(l, arguments);
    return t(e, r), n;
  };
  return i.next = s, s.previous = i, l[e] = s, () => {
    const r = s.previous;
    if (!r)
      return;
    const n = s.next;
    n ? (r.next = n, n.previous = r) : (r.next = void 0, l[e] = r), s.next = void 0, s.previous = void 0;
  };
}
const Qs = ["push", "splice", "pop", "shift", "unshift"];
function $s(l, e) {
  const t = Qs.map((i) => js(l, i, e));
  return () => {
    t.forEach((i) => {
      i == null || i();
    });
  };
}
const Ue = (l) => parseInt(l.toString().replace(/\W/g, ""));
class le {
  /**
   * Creates a new Vector2 from the given x and y coordinates
   * @param x defines the first coordinate
   * @param y defines the second coordinate
   */
  constructor(e = 0, t = 0) {
    this.x = e, this.y = t;
  }
  /**
   * 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 e = Ue(this.x), t = Ue(this.y);
    let i = e;
    return i = i * 397 ^ t, i;
  }
  // 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(e, t = 0) {
    return e[t] = this.x, e[t + 1] = this.y, this;
  }
  /**
   * Update the current vector from an array
   * Example Playground https://playground.babylonjs.com/#QYBWV4#39
   * @param array defines the destination array
   * @param index defines the offset in the destination array
   * @returns the current Vector2
   */
  fromArray(e, t = 0) {
    return le.FromArrayToRef(e, t, this), 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() {
    const e = new Array();
    return this.toArray(e, 0), e;
  }
  /**
   * 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(e) {
    return this.x = e.x, this.y = e.y, 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(e, t) {
    return this.x = e, this.y = t, 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(e, t) {
    return this.copyFromFloats(e, t);
  }
  /**
   * 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(e) {
    return new this.constructor(this.x + e.x, this.y + e.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(e, t) {
    return t.x = this.x + e.x, t.y = this.y + e.y, t;
  }
  /**
   * 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(e) {
    return this.x += e.x, this.y += e.y, 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(e) {
    return new this.constructor(this.x + e.x, this.y + e.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(e) {
    return new this.constructor(this.x - e.x, this.y - e.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(e, t) {
    return t.x = this.x - e.x, t.y = this.y - e.y, t;
  }
  /**
   * 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(e) {
    return this.x -= e.x, this.y -= e.y, 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(e) {
    return this.x *= e.x, this.y *= e.y, 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(e) {
    return new this.constructor(this.x * e.x, this.y * e.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(e, t) {
    return t.x = this.x * e.x, t.y = this.y * e.y, t;
  }
  /**
   * 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(e, t) {
    return new this.constructor(this.x * e, this.y * t);
  }
  /**
   * 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(e) {
    return new this.constructor(this.x / e.x, this.y / e.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(e, t) {
    return t.x = this.x / e.x, t.y = this.y / e.y, t;
  }
  /**
   * 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(e) {
    return this.divideToRef(e, this);
  }
  /**
   * Gets a new Vector2 with current Vector2 negated coordinates
   * Example Playground https://playground.babylonjs.com/#QYBWV4#22
   * @returns a new Vector2
   */
  negate() {
    return new this.constructor(-this.x, -this.y);
  }
  /**
   * Negate this vector in place
   * Example Playground https://playground.babylonjs.com/#QYBWV4#23
   * @returns this
   */
  negateInPlace() {
    return this.x *= -1, this.y *= -1, 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 Vector3 object where to store the result
   * @returns the result
   */
  negateToRef(e) {
    return e.copyFromFloats(this.x * -1, this.y * -1);
  }
  /**
   * 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(e) {
    return this.x *= e, this.y *= e, 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(e) {
    const t = new this.constructor(0, 0);
    return this.scaleToRef(e, t), t;
  }
  /**
   * 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(e, t) {
    return t.x = this.x * e, t.y = this.y * e, t;
  }
  /**
   * 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(e, t) {
    return t.x += this.x * e, t.y += this.y * e, t;
  }
  /**
   * 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(e) {
    return e && this.x === e.x && this.y === e.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(e, t = ye) {
    return e && H.WithinEpsilon(this.x, e.x, t) && H.WithinEpsilon(this.y, e.y, t);
  }
  /**
   * 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 this.constructor(Math.floor(this.x), Math.floor(this.y));
  }
  /**
   * 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 this.constructor(this.x - Math.floor(this.x), this.y - Math.floor(this.y));
  }
  /**
   * 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(e, t) {
    const i = Math.cos(e), s = Math.sin(e), r = i * this.x - s * this.y, n = s * this.x + i * this.y;
    return t.x = r, t.y = n, t;
  }
  // 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 le.NormalizeToRef(this, this), this;
  }
  /**
   * Gets a new Vector2 copied from the Vector2
   * Example Playground https://playground.babylonjs.com/#QYBWV4#20
   * @returns a new Vector2
   */
  clone() {
    return new this.constructor(this.x, this.y);
  }
  // Statics
  /**
   * Gets a new Vector2(0, 0)
   * @returns a new Vector2
   */
  static Zero() {
    return new le(0, 0);
  }
  /**
   * Gets a new Vector2(1, 1)
   * @returns a new Vector2
   */
  static One() {
    return new le(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(e = 0, t = 1) {
    return new le(H.RandomRange(e, t), H.RandomRange(e, t));
  }
  /**
   * Gets a zero Vector2 that must not be updated
   */
  static get ZeroReadOnly() {
    return le._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(e, t = 0) {
    return new le(e[t], e[t + 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(e, t, i) {
    return i.x = e[t], i.y = e[t + 1], i;
  }
  /**
   * 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(e, t, i, s, r) {
    const n = r * r, a = r * n, o = 0.5 * (2 * t.x + (-e.x + i.x) * r + (2 * e.x - 5 * t.x + 4 * i.x - s.x) * n + (-e.x + 3 * t.x - 3 * i.x + s.x) * a), h = 0.5 * (2 * t.y + (-e.y + i.y) * r + (2 * e.y - 5 * t.y + 4 * i.y - s.y) * n + (-e.y + 3 * t.y - 3 * i.y + s.y) * a);
    return new e.constructor(o, h);
  }
  /**
   * 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(e, t, i) {
    let s = e.x;
    s = s > i.x ? i.x : s, s = s < t.x ? t.x : s;
    let r = e.y;
    return r = r > i.y ? i.y : r, r = r < t.y ? t.y : r, new e.constructor(s, r);
  }
  /**
   * 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(e, t, i, s, r) {
    const n = r * r, a = r * n, o = 2 * a - 3 * n + 1, h = -2 * a + 3 * n, c = a - 2 * n + r, u = a - n, d = e.x * o + i.x * h + t.x * c + s.x * u, g = e.y * o + i.y * h + t.y * c + s.y * u;
    return new e.constructor(d, g);
  }
  /**
   * 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(e, t, i, s, r) {
    const n = new e.constructor();
    return this.Hermite1stDerivativeToRef(e, t, i, s, r, n), n;
  }
  /**
   * 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(e, t, i, s, r, n) {
    const a = r * r;
    return n.x = (a - r) * 6 * e.x + (3 * a - 4 * r + 1) * t.x + (-a + r) * 6 * i.x + (3 * a - 2 * r) * s.x, n.y = (a - r) * 6 * e.y + (3 * a - 4 * r + 1) * t.y + (-a + r) * 6 * i.y + (3 * a - 2 * r) * s.y, n;
  }
  /**
   * 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(e, t, i) {
    const s = e.x + (t.x - e.x) * i, r = e.y + (t.y - e.y) * i;
    return new e.constructor(s, r);
  }
  /**
   * 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(e, t) {
    return e.x * t.x + e.y * t.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(e) {
    const t = new e.constructor();
    return this.NormalizeToRef(e, t), t;
  }
  /**
   * 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(e, t) {
    const i = e.length();
    return i === 0 || (t.x = e.x / i, t.y = e.y / i), t;
  }
  /**
   * 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(e, t) {
    const i = e.x < t.x ? e.x : t.x, s = e.y < t.y ? e.y : t.y;
    return new e.constructor(i, s);
  }
  /**
   * 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(e, t) {
    const i = e.x > t.x ? e.x : t.x, s = e.y > t.y ? e.y : t.y;
    return new e.constructor(i, s);
  }
  /**
   * 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(e, t) {
    const i = new e.constructor();
    return le.TransformToRef(e, t, i), i;
  }
  /**
   * 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(e, t, i) {
    const s = t.m, r = e.x * s[0] + e.y * s[4] + s[12], n = e.x * s[1] + e.y * s[5] + s[13];
    return i.x = r, i.y = n, i;
  }
  /**
   * 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(e, t, i, s) {
    const r = 0.5 * (-i.y * s.x + t.y * (-i.x + s.x) + t.x * (i.y - s.y) + i.x * s.y), n = r < 0 ? -1 : 1, a = (t.y * s.x - t.x * s.y + (s.y - t.y) * e.x + (t.x - s.x) * e.y) * n, o = (t.x * i.y - t.y * i.x + (t.y - i.y) * e.x + (i.x - t.x) * e.y) * n;
    return a > 0 && o > 0 && a + o < 2 * r * n;
  }
  /**
   * 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(e, t) {
    return Math.sqrt(le.DistanceSquared(e, t));
  }
  /**
   * 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(e, t) {
    const i = e.x - t.x, s = e.y - t.y;
    return i * i + s * s;
  }
  /**
   * 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(e, t) {
    const i = new e.constructor();
    return le.CenterToRef(e, t, i);
  }
  /**
   * 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(e, t, i) {
    return i.copyFromFloats((e.x + t.x) / 2, (e.y + t.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(e, t, i) {
    const s = le.DistanceSquared(t, i);
    if (s === 0)
      return le.Distance(e, t);
    const r = i.subtract(t), n = Math.max(0, Math.min(1, le.Dot(e.subtract(t), r) / s)), a = t.add(r.multiplyByFloats(n, n));
    return le.Distance(e, a);
  }
}
le._ZeroReadOnly = le.Zero();
class p {
  /** Gets or sets the x coordinate */
  get x() {
    return this._x;
  }
  set x(e) {
    this._x = e, this._isDirty = !0;
  }
  /** Gets or sets the y coordinate */
  get y() {
    return this._y;
  }
  set y(e) {
    this._y = e, this._isDirty = !0;
  }
  /** Gets or sets the z coordinate */
  get z() {
    return this._z;
  }
  set z(e) {
    this._z = e, this._isDirty = !0;
  }
  /**
   * 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(e = 0, t = 0, i = 0) {
    this._isDirty = !0, this._x = e, this._y = t, this._z = i;
  }
  /**
   * 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 e = Ue(this._x), t = Ue(this._y), i = Ue(this._z);
    let s = e;
    return s = s * 397 ^ t, s = s * 397 ^ i, s;
  }
  // 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() {
    const e = [];
    return this.toArray(e, 0), e;
  }
  /**
   * 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(e, t = 0) {
    return e[t] = this._x, e[t + 1] = this._y, e[t + 2] = this._z, this;
  }
  /**
   * Update the current vector from an array
   * Example Playground https://playground.babylonjs.com/#R1F8YU#24
   * @param array defines the destination array
   * @param index defines the offset in the destination array
   * @returns the current Vector3
   */
  fromArray(e, t = 0) {
    return p.FromArrayToRef(e, t, this), 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 X.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(e) {
    return this.addInPlaceFromFloats(e._x, e._y, e._z);
  }
  /**
   * 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(e, t, i) {
    return this._x += e, this._y += t, this._z += i, this._isDirty = !0, 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(e) {
    return new this.constructor(this._x + e._x, this._y + e._y, this._z + e._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(e, t) {
    return t.copyFromFloats(this._x + e._x, this._y + e._y, this._z + e._z);
  }
  /**
   * 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(e) {
    return this._x -= e._x, this._y -= e._y, this._z -= e._z, this._isDirty = !0, 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(e) {
    return new this.constructor(this._x - e._x, this._y - e._y, this._z - e._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(e, t) {
    return this.subtractFromFloatsToRef(e._x, e._y, e._z, t);
  }
  /**
   * 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(e, t, i) {
    return new this.constructor(this._x - e, this._y - t, this._z - i);
  }
  /**
   * 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(e, t, i, s) {
    return s.copyFromFloats(this._x - e, this._y - t, this._z - i);
  }
  /**
   * 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 this.constructor(-this._x, -this._y, -this._z);
  }
  /**
   * Negate this vector in place
   * Example Playground https://playground.babylonjs.com/#R1F8YU#36
   * @returns this
   */
  negateInPlace() {
    return this._x *= -1, this._y *= -1, this._z *= -1, this._isDirty = !0, 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(e) {
    return e.copyFromFloats(this._x * -1, this._y * -1, this._z * -1);
  }
  /**
   * 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(e) {
    return this._x *= e, this._y *= e, this._z *= e, this._isDirty = !0, 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(e) {
    return new this.constructor(this._x * e, this._y * e, this._z * e);
  }
  /**
   * 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(e, t) {
    return t.copyFromFloats(this._x * e, this._y * e, this._z * e);
  }
  /**
   * 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(e) {
    const t = this.length();
    let i = Math.acos(this.y / t);
    const s = Math.atan2(this.z, this.x);
    i > Math.PI / 2 ? i -= Math.PI / 2 : i += Math.PI / 2;
    const r = t * Math.sin(i) * Math.cos(s), n = t * Math.cos(i), a = t * Math.sin(i) * Math.sin(s);
    return e.set(r, n, a), e;
  }
  /**
   * 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(e, t) {
    const i = e._w * this._x + e._y * this._z - e._z * this._y, s = e._w * this._y + e._z * this._x - e._x * this._z, r = e._w * this._z + e._x * this._y - e._y * this._x, n = -e._x * this._x - e._y * this._y - e._z * this._z;
    return t._x = i * e._w + n * -e._x + s * -e._z - r * -e._y, t._y = s * e._w + n * -e._y + r * -e._x - i * -e._z, t._z = r * e._w + n * -e._z + i * -e._y - s * -e._x, t._isDirty = !0, t;
  }
  /**
   * 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(e) {
    return this.applyRotationQuaternionToRef(e, 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(e) {
    return this.applyRotationQuaternionToRef(e, new this.constructor());
  }
  /**
   * 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(e, t) {
    return t.addInPlaceFromFloats(this._x * e, this._y * e, this._z * e);
  }
  /**
   * 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(e, t) {
    const i = new this.constructor();
    return this.projectOnPlaneToRef(e, t, i), i;
  }
  /**
   * 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(e, t, i) {
    const s = e.normal, r = e.d, n = N.Vector3[0];
    this.subtractToRef(t, n), n.normalize();
    const a = p.Dot(n, s);
    if (Math.abs(a) < Math.pow(10, -10))
      i.setAll(1 / 0);
    else {
      const o = -(p.Dot(t, s) + r) / a, h = n.scaleInPlace(o);
      t.addToRef(h, i);
    }
    return i;
  }
  /**
   * 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(e) {
    return e && this._x === e._x && this._y === e._y && this._z === e._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(e, t = ye) {
    return e && H.WithinEpsilon(this._x, e._x, t) && H.WithinEpsilon(this._y, e._y, t) && H.WithinEpsilon(this._z, e._z, t);
  }
  /**
   * 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(e, t, i) {
    return this._x === e && this._y === t && this._z === i;
  }
  /**
   * 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(e) {
    return this._x *= e._x, this._y *= e._y, this._z *= e._z, this._isDirty = !0, 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(e) {
    return this.multiplyByFloats(e._x, e._y, e._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(e, t) {
    return t.copyFromFloats(this._x * e._x, this._y * e._y, this._z * e._z);
  }
  /**
   * 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(e, t, i) {
    return new this.constructor(this._x * e, this._y * t, this._z * i);
  }
  /**
   * 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(e) {
    return new this.constructor(this._x / e._x, this._y / e._y, this._z / e._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(e, t) {
    return t.copyFromFloats(this._x / e._x, this._y / e._y, this._z / e._z);
  }
  /**
   * 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(e) {
    return this.divideToRef(e, 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(e) {
    return this.minimizeInPlaceFromFloats(e._x, e._y, e._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(e) {
    return this.maximizeInPlaceFromFloats(e._x, e._y, e._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(e, t, i) {
    return e < this._x && (this.x = e), t < this._y && (this.y = t), i < this._z && (this.z = i), 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(e, t, i) {
    return e > this._x && (this.x = e), t > this._y && (this.y = t), i > this._z && (this.z = i), 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 the vector is non uniform to a certain number of decimal places
   */
  isNonUniformWithinEpsilon(e) {
    const t = Math.abs(this._x), i = Math.abs(this._y);
    if (!H.WithinEpsilon(t, i, e))
      return !0;
    const s = Math.abs(this._z);
    return !H.WithinEpsilon(t, s, e) || !H.WithinEpsilon(i, s, e);
  }
  /**
   * Gets a boolean indicating that the vector is non uniform meaning x, y or z are not all the same
   */
  get isNonUniform() {
    const e = Math.abs(this._x), t = Math.abs(this._y);
    if (e !== t)
      return !0;
    const i = Math.abs(this._z);
    return e !== i;
  }
  /**
   * Gets a new Vector3 from current Vector3 floored values
   * Example Playground https://playground.babylonjs.com/#R1F8YU#22
   * @returns a new Vector3
   */
  floor() {
    return new this.constructor(Math.floor(this._x), Math.floor(this._y), Math.floor(this._z));
  }
  /**
   * Gets a new Vector3 from current Vector3 fractional values
   * Example Playground https://playground.babylonjs.com/#R1F8YU#23
   * @returns a new Vector3
   */
  fract() {
    return new this.constructor(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._x * this._x + this._y * this._y + this._z * this._z);
  }
  /**
   * 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(e) {
    return e = e.toLowerCase(), e === "xyz" ? this : (N.Vector3[0].copyFrom(this), ["x", "y", "z"].forEach((t, i) => {
      this[t] = N.Vector3[0][e[i]];
    }), 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(e, t) {
    return e.toRotationMatrix(N.Matrix[0]), p.TransformCoordinatesToRef(this, N.Matrix[0], t), t;
  }
  /**
   * 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(e, t, i) {
    return this.subtractToRef(t, N.Vector3[0]), N.Vector3[0].rotateByQuaternionToRef(e, N.Vector3[0]), t.addToRef(N.Vector3[0], i), i;
  }
  /**
   * 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(e) {
    const t = new this.constructor();
    return p.CrossToRef(this, e, t);
  }
  /**
   * 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(e) {
    return e === 0 || e === 1 ? this : this.scaleInPlace(1 / e);
  }
  /**
   * Normalize the current Vector3 to a new vector
   * Example Playground https://playground.babylonjs.com/#R1F8YU#124
   * @returns the new Vector3
   */
  normalizeToNew() {
    const e = new this.constructor(0, 0, 0);
    return this.normalizeToRef(e), e;
  }
  /**
   * Normalize the current Vector3 to the reference
   * Example Playground https://playground.babylonjs.com/#R1F8YU#125
   * @param reference define the Vector3 to update
   * @returns the updated Vector3
   */
  normalizeToRef(e) {
    const t = this.length();
    return t === 0 || t === 1 ? e.copyFromFloats(this._x, this._y, this._z) : this.scaleToRef(1 / t, e);
  }
  /**
   * Creates a new Vector3 copied from the current Vector3
   * Example Playground https://playground.babylonjs.com/#R1F8YU#11
   * @returns the new Vector3
   */
  clone() {
    return new this.constructor(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(e) {
    return this.copyFromFloats(e._x, e._y, e._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(e, t, i) {
    return this._x = e, this._y = t, this._z = i, this._isDirty = !0, 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(e, t, i) {
    return this.copyFromFloats(e, t, i);
  }
  /**
   * 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(e) {
    return this._x = this._y = this._z = e, this._isDirty = !0, 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(e, t, i, s) {
    const r = p.Dot(e, i) - s, n = p.Dot(t, i) - s;
    return r / (r - n);
  }
  /**
   * 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(e, t, i) {
    const s = e.normalizeToRef(N.Vector3[1]), r = t.normalizeToRef(N.Vector3[2]);
    let n = p.Dot(s, r);
    n = H.Clamp(n, -1, 1);
    const a = Math.acos(n), o = N.Vector3[3];
    return p.CrossToRef(s, r, o), p.Dot(o, i) > 0 ? isNaN(a) ? 0 : a : isNaN(a) ? -Math.PI : -Math.acos(n);
  }
  /**
   * 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(e, t, i) {
    N.Vector3[0].copyFrom(e);
    const s = N.Vector3[0];
    N.Vector3[1].copyFrom(t);
    const r = N.Vector3[1];
    N.Vector3[2].copyFrom(i);
    const n = N.Vector3[2], a = N.Vector3[3], o = N.Vector3[4];
    s.normalize(), r.normalize(), n.normalize(), p.CrossToRef(n, s, a), p.CrossToRef(a, n, o);
    const h = Math.atan2(p.Dot(r, a), p.Dot(r, o));
    return H.NormalizeRadians(h);
  }
  /**
   * 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(e, t, i) {
    const s = C.Vector3[0];
    return t.subtractToRef(e, s), i._y = Math.atan2(s.x, s.z) || 0, i._x = Math.atan2(Math.sqrt(s.x ** 2 + s.z ** 2), s.y) || 0, i._z = 0, i._isDirty = !0, i;
  }
  /**
   * 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(e, t) {
    const i = p.Zero();
    return p.PitchYawRollToMoveBetweenPointsToRef(e, t, i);
  }
  /**
   * 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
   */
  static SlerpToRef(e, t, i, s) {
    i = H.Clamp(i, 0, 1);
    const r = N.Vector3[0], n = N.Vector3[1];
    r.copyFrom(e);
    const a = r.length();
    r.normalizeFromLength(a), n.copyFrom(t);
    const o = n.length();
    n.normalizeFromLength(o);
    const h = p.Dot(r, n);
    let c, u;
    if (h < 1 - ye) {
      const d = Math.acos(h), g = 1 / Math.sin(d);
      c = Math.sin((1 - i) * d) * g, u = Math.sin(i * d) * g;
    } else
      c = 1 - i, u = i;
    return r.scaleInPlace(c), n.scaleInPlace(u), s.copyFrom(r).addInPlace(n), s.scaleInPlace(H.Lerp(a, o, i)), s;
  }
  /**
   * 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
   */
  static SmoothToRef(e, t, i, s, r) {
    return p.SlerpToRef(e, t, s === 0 ? 1 : i / s, r), r;
  }
  /**
   * 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(e, t = 0) {
    return new p(e[t], e[t + 1], e[t + 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(e, t) {
    return p.FromArray(e, t);
  }
  /**
   * 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(e, t, i) {
    return i._x = e[t], i._y = e[t + 1], i._z = e[t + 2], i._isDirty = !0, i;
  }
  /**
   * 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.
   */
  static FromFloatArrayToRef(e, t, i) {
    return p.FromArrayToRef(e, t, i);
  }
  /**
   * 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
   */
  static FromFloatsToRef(e, t, i, s) {
    return s.copyFromFloats(e, t, i), s;
  }
  /**
   * Returns a new Vector3 set to (0.0, 0.0, 0.0)
   * @returns a new empty Vector3
   */
  static Zero() {
    return new p(0, 0, 0);
  }
  /**
   * Returns a new Vector3 set to (1.0, 1.0, 1.0)
   * @returns a new Vector3
   */
  static One() {
    return new p(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 p(0, 1, 0);
  }
  /**
   * Gets an up Vector3 that must not be updated
   */
  static get UpReadOnly() {
    return p._UpReadOnly;
  }
  /**
   * Gets a down Vector3 that must not be updated
   */
  static get DownReadOnly() {
    return p._DownReadOnly;
  }
  /**
   * Gets a right Vector3 that must not be updated
   */
  static get RightReadOnly() {
    return p._RightReadOnly;
  }
  /**
   * Gets a left Vector3 that must not be updated
   */
  static get LeftReadOnly() {
    return p._LeftReadOnly;
  }
  /**
   * Gets a forward Vector3 that must not be updated
   */
  static get LeftHandedForwardReadOnly() {
    return p._LeftHandedForwardReadOnly;
  }
  /**
   * Gets a forward Vector3 that must not be updated
   */
  static get RightHandedForwardReadOnly() {
    return p._RightHandedForwardReadOnly;
  }
  /**
   * Gets a backward Vector3 that must not be updated
   */
  static get LeftHandedBackwardReadOnly() {
    return p._LeftHandedBackwardReadOnly;
  }
  /**
   * Gets a backward Vector3 that must not be updated
   */
  static get RightHandedBackwardReadOnly() {
    return p._RightHandedBackwardReadOnly;
  }
  /**
   * Gets a zero Vector3 that must not be updated
   */
  static get ZeroReadOnly() {
    return p._ZeroReadOnly;
  }
  /**
   * 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 p(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(e = !1) {
    return new p(0, 0, e ? -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(e = !1) {
    return new p(0, 0, e ? 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 p(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 p(-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(e = 0, t = 1) {
    return new p(H.RandomRange(e, t), H.RandomRange(e, t), H.RandomRange(e, t));
  }
  /**
   * 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(e, t) {
    const i = p.Zero();
    return p.TransformCoordinatesToRef(e, t, i), i;
  }
  /**
   * 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(e, t, i) {
    return p.TransformCoordinatesFromFloatsToRef(e._x, e._y, e._z, t, i), i;
  }
  /**
   * 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(e, t, i, s, r) {
    const n = s.m, a = e * n[0] + t * n[4] + i * n[8] + n[12], o = e * n[1] + t * n[5] + i * n[9] + n[13], h = e * n[2] + t * n[6] + i * n[10] + n[14], c = 1 / (e * n[3] + t * n[7] + i * n[11] + n[15]);
    return r._x = a * c, r._y = o * c, r._z = h * c, r._isDirty = !0, r;
  }
  /**
   * 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(e, t) {
    const i = p.Zero();
    return p.TransformNormalToRef(e, t, i), i;
  }
  /**
   * 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(e, t, i) {
    return this.TransformNormalFromFloatsToRef(e._x, e._y, e._z, t, i), i;
  }
  /**
   * 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(e, t, i, s, r) {
    const n = s.m;
    return r._x = e * n[0] + t * n[4] + i * n[8], r._y = e * n[1] + t * n[5] + i * n[9], r._z = e * n[2] + t * n[6] + i * n[10], r._isDirty = !0, r;
  }
  /**
   * 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(e, t, i, s, r) {
    const n = r * r, a = r * n, o = 0.5 * (2 * t._x + (-e._x + i._x) * r + (2 * e._x - 5 * t._x + 4 * i._x - s._x) * n + (-e._x + 3 * t._x - 3 * i._x + s._x) * a), h = 0.5 * (2 * t._y + (-e._y + i._y) * r + (2 * e._y - 5 * t._y + 4 * i._y - s._y) * n + (-e._y + 3 * t._y - 3 * i._y + s._y) * a), c = 0.5 * (2 * t._z + (-e._z + i._z) * r + (2 * e._z - 5 * t._z + 4 * i._z - s._z) * n + (-e._z + 3 * t._z - 3 * i._z + s._z) * a);
    return new e.constructor(o, h, c);
  }
  /**
   * 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(e, t, i) {
    const s = new e.constructor();
    return p.ClampToRef(e, t, i, s), s;
  }
  /**
   * 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(e, t, i, s) {
    let r = e._x;
    r = r > i._x ? i._x : r, r = r < t._x ? t._x : r;
    let n = e._y;
    n = n > i._y ? i._y : n, n = n < t._y ? t._y : n;
    let a = e._z;
    return a = a > i._z ? i._z : a, a = a < t._z ? t._z : a, s.copyFromFloats(r, n, a), s;
  }
  /**
   * 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(e, t, i) {
    t.minimizeInPlace(e), i.maximizeInPlace(e);
  }
  /**
   * 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(e, t, i, s, r) {
    const n = r * r, a = r * n, o = 2 * a - 3 * n + 1, h = -2 * a + 3 * n, c = a - 2 * n + r, u = a - n, d = e._x * o + i._x * h + t._x * c + s._x * u, g = e._y * o + i._y * h + t._y * c + s._y * u, f = e._z * o + i._z * h + t._z * c + s._z * u;
    return new e.constructor(d, g, f);
  }
  /**
   * 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(e, t, i, s, r) {
    const n = new e.constructor();
    return this.Hermite1stDerivativeToRef(e, t, i, s, r, n), n;
  }
  /**
   * 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(e, t, i, s, r, n) {
    const a = r * r;
    return n._x = (a - r) * 6 * e._x + (3 * a - 4 * r + 1) * t._x + (-a + r) * 6 * i._x + (3 * a - 2 * r) * s._x, n._y = (a - r) * 6 * e._y + (3 * a - 4 * r + 1) * t._y + (-a + r) * 6 * i._y + (3 * a - 2 * r) * s._y, n._z = (a - r) * 6 * e._z + (3 * a - 4 * r + 1) * t._z + (-a + r) * 6 * i._z + (3 * a - 2 * r) * s._z, n._isDirty = !0, n;
  }
  /**
   * 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(e, t, i) {
    const s = new e.constructor(0, 0, 0);
    return p.LerpToRef(e, t, i, s), s;
  }
  /**
   * 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(e, t, i, s) {
    return s._x = e._x + (t._x - e._x) * i, s._y = e._y + (t._y - e._y) * i, s._z = e._z + (t._z - e._z) * i, s._isDirty = !0, s;
  }
  /**
   * 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(e, t) {
    return e._x * t._x + e._y * t._y + e._z * t._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(e, t) {
    const i = new e.constructor();
    return p.CrossToRef(e, t, i), i;
  }
  /**
   * 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(e, t, i) {
    const s = e._y * t._z - e._z * t._y, r = e._z * t._x - e._x * t._z, n = e._x * t._y - e._y * t._x;
    return i.copyFromFloats(s, r, n), i;
  }
  /**
   * 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(e) {
    const t = p.Zero();
    return p.NormalizeToRef(e, t), t;
  }
  /**
   * 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(e, t) {
    return e.normalizeToRef(t), t;
  }
  /**
   * 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(e, t, i, s) {
    const r = new e.constructor();
    return p.ProjectToRef(e, t, i, s, r), r;
  }
  /**
   * 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(e, t, i, s, r) {
    const n = s.width, a = s.height, o = s.x, h = s.y, c = N.Matrix[1];
    R.FromValuesToRef(n / 2, 0, 0, 0, 0, -a / 2, 0, 0, 0, 0, 0.5, 0, o + n / 2, a / 2 + h, 0.5, 1, c);
    const u = N.Matrix[0];
    return t.multiplyToRef(i, u), u.multiplyToRef(c, u), p.TransformCoordinatesToRef(e, u, r), r;
  }
  /**
   * 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(e, t) {
    return this.ReflectToRef(e, t, new p());
  }
  /**
   * 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 result defines the Vector3 where to store the result
   * @returns the resulting vector
   */
  static ReflectToRef(e, t, i) {
    const s = C.Vector3[0];
    return s.copyFrom(t).scaleInPlace(2 * p.Dot(e, t)), i.copyFrom(e).subtractInPlace(s);
  }
  /**
   * @internal
   */
  static _UnprojectFromInvertedMatrixToRef(e, t, i) {
    p.TransformCoordinatesToRef(e, t, i);
    const s = t.m, r = e._x * s[3] + e._y * s[7] + e._z * s[11] + s[15];
    return H.WithinEpsilon(r, 1) && i.scaleInPlace(1 / r), i;
  }
  /**
   * 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(e, t, i, s, r) {
    return this.Unproject(e, t, i, s, r, R.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(e, t, i, s, r, n) {
    const a = new e.constructor();
    return p.UnprojectToRef(e, t, i, s, r, n, a), a;
  }
  /**
   * 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(e, t, i, s, r, n, a) {
    return p.UnprojectFloatsToRef(e._x, e._y, e._z, t, i, s, r, n, a), a;
  }
  /**
   * 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(e, t, i, s, r, n, a, o, h) {
    var c;
    const u = N.Matrix[0];
    n.multiplyToRef(a, u), u.multiplyToRef(o, u), u.invert();
    const d = N.Vector3[0];
    return d.x = e / s * 2 - 1, d.y = -(t / r * 2 - 1), !((c = J.LastCreatedEngine) === null || c === void 0) && c.isNDCHalfZRange ? d.z = i : d.z = 2 * i - 1, p._UnprojectFromInvertedMatrixToRef(d, u, h), h;
  }
  /**
   * 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(e, t) {
    const i = new e.constructor();
    return i.copyFrom(e), i.minimizeInPlace(t), i;
  }
  /**
   * 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(e, t) {
    const i = new e.constructor();
    return i.copyFrom(e), i.maximizeInPlace(t), i;
  }
  /**
   * 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(e, t) {
    return Math.sqrt(p.DistanceSquared(e, t));
  }
  /**
   * 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(e, t) {
    const i = e._x - t._x, s = e._y - t._y, r = e._z - t._z;
    return i * i + s * s + r * r;
  }
  /**
   * 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(e, t, i, s, r) {
    const n = N.Vector3[0], a = N.Vector3[1], o = N.Vector3[2], h = N.Vector3[3], c = N.Vector3[4];
    i.subtractToRef(t, n), s.subtractToRef(t, a), s.subtractToRef(i, o);
    const u = n.length(), d = a.length(), g = o.length();
    if (u < ye || d < ye || g < ye)
      return r.copyFrom(t), p.Distance(e, t);
    e.subtractToRef(t, c), p.CrossToRef(n, a, h);
    const f = h.length();
    if (f < ye)
      return r.copyFrom(t), p.Distance(e, t);
    h.normalizeFromLength(f);
    let m = c.length();
    if (m < ye)
      return r.copyFrom(t), 0;
    c.normalizeFromLength(m);
    const b = p.Dot(h, c), T = N.Vector3[5], M = N.Vector3[6];
    T.copyFrom(h).scaleInPlace(-m * b), M.copyFrom(e).addInPlace(T);
    const v = N.Vector3[4], A = N.Vector3[5], E = N.Vector3[7], y = N.Vector3[8];
    v.copyFrom(n).scaleInPlace(1 / u), y.copyFrom(a).scaleInPlace(1 / d), v.addInPlace(y).scaleInPlace(-1), A.copyFrom(n).scaleInPlace(-1 / u), y.copyFrom(o).scaleInPlace(1 / g), A.addInPlace(y).scaleInPlace(-1), E.copyFrom(o).scaleInPlace(-1 / g), y.copyFrom(a).scaleInPlace(-1 / d), E.addInPlace(y).scaleInPlace(-1);
    const x = N.Vector3[9];
    let D;
    x.copyFrom(M).subtractInPlace(t), p.CrossToRef(v, x, y), D = p.Dot(y, h);
    const V = D;
    x.copyFrom(M).subtractInPlace(i), p.CrossToRef(A, x, y), D = p.Dot(y, h);
    const W = D;
    x.copyFrom(M).subtractInPlace(s), p.CrossToRef(E, x, y), D = p.Dot(y, h);
    const ce = D, ee = N.Vector3[10];
    let oe, $;
    V > 0 && W < 0 ? (ee.copyFrom(n), oe = t, $ = i) : W > 0 && ce < 0 ? (ee.copyFrom(o), oe = i, $ = s) : (ee.copyFrom(a).scaleInPlace(-1), oe = s, $ = t);
    const Pe = N.Vector3[9], Ae = N.Vector3[4];
    if (oe.subtractToRef(M, y), $.subtractToRef(M, Pe), p.CrossToRef(y, Pe, Ae), !(p.Dot(Ae, h) < 0))
      return r.copyFrom(M), Math.abs(m * b);
    const Te = N.Vector3[5];
    p.CrossToRef(ee, Ae, Te), Te.normalize();
    const Me = N.Vector3[9];
    Me.copyFrom(oe).subtractInPlace(M);
    const ze = Me.length();
    if (ze < ye)
      return r.copyFrom(oe), p.Distance(e, oe);
    Me.normalizeFromLength(ze);
    const ke = p.Dot(Te, Me), Qe = N.Vector3[7];
    Qe.copyFrom(M).addInPlace(Te.scaleInPlace(ze * ke)), y.copyFrom(Qe).subtractInPlace(oe), m = ee.length(), ee.normalizeFromLength(m);
    let _t = p.Dot(y, ee) / Math.max(m, ye);
    return _t = H.Clamp(_t, 0, 1), Qe.copyFrom(oe).addInPlace(ee.scaleInPlace(_t * m)), r.copyFrom(Qe), p.Distance(e, Qe);
  }
  /**
   * 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(e, t) {
    return p.CenterToRef(e, t, p.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(e, t, i) {
    return i.copyFromFloats((e._x + t._x) / 2, (e._y + t._y) / 2, (e._z + t._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(e, t, i) {
    const s = new e.constructor();
    return p.RotationFromAxisToRef(e, t, i, s), s;
  }
  /**
   * 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(e, t, i, s) {
    const r = N.Quaternion[0];
    return X.RotationQuaternionFromAxisToRef(e, t, i, r), r.toEulerAnglesToRef(s), s;
  }
}
p._UpReadOnly = p.Up();
p._DownReadOnly = p.Down();
p._LeftHandedForwardReadOnly = p.Forward(!1);
p._RightHandedForwardReadOnly = p.Forward(!0);
p._LeftHandedBackwardReadOnly = p.Backward(!1);
p._RightHandedBackwardReadOnly = p.Backward(!0);
p._RightReadOnly = p.Right();
p._LeftReadOnly = p.Left();
p._ZeroReadOnly = p.Zero();
class de {
  /**
   * 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(e = 0, t = 0, i = 0, s = 0) {
    this.x = e, this.y = t, this.z = i, this.w = s;
  }
  /**
   * 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 e = Ue(this.x), t = Ue(this.y), i = Ue(this.z), s = Ue(this.w);
    let r = e;
    return r = r * 397 ^ t, r = r * 397 ^ i, r = r * 397 ^ s, r;
  }
  // Operators
  /**
   * Returns a new array populated with 4 elements : the Vector4 coordinates.
   * @returns the resulting array
   */
  asArray() {
    const e = new Array();
    return this.toArray(e, 0), e;
  }
  /**
   * 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(e, t) {
    return t === void 0 && (t = 0), e[t] = this.x, e[t + 1] = this.y, e[t + 2] = this.z, e[t + 3] = this.w, this;
  }
  /**
   * Update the current vector from an array
   * @param array defines the destination array
   * @param index defines the offset in the destination array
   * @returns the current Vector3
   */
  fromArray(e, t = 0) {
    return de.FromArrayToRef(e, t, this), this;
  }
  /**
   * Adds the given vector to the current Vector4.
   * @param otherVector the vector to add
   * @returns the updated Vector4.
   */
  addInPlace(e) {
    return this.x += e.x, this.y += e.y, this.z += e.z, this.w += e.w, 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(e) {
    return new this.constructor(this.x + e.x, this.y + e.y, this.z + e.z, this.w + e.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(e, t) {
    return t.x = this.x + e.x, t.y = this.y + e.y, t.z = this.z + e.z, t.w = this.w + e.w, t;
  }
  /**
   * Subtract in place the given vector from the current Vector4.
   * @param otherVector the vector to subtract
   * @returns the updated Vector4.
   */
  subtractInPlace(e) {
    return this.x -= e.x, this.y -= e.y, this.z -= e.z, this.w -= e.w, 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(e) {
    return new this.constructor(this.x - e.x, this.y - e.y, this.z - e.z, this.w - e.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(e, t) {
    return t.x = this.x - e.x, t.y = this.y - e.y, t.z = this.z - e.z, t.w = this.w - e.w, t;
  }
  /**
   * Returns a new Vector4 set with the result of the subtraction of the given floats from the current Vector4 coordinates.
   */
  /**
   * 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(e, t, i, s) {
    return new this.constructor(this.x - e, this.y - t, this.z - i, this.w - s);
  }
  /**
   * 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(e, t, i, s, r) {
    return r.x = this.x - e, r.y = this.y - t, r.z = this.z - i, r.w = this.w - s, r;
  }
  /**
   * Returns a new Vector4 set with the current Vector4 negated coordinates.
   * @returns a new vector with the negated values
   */
  negate() {
    return new this.constructor(-this.x, -this.y, -this.z, -this.w);
  }
  /**
   * Negate this vector in place
   * @returns this
   */
  negateInPlace() {
    return this.x *= -1, this.y *= -1, this.z *= -1, this.w *= -1, 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(e) {
    return e.copyFromFloats(this.x * -1, this.y * -1, this.z * -1, this.w * -1);
  }
  /**
   * Multiplies the current Vector4 coordinates by scale (float).
   * @param scale the number to scale with
   * @returns the updated Vector4.
   */
  scaleInPlace(e) {
    return this.x *= e, this.y *= e, this.z *= e, this.w *= e, 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(e) {
    return new this.constructor(this.x * e, this.y * e, this.z * e, this.w * e);
  }
  /**
   * 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(e, t) {
    return t.x = this.x * e, t.y = this.y * e, t.z = this.z * e, t.w = this.w * e, t;
  }
  /**
   * 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(e, t) {
    return t.x += this.x * e, t.y += this.y * e, t.z += this.z * e, t.w += this.w * e, t;
  }
  /**
   * 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(e) {
    return e && this.x === e.x && this.y === e.y && this.z === e.z && this.w === e.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(e, t = ye) {
    return e && H.WithinEpsilon(this.x, e.x, t) && H.WithinEpsilon(this.y, e.y, t) && H.WithinEpsilon(this.z, e.z, t) && H.WithinEpsilon(this.w, e.w, t);
  }
  /**
   * 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(e, t, i, s) {
    return this.x === e && this.y === t && this.z === i && this.w === s;
  }
  /**
   * Multiplies in place the current Vector4 by the given one.
   * @param otherVector vector to multiple with
   * @returns the updated Vector4.
   */
  multiplyInPlace(e) {
    return this.x *= e.x, this.y *= e.y, this.z *= e.z, this.w *= e.w, 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(e) {
    return new this.constructor(this.x * e.x, this.y * e.y, this.z * e.z, this.w * e.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(e, t) {
    return t.x = this.x * e.x, t.y = this.y * e.y, t.z = this.z * e.z, t.w = this.w * e.w, t;
  }
  /**
   * 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(e, t, i, s) {
    return new this.constructor(this.x * e, this.y * t, this.z * i, this.w * s);
  }
  /**
   * 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(e) {
    return new this.constructor(this.x / e.x, this.y / e.y, this.z / e.z, this.w / e.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(e, t) {
    return t.x = this.x / e.x, t.y = this.y / e.y, t.z = this.z / e.z, t.w = this.w / e.w, t;
  }
  /**
   * Divides the current Vector3 coordinates by the given ones.
   * @param otherVector vector to devide with
   * @returns the updated Vector3.
   */
  divideInPlace(e) {
    return this.divideToRef(e, 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(e) {
    return e.x < this.x && (this.x = e.x), e.y < this.y && (this.y = e.y), e.z < this.z && (this.z = e.z), e.w < this.w && (this.w = e.w), 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(e) {
    return e.x > this.x && (this.x = e.x), e.y > this.y && (this.y = e.y), e.z > this.z && (this.z = e.z), e.w > this.w && (this.w = e.w), this;
  }
  /**
   * Gets a new Vector4 from current Vector4 floored values
   * @returns a new Vector4
   */
  floor() {
    return new this.constructor(Math.floor(this.x), Math.floor(this.y), Math.floor(this.z), Math.floor(this.w));
  }
  /**
   * Gets a new Vector4 from current Vector4 fractional values
   * @returns a new Vector4
   */
  fract() {
    return new this.constructor(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() {
    const e = this.length();
    return e === 0 ? this : this.scaleInPlace(1 / e);
  }
  /**
   * Returns a new Vector3 from the Vector4 (x, y, z) coordinates.
   * @returns this converted to a new vector3
   */
  toVector3() {
    return new p(this.x, this.y, this.z);
  }
  /**
   * Returns a new Vector4 copied from the current one.
   * @returns the new cloned vector
   */
  clone() {
    return new this.constructor(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(e) {
    return this.x = e.x, this.y = e.y, this.z = e.z, this.w = e.w, 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(e, t, i, s) {
    return this.x = e, this.y = t, this.z = i, this.w = s, 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(e, t, i, s) {
    return this.copyFromFloats(e, t, i, s);
  }
  /**
   * Copies the given float to the current Vector3 coordinates
   * @param v defines the x, y, z and w coordinates of the operand
   * @returns the current updated Vector3
   */
  setAll(e) {
    return this.x = this.y = this.z = this.w = e, this;
  }
  // 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(e, t) {
    return t || (t = 0), new de(e[t], e[t + 1], e[t + 2], e[t + 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(e, t, i) {
    return i.x = e[t], i.y = e[t + 1], i.z = e[t + 2], i.w = e[t + 3], i;
  }
  /**
   * 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(e, t, i) {
    return de.FromArrayToRef(e, t, i), i;
  }
  /**
   * 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(e, t, i, s, r) {
    return r.x = e, r.y = t, r.z = i, r.w = s, r;
  }
  /**
   * Returns a new Vector4 set to (0.0, 0.0, 0.0, 0.0)
   * @returns the new vector
   */
  static Zero() {
    return new de(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 de(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(e = 0, t = 1) {
    return new de(H.RandomRange(e, t), H.RandomRange(e, t), H.RandomRange(e, t), H.RandomRange(e, t));
  }
  /**
   * Gets a zero Vector4 that must not be updated
   */
  static get ZeroReadOnly() {
    return de._ZeroReadOnly;
  }
  /**
   * Returns a new normalized Vector4 from the given one.
   * @param vector the vector to normalize
   * @returns the vector
   */
  static Normalize(e) {
    const t = de.Zero();
    return de.NormalizeToRef(e, t), t;
  }
  /**
   * 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(e, t) {
    return t.copyFrom(e), t.normalize(), t;
  }
  /**
   * 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(e, t) {
    const i = new e.constructor();
    return i.copyFrom(e), i.minimizeInPlace(t), i;
  }
  /**
   * 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(e, t) {
    const i = new e.constructor();
    return i.copyFrom(e), i.maximizeInPlace(t), i;
  }
  /**
   * 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(e, t) {
    return Math.sqrt(de.DistanceSquared(e, t));
  }
  /**
   * 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(e, t) {
    const i = e.x - t.x, s = e.y - t.y, r = e.z - t.z, n = e.w - t.w;
    return i * i + s * s + r * r + n * n;
  }
  /**
   * 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(e, t) {
    return de.CenterToRef(e, t, de.Zero());
  }
  /**
   * 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(e, t, i) {
    return i.copyFromFloats((e.x + t.x) / 2, (e.y + t.y) / 2, (e.z + t.z) / 2, (e.w + t.w) / 2);
  }
  /**
   * 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(e, t) {
    const i = de.Zero();
    return de.TransformCoordinatesToRef(e, t, i), i;
  }
  /**
   * 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(e, t, i) {
    return de.TransformCoordinatesFromFloatsToRef(e._x, e._y, e._z, t, i), i;
  }
  /**
   * 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(e, t, i, s, r) {
    const n = s.m, a = e * n[0] + t * n[4] + i * n[8] + n[12], o = e * n[1] + t * n[5] + i * n[9] + n[13], h = e * n[2] + t * n[6] + i * n[10] + n[14], c = e * n[3] + t * n[7] + i * n[11] + n[15];
    return r.x = a, r.y = o, r.z = h, r.w = c, r;
  }
  /**
   * 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(e, t) {
    const i = new e.constructor();
    return de.TransformNormalToRef(e, t, i), i;
  }
  /**
   * 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(e, t, i) {
    const s = t.m, r = e.x * s[0] + e.y * s[4] + e.z * s[8], n = e.x * s[1] + e.y * s[5] + e.z * s[9], a = e.x * s[2] + e.y * s[6] + e.z * s[10];
    return i.x = r, i.y = n, i.z = a, i.w = e.w, i;
  }
  /**
   * 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(e, t, i, s, r, n) {
    const a = r.m;
    return n.x = e * a[0] + t * a[4] + i * a[8], n.y = e * a[1] + t * a[5] + i * a[9], n.z = e * a[2] + t * a[6] + i * a[10], n.w = s, n;
  }
  /**
   * 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(e, t = 0) {
    return new de(e._x, e._y, e._z, t);
  }
}
de._ZeroReadOnly = de.Zero();
class X {
  /** Gets or sets the x coordinate */
  get x() {
    return this._x;
  }
  set x(e) {
    this._x = e, this._isDirty = !0;
  }
  /** Gets or sets the y coordinate */
  get y() {
    return this._y;
  }
  set y(e) {
    this._y = e, this._isDirty = !0;
  }
  /** Gets or sets the z coordinate */
  get z() {
    return this._z;
  }
  set z(e) {
    this._z = e, this._isDirty = !0;
  }
  /** Gets or sets the w coordinate */
  get w() {
    return this._w;
  }
  set w(e) {
    this._w = e, this._isDirty = !0;
  }
  /**
   * 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(e = 0, t = 0, i = 0, s = 1) {
    this._isDirty = !0, this._x = e, this._y = t, this._z = i, this._w = s;
  }
  /**
   * 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 e = Ue(this._x), t = Ue(this._y), i = Ue(this._z), s = Ue(this._w);
    let r = e;
    return r = r * 397 ^ t, r = r * 397 ^ i, r = r * 397 ^ s, r;
  }
  /**
   * 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(e, t = 0) {
    return e[t] = this._x, e[t + 1] = this._y, e[t + 2] = this._z, e[t + 3] = this._w, 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(e) {
    return e && this._x === e._x && this._y === e._y && this._z === e._z && this._w === e._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(e, t = ye) {
    return e && H.WithinEpsilon(this._x, e._x, t) && H.WithinEpsilon(this._y, e._y, t) && H.WithinEpsilon(this._z, e._z, t) && H.WithinEpsilon(this._w, e._w, t);
  }
  /**
   * Clone the current quaternion
   * Example Playground https://playground.babylonjs.com/#L49EJ7#12
   * @returns a new quaternion copied from the current one
   */
  clone() {
    return new this.constructor(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(e) {
    return this._x = e._x, this._y = e._y, this._z = e._z, this._w = e._w, this._isDirty = !0, 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(e, t, i, s) {
    return this._x = e, this._y = t, this._z = i, this._w = s, this._isDirty = !0, 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(e, t, i, s) {
    return this.copyFromFloats(e, t, i, s);
  }
  /**
   * 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(e) {
    return new this.constructor(this._x + e._x, this._y + e._y, this._z + e._z, this._w + e._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(e) {
    return this._x += e._x, this._y += e._y, this._z += e._z, this._w += e._w, this._isDirty = !0, this;
  }
  /**
   * 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(e) {
    return new this.constructor(this._x - e._x, this._y - e._y, this._z - e._z, this._w - e._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(e) {
    return this._x -= e._x, this._y -= e._y, this._z -= e._z, this._w -= e._w, this._isDirty = !0, 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(e) {
    return new this.constructor(this._x * e, this._y * e, this._z * e, this._w * e);
  }
  /**
   * 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(e, t) {
    return t._x = this._x * e, t._y = this._y * e, t._z = this._z * e, t._w = this._w * e, t._isDirty = !0, t;
  }
  /**
   * 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(e) {
    return this._x *= e, this._y *= e, this._z *= e, this._w *= e, this._isDirty = !0, 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(e, t) {
    return t._x += this._x * e, t._y += this._y * e, t._z += this._z * e, t._w += this._w * e, t._isDirty = !0, t;
  }
  /**
   * 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(e) {
    const t = new this.constructor(0, 0, 0, 1);
    return this.multiplyToRef(e, t), t;
  }
  /**
   * Sets the given "result" as the 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(e, t) {
    const i = this._x * e._w + this._y * e._z - this._z * e._y + this._w * e._x, s = -this._x * e._z + this._y * e._w + this._z * e._x + this._w * e._y, r = this._x * e._y - this._y * e._x + this._z * e._w + this._w * e._z, n = -this._x * e._x - this._y * e._y - this._z * e._z + this._w * e._w;
    return t.copyFromFloats(i, s, r, n), t;
  }
  /**
   * Updates the current quaternion with the multiplication of itself with the given one "q1"
   * Example Playground https://playground.babylonjs.com/#L49EJ7#46
   * @param q1 defines the second operand
   * @returns the currentupdated quaternion
   */
  multiplyInPlace(e) {
    return this.multiplyToRef(e, this), this;
  }
  /**
   * 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(e) {
    return e.copyFromFloats(-this._x, -this._y, -this._z, this._w), e;
  }
  /**
   * Conjugates in place the current quaternion
   * Example Playground https://playground.babylonjs.com/#L49EJ7#82
   * @returns the current updated quaternion
   */
  conjugateInPlace() {
    return this._x *= -1, this._y *= -1, this._z *= -1, this._isDirty = !0, this;
  }
  /**
   * Conjugates (1-q) the current quaternion
   * Example Playground https://playground.babylonjs.com/#L49EJ7#83
   * @returns a new quaternion
   */
  conjugate() {
    return new this.constructor(-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 e = this.conjugate(), t = this.lengthSquared();
    return t == 0 || t == 1 || e.scaleInPlace(1 / t), e;
  }
  /**
   * Invert in place the current quaternion
   * Example Playground https://playground.babylonjs.com/#L49EJ7#85
   * @returns this quaternion
   */
  invertInPlace() {
    this.conjugateInPlace();
    const e = this.lengthSquared();
    return e == 0 || e == 1 ? this : (this.scaleInPlace(1 / e), 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() {
    const e = this.length();
    if (e === 0)
      return this;
    const t = 1 / e;
    return this.scaleInPlace(t), this;
  }
  /**
   * Normalize a copy of the current quaternion
   * Example Playground https://playground.babylonjs.com/#L49EJ7#55
   * @returns the normalized quaternion
   */
  normalizeToNew() {
    const e = this.length();
    if (e === 0)
      return this.clone();
    const t = 1 / e;
    return this.scale(t);
  }
  /**
   * 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 e = p.Zero();
    return this.toEulerAnglesToRef(e), e;
  }
  /**
   * 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(e) {
    const t = this._z, i = this._x, s = this._y, r = this._w, n = s * t - i * r, a = 0.4999999;
    if (n < -a)
      e._y = 2 * Math.atan2(s, r), e._x = Math.PI / 2, e._z = 0, e._isDirty = !0;
    else if (n > a)
      e._y = 2 * Math.atan2(s, r), e._x = -Math.PI / 2, e._z = 0, e._isDirty = !0;
    else {
      const o = r * r, h = t * t, c = i * i, u = s * s;
      e._z = Math.atan2(2 * (i * s + t * r), -h - c + u + o), e._x = Math.asin(-2 * n), e._y = Math.atan2(2 * (t * i + s * r), h - c - u + o), e._isDirty = !0;
    }
    return e;
  }
  /**
   * 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 current unchanged quaternion
   */
  toRotationMatrix(e) {
    return R.FromQuaternionToRef(this, e), e;
  }
  /**
   * 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(e) {
    return X.FromRotationMatrixToRef(e, this), this;
  }
  // 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(e) {
    const t = new X();
    return X.FromRotationMatrixToRef(e, t), t;
  }
  /**
   * 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(e, t) {
    const i = e.m, s = i[0], r = i[4], n = i[8], a = i[1], o = i[5], h = i[9], c = i[2], u = i[6], d = i[10], g = s + o + d;
    let f;
    return g > 0 ? (f = 0.5 / Math.sqrt(g + 1), t._w = 0.25 / f, t._x = (u - h) * f, t._y = (n - c) * f, t._z = (a - r) * f, t._isDirty = !0) : s > o && s > d ? (f = 2 * Math.sqrt(1 + s - o - d), t._w = (u - h) / f, t._x = 0.25 * f, t._y = (r + a) / f, t._z = (n + c) / f, t._isDirty = !0) : o > d ? (f = 2 * Math.sqrt(1 + o - s - d), t._w = (n - c) / f, t._x = (r + a) / f, t._y = 0.25 * f, t._z = (h + u) / f, t._isDirty = !0) : (f = 2 * Math.sqrt(1 + d - s - o), t._w = (a - r) / f, t._x = (n + c) / f, t._y = (h + u) / f, t._z = 0.25 * f, t._isDirty = !0), t;
  }
  /**
   * 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(e, t) {
    return e._x * t._x + e._y * t._y + e._z * t._z + e._w * t._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(e, t, i = 0.1) {
    const s = X.Dot(e, t);
    return 1 - s * s <= i;
  }
  /**
   * 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
   */
  static SmoothToRef(e, t, i, s, r) {
    let n = s === 0 ? 1 : i / s;
    return n = H.Clamp(n, 0, 1), X.SlerpToRef(e, t, n, r), r;
  }
  /**
   * Creates an empty quaternion
   * @returns a new quaternion set to (0.0, 0.0, 0.0)
   */
  static Zero() {
    return new X(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(e) {
    return new e.constructor(-e._x, -e._y, -e._z, e._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(e, t) {
    return t.set(-e._x, -e._y, -e._z, e._w), t;
  }
  /**
   * Creates an identity quaternion
   * @returns the identity quaternion
   */
  static Identity() {
    return new X(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(e) {
    return e && e._x === 0 && e._y === 0 && e._z === 0 && e._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(e, t) {
    return X.RotationAxisToRef(e, t, new X());
  }
  /**
   * 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(e, t, i) {
    const s = Math.sin(t / 2);
    return e.normalize(), i._w = Math.cos(t / 2), i._x = e._x * s, i._y = e._y * s, i._z = e._z * s, i._isDirty = !0, i;
  }
  /**
   * 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(e, t) {
    return t || (t = 0), new X(e[t], e[t + 1], e[t + 2], e[t + 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(e, t, i) {
    return i._x = e[t], i._y = e[t + 1], i._z = e[t + 2], i._w = e[t + 3], i._isDirty = !0, i;
  }
  /**
   * 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(e, t, i) {
    const s = new X();
    return X.RotationYawPitchRollToRef(t, e, i, s), s;
  }
  /**
   * 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(e, t, i, s) {
    return X.RotationYawPitchRollToRef(t, e, i, s), s;
  }
  /**
   * 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(e) {
    const t = new X();
    return X.RotationYawPitchRollToRef(e._y, e._x, e._z, t), t;
  }
  /**
   * 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(e, t) {
    return X.RotationYawPitchRollToRef(e._y, e._x, e._z, t), t;
  }
  /**
   * 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
   * @returns the updated quaternion
   */
  static FromUnitVectorsToRef(e, t, i) {
    const s = p.Dot(e, t) + 1;
    return s < ye ? Math.abs(e.x) > Math.abs(e.z) ? i.set(-e.y, e.x, 0, 0) : i.set(0, -e.z, e.y, 0) : (p.CrossToRef(e, t, C.Vector3[0]), i.set(C.Vector3[0].x, C.Vector3[0].y, C.Vector3[0].z, s)), i.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(e, t, i) {
    const s = new X();
    return X.RotationYawPitchRollToRef(e, t, i, s), s;
  }
  /**
   * 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#78
   * @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(e, t, i, s) {
    const r = i * 0.5, n = t * 0.5, a = e * 0.5, o = Math.sin(r), h = Math.cos(r), c = Math.sin(n), u = Math.cos(n), d = Math.sin(a), g = Math.cos(a);
    return s._x = g * c * h + d * u * o, s._y = d * u * h - g * c * o, s._z = g * u * o - d * c * h, s._w = g * u * h + d * c * o, s._isDirty = !0, s;
  }
  /**
   * 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(e, t, i) {
    const s = new X();
    return X.RotationAlphaBetaGammaToRef(e, t, i, s), s;
  }
  /**
   * 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(e, t, i, s) {
    const r = (i + e) * 0.5, n = (i - e) * 0.5, a = t * 0.5;
    return s._x = Math.cos(n) * Math.sin(a), s._y = Math.sin(n) * Math.sin(a), s._z = Math.sin(r) * Math.cos(a), s._w = Math.cos(r) * Math.cos(a), s._isDirty = !0, s;
  }
  /**
   * 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(e, t, i) {
    const s = new X(0, 0, 0, 0);
    return X.RotationQuaternionFromAxisToRef(e, t, i, s), s;
  }
  /**
   * 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(e, t, i, s) {
    const r = N.Matrix[0];
    return R.FromXYZAxesToRef(e.normalize(), t.normalize(), i.normalize(), r), X.FromRotationMatrixToRef(r, s), s;
  }
  /**
   * 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(e, t) {
    const i = new X();
    return X.FromLookDirectionLHToRef(e, t, i), i;
  }
  /**
   * 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(e, t, i) {
    const s = N.Matrix[0];
    return R.LookDirectionLHToRef(e, t, s), X.FromRotationMatrixToRef(s, i), i;
  }
  /**
   * 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(e, t) {
    const i = new X();
    return X.FromLookDirectionRHToRef(e, t, i), i;
  }
  /**
   * 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(e, t, i) {
    const s = N.Matrix[0];
    return R.LookDirectionRHToRef(e, t, s), X.FromRotationMatrixToRef(s, i);
  }
  /**
   * 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(e, t, i) {
    const s = X.Identity();
    return X.SlerpToRef(e, t, i, s), s;
  }
  /**
   * 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(e, t, i, s) {
    let r, n, a = e._x * t._x + e._y * t._y + e._z * t._z + e._w * t._w, o = !1;
    if (a < 0 && (o = !0, a = -a), a > 0.999999)
      n = 1 - i, r = o ? -i : i;
    else {
      const h = Math.acos(a), c = 1 / Math.sin(h);
      n = Math.sin((1 - i) * h) * c, r = o ? -Math.sin(i * h) * c : Math.sin(i * h) * c;
    }
    return s._x = n * e._x + r * t._x, s._y = n * e._y + r * t._y, s._z = n * e._z + r * t._z, s._w = n * e._w + r * t._w, s._isDirty = !0, s;
  }
  /**
   * 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(e, t, i, s, r) {
    const n = r * r, a = r * n, o = 2 * a - 3 * n + 1, h = -2 * a + 3 * n, c = a - 2 * n + r, u = a - n, d = e._x * o + i._x * h + t._x * c + s._x * u, g = e._y * o + i._y * h + t._y * c + s._y * u, f = e._z * o + i._z * h + t._z * c + s._z * u, m = e._w * o + i._w * h + t._w * c + s._w * u;
    return new e.constructor(d, g, f, m);
  }
  /**
   * 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(e, t, i, s, r) {
    const n = new e.constructor();
    return this.Hermite1stDerivativeToRef(e, t, i, s, r, n), n;
  }
  /**
   * 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(e, t, i, s, r, n) {
    const a = r * r;
    return n._x = (a - r) * 6 * e._x + (3 * a - 4 * r + 1) * t._x + (-a + r) * 6 * i._x + (3 * a - 2 * r) * s._x, n._y = (a - r) * 6 * e._y + (3 * a - 4 * r + 1) * t._y + (-a + r) * 6 * i._y + (3 * a - 2 * r) * s._y, n._z = (a - r) * 6 * e._z + (3 * a - 4 * r + 1) * t._z + (-a + r) * 6 * i._z + (3 * a - 2 * r) * s._z, n._w = (a - r) * 6 * e._w + (3 * a - 4 * r + 1) * t._w + (-a + r) * 6 * i._w + (3 * a - 2 * r) * s._w, n._isDirty = !0, n;
  }
}
class R {
  /**
   * Gets the precision of matrix computations
   */
  static get Use64Bits() {
    return be.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 = R._UpdateFlagSeed++, this._isIdentity = !1, this._isIdentity3x2 = !1, this._isIdentityDirty = !0, this._isIdentity3x2Dirty = !0;
  }
  _updateIdentityStatus(e, t = !1, i = !1, s = !0) {
    this._isIdentity = e, this._isIdentity3x2 = e || i, this._isIdentityDirty = this._isIdentity ? !1 : t, this._isIdentity3x2Dirty = this._isIdentity3x2 ? !1 : s;
  }
  /**
   * Creates an empty matrix (filled with zeros)
   */
  constructor() {
    this._isIdentity = !1, this._isIdentityDirty = !0, this._isIdentity3x2 = !0, this._isIdentity3x2Dirty = !0, this.updateFlag = -1, be.MatrixTrackPrecisionChange && be.MatrixTrackedMatrices.push(this), this._m = new be.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 = !1;
      const e = this._m;
      this._isIdentity = e[0] === 1 && e[1] === 0 && e[2] === 0 && e[3] === 0 && e[4] === 0 && e[5] === 1 && e[6] === 0 && e[7] === 0 && e[8] === 0 && e[9] === 0 && e[10] === 1 && e[11] === 0 && e[12] === 0 && e[13] === 0 && e[14] === 0 && e[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() {
    return this._isIdentity3x2Dirty && (this._isIdentity3x2Dirty = !1, this._m[0] !== 1 || this._m[5] !== 1 || this._m[15] !== 1 ? this._isIdentity3x2 = !1 : 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 = !1 : this._isIdentity3x2 = !0), this._isIdentity3x2;
  }
  /**
   * Gets the determinant of the matrix
   * Example Playground - https://playground.babylonjs.com/#AV9X17#34
   * @returns the matrix determinant
   */
  determinant() {
    if (this._isIdentity === !0)
      return 1;
    const e = this._m, t = e[0], i = e[1], s = e[2], r = e[3], n = e[4], a = e[5], o = e[6], h = e[7], c = e[8], u = e[9], d = e[10], g = e[11], f = e[12], m = e[13], b = e[14], T = e[15], M = d * T - b * g, v = u * T - m * g, A = u * b - m * d, E = c * T - f * g, y = c * b - d * f, x = c * m - f * u, D = +(a * M - o * v + h * A), V = -(n * M - o * E + h * y), W = +(n * v - a * E + h * x), ce = -(n * A - a * y + o * x);
    return t * D + i * V + s * W + r * ce;
  }
  // Methods
  /**
   * Returns the matrix as a Float32Array or Array<number>
   * Example Playground - https://playground.babylonjs.com/#AV9X17#49
   * @returns the matrix underlying array
   */
  toArray() {
    return this._m;
  }
  /**
   * Returns the matrix as a Float32Array or Array<number>
   * Example Playground - https://playground.babylonjs.com/#AV9X17#114
   * @returns the matrix underlying array.
   */
  asArray() {
    return this._m;
  }
  /**
   * Inverts the current matrix in place
   * Example Playground - https://playground.babylonjs.com/#AV9X17#118
   * @returns the current inverted matrix
   */
  invert() {
    return this.invertToRef(this), this;
  }
  /**
   * Sets all the matrix elements to zero
   * @returns the current matrix
   */
  reset() {
    return R.FromValuesToRef(0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, this), this._updateIdentityStatus(!1), 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(e) {
    const t = new this.constructor();
    return this.addToRef(e, t), t;
  }
  /**
   * 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(e, t) {
    const i = this._m, s = t._m, r = e.m;
    for (let n = 0; n < 16; n++)
      s[n] = i[n] + r[n];
    return t.markAsUpdated(), t;
  }
  /**
   * 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(e) {
    const t = this._m, i = e.m;
    for (let s = 0; s < 16; s++)
      t[s] += i[s];
    return this.markAsUpdated(), this;
  }
  /**
   * 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(e) {
    if (this._isIdentity === !0)
      return R.IdentityToRef(e), e;
    const t = this._m, i = t[0], s = t[1], r = t[2], n = t[3], a = t[4], o = t[5], h = t[6], c = t[7], u = t[8], d = t[9], g = t[10], f = t[11], m = t[12], b = t[13], T = t[14], M = t[15], v = g * M - T * f, A = d * M - b * f, E = d * T - b * g, y = u * M - m * f, x = u * T - g * m, D = u * b - m * d, V = +(o * v - h * A + c * E), W = -(a * v - h * y + c * x), ce = +(a * A - o * y + c * D), ee = -(a * E - o * x + h * D), oe = i * V + s * W + r * ce + n * ee;
    if (oe === 0)
      return e.copyFrom(this), e;
    const $ = 1 / oe, Pe = h * M - T * c, Ae = o * M - b * c, Fe = o * T - b * h, Te = a * M - m * c, Me = a * T - m * h, ze = a * b - m * o, ke = h * f - g * c, Qe = o * f - d * c, _t = o * g - d * h, Xt = a * f - u * c, Yt = a * g - u * h, qt = a * d - u * o, ui = -(s * v - r * A + n * E), di = +(i * v - r * y + n * x), fi = -(i * A - s * y + n * D), _i = +(i * E - s * x + r * D), gi = +(s * Pe - r * Ae + n * Fe), pi = -(i * Pe - r * Te + n * Me), it = +(i * Ae - s * Te + n * ze), st = -(i * Fe - s * Me + r * ze), rt = -(s * ke - r * Qe + n * _t), nt = +(i * ke - r * Xt + n * Yt), ps = -(i * Qe - s * Xt + n * qt), ms = +(i * _t - s * Yt + r * qt);
    return R.FromValuesToRef(V * $, ui * $, gi * $, rt * $, W * $, di * $, pi * $, nt * $, ce * $, fi * $, it * $, ps * $, ee * $, _i * $, st * $, ms * $, e), e;
  }
  /**
   * 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(e, t) {
    return this._m[e] += t, this.markAsUpdated(), 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(e, t) {
    return this._m[e] *= t, this.markAsUpdated(), 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(e, t, i) {
    return this._m[12] = e, this._m[13] = t, this._m[14] = i, this.markAsUpdated(), 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(e, t, i) {
    return this._m[12] += e, this._m[13] += t, this._m[14] += i, this.markAsUpdated(), 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(e) {
    return this.setTranslationFromFloats(e._x, e._y, e._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 p(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(e) {
    return e.x = this._m[12], e.y = this._m[13], e.z = this._m[14], e;
  }
  /**
   * Remove rotation and scaling part from the matrix
   * @returns the updated matrix
   */
  removeRotationAndScaling() {
    const e = this.m;
    return R.FromValuesToRef(1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, e[12], e[13], e[14], e[15], this), this._updateIdentityStatus(e[12] === 0 && e[13] === 0 && e[14] === 0 && e[15] === 1), 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(e) {
    const t = new this.constructor();
    return this.multiplyToRef(e, t), t;
  }
  /**
   * 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(e) {
    e.copyToArray(this._m);
    const t = e;
    return this.updateFlag = t.updateFlag, this._updateIdentityStatus(t._isIdentity, t._isIdentityDirty, t._isIdentity3x2, t._isIdentity3x2Dirty), 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(e, t = 0) {
    const i = this._m;
    return e[t] = i[0], e[t + 1] = i[1], e[t + 2] = i[2], e[t + 3] = i[3], e[t + 4] = i[4], e[t + 5] = i[5], e[t + 6] = i[6], e[t + 7] = i[7], e[t + 8] = i[8], e[t + 9] = i[9], e[t + 10] = i[10], e[t + 11] = i[11], e[t + 12] = i[12], e[t + 13] = i[13], e[t + 14] = i[14], e[t + 15] = i[15], this;
  }
  /**
   * 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(e, t) {
    return this._isIdentity ? (t.copyFrom(e), t) : e._isIdentity ? (t.copyFrom(this), t) : (this.multiplyToArray(e, t._m, 0), t.markAsUpdated(), t);
  }
  /**
   * 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(e, t, i) {
    const s = this._m, r = e.m, n = s[0], a = s[1], o = s[2], h = s[3], c = s[4], u = s[5], d = s[6], g = s[7], f = s[8], m = s[9], b = s[10], T = s[11], M = s[12], v = s[13], A = s[14], E = s[15], y = r[0], x = r[1], D = r[2], V = r[3], W = r[4], ce = r[5], ee = r[6], oe = r[7], $ = r[8], Pe = r[9], Ae = r[10], Fe = r[11], Te = r[12], Me = r[13], ze = r[14], ke = r[15];
    return t[i] = n * y + a * W + o * $ + h * Te, t[i + 1] = n * x + a * ce + o * Pe + h * Me, t[i + 2] = n * D + a * ee + o * Ae + h * ze, t[i + 3] = n * V + a * oe + o * Fe + h * ke, t[i + 4] = c * y + u * W + d * $ + g * Te, t[i + 5] = c * x + u * ce + d * Pe + g * Me, t[i + 6] = c * D + u * ee + d * Ae + g * ze, t[i + 7] = c * V + u * oe + d * Fe + g * ke, t[i + 8] = f * y + m * W + b * $ + T * Te, t[i + 9] = f * x + m * ce + b * Pe + T * Me, t[i + 10] = f * D + m * ee + b * Ae + T * ze, t[i + 11] = f * V + m * oe + b * Fe + T * ke, t[i + 12] = M * y + v * W + A * $ + E * Te, t[i + 13] = M * x + v * ce + A * Pe + E * Me, t[i + 14] = M * D + v * ee + A * Ae + E * ze, t[i + 15] = M * V + v * oe + A * Fe + E * ke, this;
  }
  /**
   * 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(e) {
    const t = e;
    if (!t)
      return !1;
    if ((this._isIdentity || t._isIdentity) && !this._isIdentityDirty && !t._isIdentityDirty)
      return this._isIdentity && t._isIdentity;
    const i = this.m, s = t.m;
    return i[0] === s[0] && i[1] === s[1] && i[2] === s[2] && i[3] === s[3] && i[4] === s[4] && i[5] === s[5] && i[6] === s[6] && i[7] === s[7] && i[8] === s[8] && i[9] === s[9] && i[10] === s[10] && i[11] === s[11] && i[12] === s[12] && i[13] === s[13] && i[14] === s[14] && i[15] === s[15];
  }
  /**
   * Clone the current matrix
   * Example Playground - https://playground.babylonjs.com/#AV9X17#18
   * @returns a new matrix from the current matrix
   */
  clone() {
    const e = new this.constructor();
    return e.copyFrom(this), e;
  }
  /**
   * 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 e = Ue(this._m[0]);
    for (let t = 1; t < 16; t++)
      e = e * 397 ^ Ue(this._m[t]);
    return e;
  }
  /**
   * 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(e) {
    return e.rotationQuaternion = e.rotationQuaternion || new X(), this.decompose(e.scaling, e.rotationQuaternion, e.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.
   * @returns true if operation was successful
   */
  decompose(e, t, i, s) {
    if (this._isIdentity)
      return i && i.setAll(0), e && e.setAll(1), t && t.copyFromFloats(0, 0, 0, 1), !0;
    const r = this._m;
    if (i && i.copyFromFloats(r[12], r[13], r[14]), e = e || N.Vector3[0], e.x = Math.sqrt(r[0] * r[0] + r[1] * r[1] + r[2] * r[2]), e.y = Math.sqrt(r[4] * r[4] + r[5] * r[5] + r[6] * r[6]), e.z = Math.sqrt(r[8] * r[8] + r[9] * r[9] + r[10] * r[10]), s) {
      const n = s.scaling.x < 0 ? -1 : 1, a = s.scaling.y < 0 ? -1 : 1, o = s.scaling.z < 0 ? -1 : 1;
      e.x *= n, e.y *= a, e.z *= o;
    } else
      this.determinant() <= 0 && (e.y *= -1);
    if (e._x === 0 || e._y === 0 || e._z === 0)
      return t && t.copyFromFloats(0, 0, 0, 1), !1;
    if (t) {
      const n = 1 / e._x, a = 1 / e._y, o = 1 / e._z;
      R.FromValuesToRef(r[0] * n, r[1] * n, r[2] * n, 0, r[4] * a, r[5] * a, r[6] * a, 0, r[8] * o, r[9] * o, r[10] * o, 0, 0, 0, 0, 1, N.Matrix[0]), X.FromRotationMatrixToRef(N.Matrix[0], t);
    }
    return !0;
  }
  /**
   * 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(e) {
    if (e < 0 || e > 3)
      return null;
    const t = e * 4;
    return new de(this._m[t + 0], this._m[t + 1], this._m[t + 2], this._m[t + 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(e, t) {
    if (e >= 0 && e < 3) {
      const i = e * 4;
      t.x = this._m[i + 0], t.y = this._m[i + 1], t.z = this._m[i + 2], t.w = this._m[i + 3];
    }
    return t;
  }
  /**
   * 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(e, t) {
    return this.setRowFromFloats(e, t.x, t.y, t.z, t.w);
  }
  /**
   * Compute the transpose of the matrix
   * Example Playground - https://playground.babylonjs.com/#AV9X17#40
   * @returns the new transposed matrix
   */
  transpose() {
    const e = new this.constructor();
    return R.TransposeToRef(this, e), e;
  }
  /**
   * 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(e) {
    return R.TransposeToRef(this, e), e;
  }
  /**
   * 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(e, t, i, s, r) {
    if (e < 0 || e > 3)
      return this;
    const n = e * 4;
    return this._m[n + 0] = t, this._m[n + 1] = i, this._m[n + 2] = s, this._m[n + 3] = r, this.markAsUpdated(), 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(e) {
    const t = new this.constructor();
    return this.scaleToRef(e, t), t;
  }
  /**
   * 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(e, t) {
    for (let i = 0; i < 16; i++)
      t._m[i] = this._m[i] * e;
    return t.markAsUpdated(), t;
  }
  /**
   * 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(e, t) {
    for (let i = 0; i < 16; i++)
      t._m[i] += this._m[i] * e;
    return t.markAsUpdated(), t;
  }
  /**
   * 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
   */
  toNormalMatrix(e) {
    const t = N.Matrix[0];
    this.invertToRef(t), t.transposeToRef(e);
    const i = e._m;
    return R.FromValuesToRef(i[0], i[1], i[2], 0, i[4], i[5], i[6], 0, i[8], i[9], i[10], 0, 0, 0, 0, 1, e), e;
  }
  /**
   * Gets only rotation part of the current matrix
   * @returns a new matrix sets to the extracted rotation matrix from the current one
   */
  getRotationMatrix() {
    const e = new this.constructor();
    return this.getRotationMatrixToRef(e), e;
  }
  /**
   * 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(e) {
    const t = N.Vector3[0];
    if (!this.decompose(t))
      return R.IdentityToRef(e), e;
    const i = this._m, s = 1 / t._x, r = 1 / t._y, n = 1 / t._z;
    return R.FromValuesToRef(i[0] * s, i[1] * s, i[2] * s, 0, i[4] * r, i[5] * r, i[6] * r, 0, i[8] * n, i[9] * n, i[10] * n, 0, 0, 0, 0, 1, e), e;
  }
  /**
   * Toggles model matrix from being right handed to left handed in place and vice versa
   */
  toggleModelMatrixHandInPlace() {
    const e = this._m;
    return e[2] *= -1, e[6] *= -1, e[8] *= -1, e[9] *= -1, e[14] *= -1, this.markAsUpdated(), this;
  }
  /**
   * Toggles projection matrix from being right handed to left handed in place and vice versa
   */
  toggleProjectionMatrixHandInPlace() {
    const e = this._m;
    return e[8] *= -1, e[9] *= -1, e[10] *= -1, e[11] *= -1, this.markAsUpdated(), 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(e, t = 0) {
    const i = new R();
    return R.FromArrayToRef(e, t, i), i;
  }
  /**
   * 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(e, t, i) {
    for (let s = 0; s < 16; s++)
      i._m[s] = e[s + t];
    return i.markAsUpdated(), i;
  }
  /**
   * 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(e, t, i, s) {
    for (let r = 0; r < 16; r++)
      s._m[r] = e[r + t] * i;
    return s.markAsUpdated(), s;
  }
  /**
   * Gets an identity matrix that must not be updated
   */
  static get IdentityReadOnly() {
    return R._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
   * @returns result input
   */
  static FromValuesToRef(e, t, i, s, r, n, a, o, h, c, u, d, g, f, m, b, T) {
    const M = T._m;
    M[0] = e, M[1] = t, M[2] = i, M[3] = s, M[4] = r, M[5] = n, M[6] = a, M[7] = o, M[8] = h, M[9] = c, M[10] = u, M[11] = d, M[12] = g, M[13] = f, M[14] = m, M[15] = b, T.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(e, t, i, s, r, n, a, o, h, c, u, d, g, f, m, b) {
    const T = new R(), M = T._m;
    return M[0] = e, M[1] = t, M[2] = i, M[3] = s, M[4] = r, M[5] = n, M[6] = a, M[7] = o, M[8] = h, M[9] = c, M[10] = u, M[11] = d, M[12] = g, M[13] = f, M[14] = m, M[15] = b, T.markAsUpdated(), T;
  }
  /**
   * 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(e, t, i) {
    const s = new R();
    return R.ComposeToRef(e, t, i, s), s;
  }
  /**
   * 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(e, t, i, s) {
    const r = s._m, n = t._x, a = t._y, o = t._z, h = t._w, c = n + n, u = a + a, d = o + o, g = n * c, f = n * u, m = n * d, b = a * u, T = a * d, M = o * d, v = h * c, A = h * u, E = h * d, y = e._x, x = e._y, D = e._z;
    return r[0] = (1 - (b + M)) * y, r[1] = (f + E) * y, r[2] = (m - A) * y, r[3] = 0, r[4] = (f - E) * x, r[5] = (1 - (g + M)) * x, r[6] = (T + v) * x, r[7] = 0, r[8] = (m + A) * D, r[9] = (T - v) * D, r[10] = (1 - (g + b)) * D, r[11] = 0, r[12] = i._x, r[13] = i._y, r[14] = i._z, r[15] = 1, s.markAsUpdated(), s;
  }
  /**
   * Creates a new identity matrix
   * @returns a new identity matrix
   */
  static Identity() {
    const e = R.FromValues(1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1);
    return e._updateIdentityStatus(!0), e;
  }
  /**
   * Creates a new identity matrix and stores the result in a given matrix
   * @param result defines the target matrix
   * @returns result input
   */
  static IdentityToRef(e) {
    return R.FromValuesToRef(1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, e), e._updateIdentityStatus(!0), e;
  }
  /**
   * Creates a new zero matrix
   * @returns a new zero matrix
   */
  static Zero() {
    const e = R.FromValues(0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0);
    return e._updateIdentityStatus(!1), e;
  }
  /**
   * 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(e) {
    const t = new R();
    return R.RotationXToRef(e, t), t;
  }
  /**
   * 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(e) {
    const t = new e.constructor();
    return e.invertToRef(t), t;
  }
  /**
   * 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(e, t) {
    const i = Math.sin(e), s = Math.cos(e);
    return R.FromValuesToRef(1, 0, 0, 0, 0, s, i, 0, 0, -i, s, 0, 0, 0, 0, 1, t), t._updateIdentityStatus(s === 1 && i === 0), t;
  }
  /**
   * 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(e) {
    const t = new R();
    return R.RotationYToRef(e, t), t;
  }
  /**
   * 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(e, t) {
    const i = Math.sin(e), s = Math.cos(e);
    return R.FromValuesToRef(s, 0, -i, 0, 0, 1, 0, 0, i, 0, s, 0, 0, 0, 0, 1, t), t._updateIdentityStatus(s === 1 && i === 0), t;
  }
  /**
   * 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(e) {
    const t = new R();
    return R.RotationZToRef(e, t), t;
  }
  /**
   * 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(e, t) {
    const i = Math.sin(e), s = Math.cos(e);
    return R.FromValuesToRef(s, i, 0, 0, -i, s, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, t), t._updateIdentityStatus(s === 1 && i === 0), t;
  }
  /**
   * 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(e, t) {
    const i = new R();
    return R.RotationAxisToRef(e, t, i), i;
  }
  /**
   * 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(e, t, i) {
    const s = Math.sin(-t), r = Math.cos(-t), n = 1 - r;
    e.normalize();
    const a = i._m;
    return a[0] = e._x * e._x * n + r, a[1] = e._x * e._y * n - e._z * s, a[2] = e._x * e._z * n + e._y * s, a[3] = 0, a[4] = e._y * e._x * n + e._z * s, a[5] = e._y * e._y * n + r, a[6] = e._y * e._z * n - e._x * s, a[7] = 0, a[8] = e._z * e._x * n - e._y * s, a[9] = e._z * e._y * n + e._x * s, a[10] = e._z * e._z * n + r, a[11] = 0, a[12] = 0, a[13] = 0, a[14] = 0, a[15] = 1, i.markAsUpdated(), i;
  }
  /**
   * 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
   * @returns result input
   */
  static RotationAlignToRef(e, t, i) {
    const s = p.Dot(t, e), r = i._m;
    if (s < -1 + ye)
      r[0] = -1, r[1] = 0, r[2] = 0, r[3] = 0, r[4] = 0, r[5] = -1, r[6] = 0, r[7] = 0, r[8] = 0, r[9] = 0, r[10] = 1, r[11] = 0;
    else {
      const n = p.Cross(t, e), a = 1 / (1 + s);
      r[0] = n._x * n._x * a + s, r[1] = n._y * n._x * a - n._z, r[2] = n._z * n._x * a + n._y, r[3] = 0, r[4] = n._x * n._y * a + n._z, r[5] = n._y * n._y * a + s, r[6] = n._z * n._y * a - n._x, r[7] = 0, r[8] = n._x * n._z * a - n._y, r[9] = n._y * n._z * a + n._x, r[10] = n._z * n._z * a + s, r[11] = 0;
    }
    return r[12] = 0, r[13] = 0, r[14] = 0, r[15] = 1, i.markAsUpdated(), i;
  }
  /**
   * 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(e, t, i) {
    const s = new R();
    return R.RotationYawPitchRollToRef(e, t, i, s), s;
  }
  /**
   * 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(e, t, i, s) {
    return X.RotationYawPitchRollToRef(e, t, i, N.Quaternion[0]), N.Quaternion[0].toRotationMatrix(s), s;
  }
  /**
   * 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(e, t, i) {
    const s = new R();
    return R.ScalingToRef(e, t, i, s), s;
  }
  /**
   * 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(e, t, i, s) {
    return R.FromValuesToRef(e, 0, 0, 0, 0, t, 0, 0, 0, 0, i, 0, 0, 0, 0, 1, s), s._updateIdentityStatus(e === 1 && t === 1 && i === 1), s;
  }
  /**
   * 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(e, t, i) {
    const s = new R();
    return R.TranslationToRef(e, t, i, s), s;
  }
  /**
   * 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(e, t, i, s) {
    return R.FromValuesToRef(1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, e, t, i, 1, s), s._updateIdentityStatus(e === 0 && t === 0 && i === 0), s;
  }
  /**
   * 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(e, t, i) {
    const s = new e.constructor();
    return R.LerpToRef(e, t, i, s), s;
  }
  /**
   * 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(e, t, i, s) {
    const r = s._m, n = e.m, a = t.m;
    for (let o = 0; o < 16; o++)
      r[o] = n[o] * (1 - i) + a[o] * i;
    return s.markAsUpdated(), s;
  }
  /**
   * Builds a new matrix whose values are computed by:
   * * decomposing the 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(e, t, i) {
    const s = new e.constructor();
    return R.DecomposeLerpToRef(e, t, i, s), s;
  }
  /**
   * Update a matrix to values which are computed by:
   * * decomposing the 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(e, t, i, s) {
    const r = N.Vector3[0], n = N.Quaternion[0], a = N.Vector3[1];
    e.decompose(r, n, a);
    const o = N.Vector3[2], h = N.Quaternion[1], c = N.Vector3[3];
    t.decompose(o, h, c);
    const u = N.Vector3[4];
    p.LerpToRef(r, o, i, u);
    const d = N.Quaternion[2];
    X.SlerpToRef(n, h, i, d);
    const g = N.Vector3[5];
    return p.LerpToRef(a, c, i, g), R.ComposeToRef(u, d, g, s), s;
  }
  /**
   * 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(e, t, i) {
    const s = new R();
    return R.LookAtLHToRef(e, t, i, s), s;
  }
  /**
   * 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(e, t, i, s) {
    const r = N.Vector3[0], n = N.Vector3[1], a = N.Vector3[2];
    t.subtractToRef(e, a), a.normalize(), p.CrossToRef(i, a, r);
    const o = r.lengthSquared();
    o === 0 ? r.x = 1 : r.normalizeFromLength(Math.sqrt(o)), p.CrossToRef(a, r, n), n.normalize();
    const h = -p.Dot(r, e), c = -p.Dot(n, e), u = -p.Dot(a, e);
    R.FromValuesToRef(r._x, n._x, a._x, 0, r._y, n._y, a._y, 0, r._z, n._z, a._z, 0, h, c, u, 1, s);
  }
  /**
   * 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(e, t, i) {
    const s = new R();
    return R.LookAtRHToRef(e, t, i, s), s;
  }
  /**
   * 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(e, t, i, s) {
    const r = N.Vector3[0], n = N.Vector3[1], a = N.Vector3[2];
    e.subtractToRef(t, a), a.normalize(), p.CrossToRef(i, a, r);
    const o = r.lengthSquared();
    o === 0 ? r.x = 1 : r.normalizeFromLength(Math.sqrt(o)), p.CrossToRef(a, r, n), n.normalize();
    const h = -p.Dot(r, e), c = -p.Dot(n, e), u = -p.Dot(a, e);
    return R.FromValuesToRef(r._x, n._x, a._x, 0, r._y, n._y, a._y, 0, r._z, n._z, a._z, 0, h, c, u, 1, s), s;
  }
  /**
   * 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(e, t) {
    const i = new R();
    return R.LookDirectionLHToRef(e, t, i), i;
  }
  /**
   * 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(e, t, i) {
    const s = N.Vector3[0];
    s.copyFrom(e), s.scaleInPlace(-1);
    const r = N.Vector3[1];
    return p.CrossToRef(t, s, r), R.FromValuesToRef(r._x, r._y, r._z, 0, t._x, t._y, t._z, 0, s._x, s._y, s._z, 0, 0, 0, 0, 1, i), i;
  }
  /**
   * 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(e, t) {
    const i = new R();
    return R.LookDirectionRHToRef(e, t, i), i;
  }
  /**
   * 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(e, t, i) {
    const s = N.Vector3[2];
    return p.CrossToRef(t, e, s), R.FromValuesToRef(s._x, s._y, s._z, 0, t._x, t._y, t._z, 0, e._x, e._y, e._z, 0, 0, 0, 0, 1, i), i;
  }
  /**
   * 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(e, t, i, s, r) {
    const n = new R();
    return R.OrthoLHToRef(e, t, i, s, n, r), n;
  }
  /**
   * 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(e, t, i, s, r, n) {
    const a = i, o = s, h = 2 / e, c = 2 / t, u = 2 / (o - a), d = -(o + a) / (o - a);
    return R.FromValuesToRef(h, 0, 0, 0, 0, c, 0, 0, 0, 0, u, 0, 0, 0, d, 1, r), n && r.multiplyToRef(gt, r), r._updateIdentityStatus(h === 1 && c === 1 && u === 1 && d === 0), r;
  }
  /**
   * 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(e, t, i, s, r, n, a) {
    const o = new R();
    return R.OrthoOffCenterLHToRef(e, t, i, s, r, n, o, a), o;
  }
  /**
   * 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(e, t, i, s, r, n, a, o) {
    const h = r, c = n, u = 2 / (t - e), d = 2 / (s - i), g = 2 / (c - h), f = -(c + h) / (c - h), m = (e + t) / (e - t), b = (s + i) / (i - s);
    return R.FromValuesToRef(u, 0, 0, 0, 0, d, 0, 0, 0, 0, g, 0, m, b, f, 1, a), o && a.multiplyToRef(gt, a), a.markAsUpdated(), a;
  }
  /**
   * 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(e, t, i, s, r, n, a) {
    const o = new R();
    return R.OrthoOffCenterRHToRef(e, t, i, s, r, n, o, a), o;
  }
  /**
   * 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(e, t, i, s, r, n, a, o) {
    return R.OrthoOffCenterLHToRef(e, t, i, s, r, n, a, o), a._m[10] *= -1, a;
  }
  /**
   * 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(e, t, i, s, r, n = 0) {
    const a = new R(), o = i, h = s, c = 2 * o / e, u = 2 * o / t, d = (h + o) / (h - o), g = -2 * h * o / (h - o), f = Math.tan(n);
    return R.FromValuesToRef(c, 0, 0, 0, 0, u, 0, f, 0, 0, d, 1, 0, 0, g, 0, a), r && a.multiplyToRef(gt, a), a._updateIdentityStatus(!1), a;
  }
  /**
   * 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(e, t, i, s, r, n = 0, a = !1) {
    const o = new R();
    return R.PerspectiveFovLHToRef(e, t, i, s, o, !0, r, n, a), o;
  }
  /**
   * 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(e, t, i, s, r, n = !0, a, o = 0, h = !1) {
    const c = i, u = s, d = 1 / Math.tan(e * 0.5), g = n ? d / t : d, f = n ? d : d * t, m = h && c === 0 ? -1 : u !== 0 ? (u + c) / (u - c) : 1, b = h && c === 0 ? 2 * u : u !== 0 ? -2 * u * c / (u - c) : -2 * c, T = Math.tan(o);
    return R.FromValuesToRef(g, 0, 0, 0, 0, f, 0, T, 0, 0, m, 1, 0, 0, b, 0, r), a && r.multiplyToRef(gt, r), r._updateIdentityStatus(!1), r;
  }
  /**
   * 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(e, t, i, s, r, n = !0, a, o = 0) {
    const h = 1 / Math.tan(e * 0.5), c = n ? h / t : h, u = n ? h : h * t, d = Math.tan(o);
    return R.FromValuesToRef(c, 0, 0, 0, 0, u, 0, d, 0, 0, -i, 1, 0, 0, 1, 0, r), a && r.multiplyToRef(gt, r), r._updateIdentityStatus(!1), r;
  }
  /**
   * 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(e, t, i, s, r, n = 0, a = !1) {
    const o = new R();
    return R.PerspectiveFovRHToRef(e, t, i, s, o, !0, r, n, a), o;
  }
  /**
   * 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(e, t, i, s, r, n = !0, a, o = 0, h = !1) {
    const c = i, u = s, d = 1 / Math.tan(e * 0.5), g = n ? d / t : d, f = n ? d : d * t, m = h && c === 0 ? 1 : u !== 0 ? -(u + c) / (u - c) : -1, b = h && c === 0 ? 2 * u : u !== 0 ? -2 * u * c / (u - c) : -2 * c, T = Math.tan(o);
    return R.FromValuesToRef(g, 0, 0, 0, 0, f, 0, T, 0, 0, m, -1, 0, 0, b, 0, r), a && r.multiplyToRef(gt, r), r._updateIdentityStatus(!1), r;
  }
  /**
   * 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(e, t, i, s, r, n = !0, a, o = 0) {
    const h = 1 / Math.tan(e * 0.5), c = n ? h / t : h, u = n ? h : h * t, d = Math.tan(o);
    return R.FromValuesToRef(c, 0, 0, 0, 0, u, 0, d, 0, 0, -i, -1, 0, 0, -1, 0, r), a && r.multiplyToRef(gt, r), r._updateIdentityStatus(!1), r;
  }
  /**
   * Stores a perspective projection for WebVR info a given matrix
   * Example Playground - https://playground.babylonjs.com/#AV9X17#92
   * @param fov defines the field of view
   * @param fov.upDegrees
   * @param fov.downDegrees
   * @param fov.leftDegrees
   * @param fov.rightDegrees
   * @param znear defines the near clip plane
   * @param zfar defines the far clip plane
   * @param result defines the target matrix
   * @param rightHanded defines if the matrix must be in right-handed mode (false by default)
   * @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 PerspectiveFovWebVRToRef(e, t, i, s, r = !1, n, a = 0) {
    const o = r ? -1 : 1, h = Math.tan(e.upDegrees * Math.PI / 180), c = Math.tan(e.downDegrees * Math.PI / 180), u = Math.tan(e.leftDegrees * Math.PI / 180), d = Math.tan(e.rightDegrees * Math.PI / 180), g = 2 / (u + d), f = 2 / (h + c), m = Math.tan(a), b = s._m;
    return b[0] = g, b[1] = b[2] = b[3] = b[4] = 0, b[5] = f, b[6] = 0, b[7] = m, b[8] = (u - d) * g * 0.5, b[9] = -((h - c) * f * 0.5), b[10] = -i / (t - i), b[11] = 1 * o, b[12] = b[13] = b[15] = 0, b[14] = -(2 * i * t) / (i - t), n && s.multiplyToRef(gt, s), s.markAsUpdated(), s;
  }
  /**
   * 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(e, t, i, s, r, n) {
    const a = e.width, o = e.height, h = e.x, c = e.y, u = R.FromValues(a / 2, 0, 0, 0, 0, -o / 2, 0, 0, 0, 0, n - r, 0, h + a / 2, o / 2 + c, r, 1), d = new t.constructor();
    return t.multiplyToRef(i, d), d.multiplyToRef(s, d), d.multiplyToRef(u, d);
  }
  /**
   * 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(e) {
    const t = e.m, i = [t[0], t[1], t[4], t[5]];
    return be.MatrixUse64Bits ? i : new Float32Array(i);
  }
  /**
   * 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(e) {
    const t = e.m, i = [t[0], t[1], t[2], t[4], t[5], t[6], t[8], t[9], t[10]];
    return be.MatrixUse64Bits ? i : new Float32Array(i);
  }
  /**
   * 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(e) {
    const t = new e.constructor();
    return R.TransposeToRef(e, t), t;
  }
  /**
   * 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(e, t) {
    const i = t._m, s = e.m;
    return i[0] = s[0], i[1] = s[4], i[2] = s[8], i[3] = s[12], i[4] = s[1], i[5] = s[5], i[6] = s[9], i[7] = s[13], i[8] = s[2], i[9] = s[6], i[10] = s[10], i[11] = s[14], i[12] = s[3], i[13] = s[7], i[14] = s[11], i[15] = s[15], t.markAsUpdated(), t._updateIdentityStatus(e._isIdentity, e._isIdentityDirty), t;
  }
  /**
   * 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(e) {
    const t = new R();
    return R.ReflectionToRef(e, t), t;
  }
  /**
   * 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(e, t) {
    e.normalize();
    const i = e.normal.x, s = e.normal.y, r = e.normal.z, n = -2 * i, a = -2 * s, o = -2 * r;
    return R.FromValuesToRef(n * i + 1, a * i, o * i, 0, n * s, a * s + 1, o * s, 0, n * r, a * r, o * r + 1, 0, n * e.d, a * e.d, o * e.d, 1, t), t;
  }
  /**
   * 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(e, t, i, s) {
    return R.FromValuesToRef(e._x, e._y, e._z, 0, t._x, t._y, t._z, 0, i._x, i._y, i._z, 0, 0, 0, 0, 1, s), s;
  }
  /**
   * 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(e, t) {
    const i = e._x * e._x, s = e._y * e._y, r = e._z * e._z, n = e._x * e._y, a = e._z * e._w, o = e._z * e._x, h = e._y * e._w, c = e._y * e._z, u = e._x * e._w;
    return t._m[0] = 1 - 2 * (s + r), t._m[1] = 2 * (n + a), t._m[2] = 2 * (o - h), t._m[3] = 0, t._m[4] = 2 * (n - a), t._m[5] = 1 - 2 * (r + i), t._m[6] = 2 * (c + u), t._m[7] = 0, t._m[8] = 2 * (o + h), t._m[9] = 2 * (c - u), t._m[10] = 1 - 2 * (s + i), t._m[11] = 0, t._m[12] = 0, t._m[13] = 0, t._m[14] = 0, t._m[15] = 1, t.markAsUpdated(), t;
  }
}
R._UpdateFlagSeed = 0;
R._IdentityReadOnly = R.Identity();
class N {
}
N.Vector3 = Ee.BuildTuple(11, p.Zero);
N.Matrix = Ee.BuildTuple(2, R.Identity);
N.Quaternion = Ee.BuildTuple(3, X.Zero);
class C {
}
C.Vector2 = Ee.BuildTuple(3, le.Zero);
C.Vector3 = Ee.BuildTuple(13, p.Zero);
C.Vector4 = Ee.BuildTuple(3, de.Zero);
C.Quaternion = Ee.BuildTuple(2, X.Zero);
C.Matrix = Ee.BuildTuple(8, R.Identity);
dt("BABYLON.Vector2", le);
dt("BABYLON.Vector3", p);
dt("BABYLON.Vector4", de);
dt("BABYLON.Matrix", R);
const gt = R.FromValues(1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0.5, 0, 0, 0, 0.5, 1);
class Li {
  constructor() {
    this.rootNodes = new Array(), this.cameras = new Array(), this.lights = new Array(), this.meshes = new Array(), this.skeletons = new Array(), this.particleSystems = new Array(), this.animations = [], this.animationGroups = new Array(), this.multiMaterials = new Array(), this.materials = new Array(), this.morphTargetManagers = new Array(), this.geometries = new Array(), this.transformNodes = new Array(), this.actionManagers = new Array(), this.textures = new Array(), this._environmentTexture = null, this.postProcesses = new Array();
  }
  /**
   * Adds a parser in the list of available ones
   * @param name Defines the name of the parser
   * @param parser Defines the parser to add
   */
  static AddParser(e, t) {
    this._BabylonFileParsers[e] = t;
  }
  /**
   * Gets a general parser from the list of available ones
   * @param name Defines the name of the parser
   * @returns the requested parser or null
   */
  static GetParser(e) {
    return this._BabylonFileParsers[e] ? this._BabylonFileParsers[e] : null;
  }
  /**
   * Adds n individual parser in the list of available ones
   * @param name Defines the name of the parser
   * @param parser Defines the parser to add
   */
  static AddIndividualParser(e, t) {
    this._IndividualBabylonFileParsers[e] = t;
  }
  /**
   * Gets an individual parser from the list of available ones
   * @param name Defines the name of the parser
   * @returns the requested parser or null
   */
  static GetIndividualParser(e) {
    return this._IndividualBabylonFileParsers[e] ? this._IndividualBabylonFileParsers[e] : null;
  }
  /**
   * Parser json data and populate both a scene and its associated container object
   * @param jsonData Defines the data to parse
   * @param scene Defines the scene to parse the data for
   * @param container Defines the container attached to the parsing sequence
   * @param rootUrl Defines the root url of the data
   */
  static Parse(e, t, i, s) {
    for (const r in this._BabylonFileParsers)
      Object.prototype.hasOwnProperty.call(this._BabylonFileParsers, r) && this._BabylonFileParsers[r](e, t, i, s);
  }
  /**
   * 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;
  }
  set environmentTexture(e) {
    this._environmentTexture = e;
  }
  /**
   * @returns all meshes, lights, cameras, transformNodes and bones
   */
  getNodes() {
    let e = new Array();
    return e = e.concat(this.meshes), e = e.concat(this.lights), e = e.concat(this.cameras), e = e.concat(this.transformNodes), this.skeletons.forEach((t) => e = e.concat(t.bones)), e;
  }
}
Li._BabylonFileParsers = {};
Li._IndividualBabylonFileParsers = {};
function F(l, e, t, i) {
  var s = arguments.length, r = s < 3 ? e : i === null ? i = Object.getOwnPropertyDescriptor(e, t) : i, n;
  if (typeof Reflect == "object" && typeof Reflect.decorate == "function")
    r = Reflect.decorate(l, e, t, i);
  else
    for (var a = l.length - 1; a >= 0; a--)
      (n = l[a]) && (r = (s < 3 ? n(r) : s > 3 ? n(e, t, r) : n(e, t)) || r);
  return s > 3 && r && Object.defineProperty(e, t, r), r;
}
function St(l) {
  return Math.pow(l, Zs);
}
function Dt(l) {
  return l <= 0.04045 ? 0.0773993808 * l : Math.pow(0.947867299 * (l + 0.055), 2.4);
}
function Ft(l) {
  return Math.pow(l, qs);
}
function wt(l) {
  return l <= 31308e-7 ? 12.92 * l : 1.055 * Math.pow(l, 0.41666) - 0.055;
}
class te {
  /**
   * 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(e = 0, t = 0, i = 0) {
    this.r = e, this.g = t, this.b = i;
  }
  /**
   * 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 e = this.r * 255 | 0;
    return e = e * 397 ^ (this.g * 255 | 0), e = e * 397 ^ (this.b * 255 | 0), e;
  }
  // 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(e, t = 0) {
    return e[t] = this.r, e[t + 1] = this.g, e[t + 2] = this.b, 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(e, t = 0) {
    return te.FromArrayToRef(e, t, this), 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(e = 1) {
    return new Oe(this.r, this.g, this.b, e);
  }
  /**
   * 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(e) {
    return new te(this.r * e.r, this.g * e.g, this.b * e.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 current Color3
   */
  multiplyToRef(e, t) {
    return t.r = this.r * e.r, t.g = this.g * e.g, t.b = this.b * e.b, this;
  }
  /**
   * Determines equality between Color3 objects
   * @param otherColor defines the second operand
   * @returns true if the rgb values are equal to the given ones
   */
  equals(e) {
    return e && this.r === e.r && this.g === e.g && this.b === e.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
   */
  equalsFloats(e, t, i) {
    return this.r === e && this.g === t && this.b === i;
  }
  /**
   * 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(e) {
    return new te(this.r * e, this.g * e, this.b * e);
  }
  /**
   * Multiplies the Color3 values by the float "scale"
   * @param scale defines the scaling factor to apply
   * @returns the current updated Color3
   */
  scaleInPlace(e) {
    return this.r *= e, this.g *= e, this.b *= e, 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 unmodified current Color3
   */
  scaleToRef(e, t) {
    return t.r = this.r * e, t.g = this.g * e, t.b = this.b * e, this;
  }
  /**
   * 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 unmodified current Color3
   */
  scaleAndAddToRef(e, t) {
    return t.r += this.r * e, t.g += this.g * e, t.b += this.b * e, this;
  }
  /**
   * 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 original Color3
   */
  clampToRef(e = 0, t = 1, i) {
    return i.r = H.Clamp(this.r, e, t), i.g = H.Clamp(this.g, e, t), i.b = H.Clamp(this.b, e, t), this;
  }
  /**
   * 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(e) {
    return new te(this.r + e.r, this.g + e.g, this.b + e.b);
  }
  /**
   * 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(e, t) {
    return t.r = this.r + e.r, t.g = this.g + e.g, t.b = this.b + e.b, this;
  }
  /**
   * 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(e) {
    return new te(this.r - e.r, this.g - e.g, this.b - e.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(e, t) {
    return t.r = this.r - e.r, t.g = this.g - e.g, t.b = this.b - e.b, this;
  }
  /**
   * Copy the current object
   * @returns a new Color3 copied the current one
   */
  clone() {
    return new te(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(e) {
    return this.r = e.r, this.g = e.g, this.b = e.b, 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(e, t, i) {
    return this.r = e, this.g = t, this.b = i, 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(e, t, i) {
    return this.copyFromFloats(e, t, i);
  }
  /**
   * Compute the Color3 hexadecimal code as a string
   * @returns a string containing the hexadecimal representation of the Color3 object
   */
  toHexString() {
    const e = Math.round(this.r * 255), t = Math.round(this.g * 255), i = Math.round(this.b * 255);
    return "#" + H.ToHex(e) + H.ToHex(t) + H.ToHex(i);
  }
  /**
   * Converts current color in rgb space to HSV values
   * @returns a new color3 representing the HSV values
   */
  toHSV() {
    const e = new te();
    return this.toHSVToRef(e), e;
  }
  /**
   * Converts current color in rgb space to HSV values
   * @param result defines the Color3 where to store the HSV values
   */
  toHSVToRef(e) {
    const t = this.r, i = this.g, s = this.b, r = Math.max(t, i, s), n = Math.min(t, i, s);
    let a = 0, o = 0;
    const h = r, c = r - n;
    r !== 0 && (o = c / r), r != n && (r == t ? (a = (i - s) / c, i < s && (a += 6)) : r == i ? a = (s - t) / c + 2 : r == s && (a = (t - i) / c + 4), a *= 60), e.r = a, e.g = o, e.b = h;
  }
  /**
   * 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(e = !1) {
    const t = new te();
    return this.toLinearSpaceToRef(t, e), t;
  }
  /**
   * 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(e, t = !1) {
    return t ? (e.r = Dt(this.r), e.g = Dt(this.g), e.b = Dt(this.b)) : (e.r = St(this.r), e.g = St(this.g), e.b = St(this.b)), 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(e = !1) {
    const t = new te();
    return this.toGammaSpaceToRef(t, e), t;
  }
  /**
   * 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(e, t = !1) {
    return t ? (e.r = wt(this.r), e.g = wt(this.g), e.b = wt(this.b)) : (e.r = Ft(this.r), e.g = Ft(this.g), e.b = Ft(this.b)), this;
  }
  /**
   * Converts Hue, saturation and value to a Color3 (RGB)
   * @param hue defines the hue
   * @param saturation defines the saturation
   * @param value defines the value
   * @param result defines the Color3 where to store the RGB values
   */
  static HSVtoRGBToRef(e, t, i, s) {
    const r = i * t, n = e / 60, a = r * (1 - Math.abs(n % 2 - 1));
    let o = 0, h = 0, c = 0;
    n >= 0 && n <= 1 ? (o = r, h = a) : n >= 1 && n <= 2 ? (o = a, h = r) : n >= 2 && n <= 3 ? (h = r, c = a) : n >= 3 && n <= 4 ? (h = a, c = r) : n >= 4 && n <= 5 ? (o = a, c = r) : n >= 5 && n <= 6 && (o = r, c = a);
    const u = i - r;
    s.set(o + u, h + u, c + u);
  }
  /**
   * 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(e, t, i) {
    const s = new te(0, 0, 0);
    return te.HSVtoRGBToRef(e, t, i, s), s;
  }
  /**
   * 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(e) {
    if (e.substring(0, 1) !== "#" || e.length !== 7)
      return new te(0, 0, 0);
    const t = parseInt(e.substring(1, 3), 16), i = parseInt(e.substring(3, 5), 16), s = parseInt(e.substring(5, 7), 16);
    return te.FromInts(t, i, s);
  }
  /**
   * 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(e, t = 0) {
    return new te(e[t], e[t + 1], e[t + 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(e, t = 0, i) {
    i.r = e[t], i.g = e[t + 1], i.b = e[t + 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(e, t, i) {
    return new te(e / 255, t / 255, i / 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(e, t, i) {
    const s = new te(0, 0, 0);
    return te.LerpToRef(e, t, i, s), s;
  }
  /**
   * 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(e, t, i, s) {
    s.r = e.r + (t.r - e.r) * i, s.g = e.g + (t.g - e.g) * i, s.b = e.b + (t.b - e.b) * i;
  }
  /**
   * 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(e, t, i, s, r) {
    const n = r * r, a = r * n, o = 2 * a - 3 * n + 1, h = -2 * a + 3 * n, c = a - 2 * n + r, u = a - n, d = e.r * o + i.r * h + t.r * c + s.r * u, g = e.g * o + i.g * h + t.g * c + s.g * u, f = e.b * o + i.b * h + t.b * c + s.b * u;
    return new te(d, g, f);
  }
  /**
   * 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(e, t, i, s, r) {
    const n = te.Black();
    return this.Hermite1stDerivativeToRef(e, t, i, s, r, n), n;
  }
  /**
   * 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(e, t, i, s, r, n) {
    const a = r * r;
    n.r = (a - r) * 6 * e.r + (3 * a - 4 * r + 1) * t.r + (-a + r) * 6 * i.r + (3 * a - 2 * r) * s.r, n.g = (a - r) * 6 * e.g + (3 * a - 4 * r + 1) * t.g + (-a + r) * 6 * i.g + (3 * a - 2 * r) * s.g, n.b = (a - r) * 6 * e.b + (3 * a - 4 * r + 1) * t.b + (-a + r) * 6 * i.b + (3 * a - 2 * r) * s.b;
  }
  /**
   * Returns a Color3 value containing a red color
   * @returns a new Color3 object
   */
  static Red() {
    return new te(1, 0, 0);
  }
  /**
   * Returns a Color3 value containing a green color
   * @returns a new Color3 object
   */
  static Green() {
    return new te(0, 1, 0);
  }
  /**
   * Returns a Color3 value containing a blue color
   * @returns a new Color3 object
   */
  static Blue() {
    return new te(0, 0, 1);
  }
  /**
   * Returns a Color3 value containing a black color
   * @returns a new Color3 object
   */
  static Black() {
    return new te(0, 0, 0);
  }
  /**
   * Gets a Color3 value containing a black color that must not be updated
   */
  static get BlackReadOnly() {
    return te._BlackReadOnly;
  }
  /**
   * Returns a Color3 value containing a white color
   * @returns a new Color3 object
   */
  static White() {
    return new te(1, 1, 1);
  }
  /**
   * Returns a Color3 value containing a purple color
   * @returns a new Color3 object
   */
  static Purple() {
    return new te(0.5, 0, 0.5);
  }
  /**
   * Returns a Color3 value containing a magenta color
   * @returns a new Color3 object
   */
  static Magenta() {
    return new te(1, 0, 1);
  }
  /**
   * Returns a Color3 value containing a yellow color
   * @returns a new Color3 object
   */
  static Yellow() {
    return new te(1, 1, 0);
  }
  /**
   * Returns a Color3 value containing a gray color
   * @returns a new Color3 object
   */
  static Gray() {
    return new te(0.5, 0.5, 0.5);
  }
  /**
   * Returns a Color3 value containing a teal color
   * @returns a new Color3 object
   */
  static Teal() {
    return new te(0, 1, 1);
  }
  /**
   * Returns a Color3 value containing a random color
   * @returns a new Color3 object
   */
  static Random() {
    return new te(Math.random(), Math.random(), Math.random());
  }
}
te._BlackReadOnly = te.Black();
let Oe = class ve {
  /**
   * 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(e = 0, t = 0, i = 0, s = 1) {
    this.r = e, this.g = t, this.b = i, this.a = s;
  }
  // Operators
  /**
   * Adds in place the given Color4 values to the current Color4 object
   * @param right defines the second operand
   * @returns the current updated Color4 object
   */
  addInPlace(e) {
    return this.r += e.r, this.g += e.g, this.b += e.b, this.a += e.a, this;
  }
  /**
   * 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(e, t = 0) {
    return e[t] = this.r, e[t + 1] = this.g, e[t + 2] = this.b, e[t + 3] = this.a, 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(e, t = 0) {
    return ve.FromArrayToRef(e, t, this), 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(e) {
    return e && this.r === e.r && this.g === e.g && this.b === e.b && this.a === e.a;
  }
  /**
   * Creates a new Color4 set with the added values of the current Color4 and of the given one
   * @param right defines the second operand
   * @returns a new Color4 object
   */
  add(e) {
    return new ve(this.r + e.r, this.g + e.g, this.b + e.b, this.a + e.a);
  }
  /**
   * Creates a new Color4 set with the subtracted values of the given one from the current Color4
   * @param right defines the second operand
   * @returns a new Color4 object
   */
  subtract(e) {
    return new ve(this.r - e.r, this.g - e.g, this.b - e.b, this.a - e.a);
  }
  /**
   * Subtracts the given ones from the current Color4 values and stores the results in "result"
   * @param right defines the second operand
   * @param result defines the Color4 object where to store the result
   * @returns the current Color4 object
   */
  subtractToRef(e, t) {
    return t.r = this.r - e.r, t.g = this.g - e.g, t.b = this.b - e.b, t.a = this.a - e.a, this;
  }
  /**
   * 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(e) {
    return new ve(this.r * e, this.g * e, this.b * e, this.a * e);
  }
  /**
   * Multiplies the Color4 values by the float "scale"
   * @param scale defines the scaling factor to apply
   * @returns the current updated Color4
   */
  scaleInPlace(e) {
    return this.r *= e, this.g *= e, this.b *= e, this.a *= e, 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 current unmodified Color4
   */
  scaleToRef(e, t) {
    return t.r = this.r * e, t.g = this.g * e, t.b = this.b * e, t.a = this.a * e, this;
  }
  /**
   * 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 unmodified current Color4
   */
  scaleAndAddToRef(e, t) {
    return t.r += this.r * e, t.g += this.g * e, t.b += this.b * e, t.a += this.a * e, this;
  }
  /**
   * 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 current Color4
   */
  clampToRef(e = 0, t = 1, i) {
    return i.r = H.Clamp(this.r, e, t), i.g = H.Clamp(this.g, e, t), i.b = H.Clamp(this.b, e, t), i.a = H.Clamp(this.a, e, t), this;
  }
  /**
   * 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(e) {
    return new ve(this.r * e.r, this.g * e.g, this.b * e.b, this.a * e.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(e, t) {
    return t.r = this.r * e.r, t.g = this.g * e.g, t.b = this.b * e.b, t.a = this.a * e.a, t;
  }
  /**
   * 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 e = this.r * 255 | 0;
    return e = e * 397 ^ (this.g * 255 | 0), e = e * 397 ^ (this.b * 255 | 0), e = e * 397 ^ (this.a * 255 | 0), e;
  }
  /**
   * Creates a new Color4 copied from the current one
   * @returns a new Color4 object
   */
  clone() {
    return new ve(this.r, this.g, this.b, this.a);
  }
  /**
   * Copies the given Color4 values into the current one
   * @param source defines the source Color4 object
   * @returns the current updated Color4 object
   */
  copyFrom(e) {
    return this.r = e.r, this.g = e.g, this.b = e.b, this.a = e.a, 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(e, t, i, s) {
    return this.r = e, this.g = t, this.b = i, this.a = s, 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(e, t, i, s) {
    return this.copyFromFloats(e, t, i, s);
  }
  /**
   * 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(e = !1) {
    const t = Math.round(this.r * 255), i = Math.round(this.g * 255), s = Math.round(this.b * 255);
    if (e)
      return "#" + H.ToHex(t) + H.ToHex(i) + H.ToHex(s);
    const r = Math.round(this.a * 255);
    return "#" + H.ToHex(t) + H.ToHex(i) + H.ToHex(s) + H.ToHex(r);
  }
  /**
   * 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(e = !1) {
    const t = new ve();
    return this.toLinearSpaceToRef(t, e), t;
  }
  /**
   * 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(e, t = !1) {
    return t ? (e.r = Dt(this.r), e.g = Dt(this.g), e.b = Dt(this.b)) : (e.r = St(this.r), e.g = St(this.g), e.b = St(this.b)), e.a = this.a, 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(e = !1) {
    const t = new ve();
    return this.toGammaSpaceToRef(t, e), t;
  }
  /**
   * 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(e, t = !1) {
    return t ? (e.r = wt(this.r), e.g = wt(this.g), e.b = wt(this.b)) : (e.r = Ft(this.r), e.g = Ft(this.g), e.b = Ft(this.b)), e.a = this.a, 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(e) {
    if (e.substring(0, 1) !== "#" || e.length !== 9 && e.length !== 7)
      return new ve(0, 0, 0, 0);
    const t = parseInt(e.substring(1, 3), 16), i = parseInt(e.substring(3, 5), 16), s = parseInt(e.substring(5, 7), 16), r = e.length === 9 ? parseInt(e.substring(7, 9), 16) : 255;
    return ve.FromInts(t, i, s, r);
  }
  /**
   * 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(e, t, i) {
    const s = new ve(0, 0, 0, 0);
    return ve.LerpToRef(e, t, i, s), s;
  }
  /**
   * 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
   */
  static LerpToRef(e, t, i, s) {
    s.r = e.r + (t.r - e.r) * i, s.g = e.g + (t.g - e.g) * i, s.b = e.b + (t.b - e.b) * i, s.a = e.a + (t.a - e.a) * i;
  }
  /**
   * 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(e, t, i, s, r) {
    const n = r * r, a = r * n, o = 2 * a - 3 * n + 1, h = -2 * a + 3 * n, c = a - 2 * n + r, u = a - n, d = e.r * o + i.r * h + t.r * c + s.r * u, g = e.g * o + i.g * h + t.g * c + s.g * u, f = e.b * o + i.b * h + t.b * c + s.b * u, m = e.a * o + i.a * h + t.a * c + s.a * u;
    return new ve(d, g, f, m);
  }
  /**
   * 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(e, t, i, s, r) {
    const n = new ve();
    return this.Hermite1stDerivativeToRef(e, t, i, s, r, n), n;
  }
  /**
   * 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(e, t, i, s, r, n) {
    const a = r * r;
    n.r = (a - r) * 6 * e.r + (3 * a - 4 * r + 1) * t.r + (-a + r) * 6 * i.r + (3 * a - 2 * r) * s.r, n.g = (a - r) * 6 * e.g + (3 * a - 4 * r + 1) * t.g + (-a + r) * 6 * i.g + (3 * a - 2 * r) * s.g, n.b = (a - r) * 6 * e.b + (3 * a - 4 * r + 1) * t.b + (-a + r) * 6 * i.b + (3 * a - 2 * r) * s.b, n.a = (a - r) * 6 * e.a + (3 * a - 4 * r + 1) * t.a + (-a + r) * 6 * i.a + (3 * a - 2 * r) * s.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(e, t = 1) {
    return new ve(e.r, e.g, e.b, t);
  }
  /**
   * 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(e, t = 0) {
    return new ve(e[t], e[t + 1], e[t + 2], e[t + 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(e, t = 0, i) {
    i.r = e[t], i.g = e[t + 1], i.b = e[t + 2], i.a = e[t + 3];
  }
  /**
   * 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)
   * @param a defines the alpha component to read from (value between 0 and 255)
   * @returns a new Color3 object
   */
  static FromInts(e, t, i, s) {
    return new ve(e / 255, t / 255, i / 255, s / 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(e, t) {
    if (e.length === t * 3) {
      const i = [];
      for (let s = 0; s < e.length; s += 3) {
        const r = s / 3 * 4;
        i[r] = e[s], i[r + 1] = e[s + 1], i[r + 2] = e[s + 2], i[r + 3] = 1;
      }
      return i;
    }
    return e;
  }
};
class us {
}
us.Color3 = Ee.BuildArray(3, te.Black);
us.Color4 = Ee.BuildArray(3, () => new Oe(0, 0, 0, 0));
dt("BABYLON.Color3", te);
dt("BABYLON.Color4", Oe);
const Jt = {}, jt = {}, Wi = function(l, e, t) {
  const i = l();
  re && re.HasTags(e) && re.AddTagsTo(i, re.GetTags(e, !0));
  const s = Ri(i);
  for (const r in s) {
    const n = s[r], a = e[r], o = n.type;
    if (a != null && (r !== "uniqueId" || he.AllowLoadingUniqueId))
      switch (o) {
        case 0:
        case 6:
        case 11:
          i[r] = a;
          break;
        case 1:
          i[r] = t || a.isRenderTarget ? a : a.clone();
          break;
        case 2:
        case 3:
        case 4:
        case 5:
        case 7:
        case 10:
        case 12:
          i[r] = t ? a : a.clone();
          break;
      }
  }
  return i;
};
function Js(l) {
  const e = l.getClassName();
  return Jt[e] || (Jt[e] = {}), Jt[e];
}
function Ri(l) {
  const e = l.getClassName();
  if (jt[e])
    return jt[e];
  jt[e] = {};
  const t = jt[e];
  let i = l, s = e;
  for (; s; ) {
    const r = Jt[s];
    for (const o in r)
      t[o] = r[o];
    let n, a = !1;
    do {
      if (n = Object.getPrototypeOf(i), !n.getClassName) {
        a = !0;
        break;
      }
      if (n.getClassName() !== s)
        break;
      i = n;
    } while (n);
    if (a)
      break;
    s = n.getClassName(), i = n;
  }
  return t;
}
function tt(l, e) {
  return (t, i) => {
    const s = Js(t);
    s[i] || (s[i] = { type: l, sourceName: e });
  };
}
function er(l, e = null) {
  return (t, i) => {
    const s = e || "_" + i;
    Object.defineProperty(t, i, {
      get: function() {
        return this[s];
      },
      set: function(r) {
        typeof this.equals == "function" && this.equals(r) || this[s] !== r && (this[s] = r, t[l].apply(this));
      },
      enumerable: !0,
      configurable: !0
    });
  };
}
function Fr(l, e = null) {
  return er(l, e);
}
function B(l) {
  return tt(0, l);
}
function tr(l) {
  return tt(1, l);
}
function wr(l) {
  return tt(2, l);
}
function Or(l) {
  return tt(3, l);
}
function Br(l) {
  return tt(4, l);
}
function Ht(l) {
  return tt(5, l);
}
function Lr(l) {
  return tt(6, l);
}
function ir(l) {
  return tt(7, l);
}
function sr(l) {
  return tt(8, l);
}
function rr(l) {
  return tt(10, l);
}
class he {
  /**
   * Appends the serialized animations from the source animations
   * @param source Source containing the animations
   * @param destination Target to store the animations
   */
  static AppendSerializedAnimations(e, t) {
    if (e.animations) {
      t.animations = [];
      for (let i = 0; i < e.animations.length; i++) {
        const s = e.animations[i];
        t.animations.push(s.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(e, t) {
    t || (t = {}), re && (t.tags = re.GetTags(e));
    const i = Ri(e);
    for (const s in i) {
      const r = i[s], n = r.sourceName || s, a = r.type, o = e[s];
      if (o != null && (s !== "uniqueId" || he.AllowLoadingUniqueId))
        switch (a) {
          case 0:
            t[n] = o;
            break;
          case 1:
            t[n] = o.serialize();
            break;
          case 2:
            t[n] = o.asArray();
            break;
          case 3:
            t[n] = o.serialize();
            break;
          case 4:
            t[n] = o.asArray();
            break;
          case 5:
            t[n] = o.asArray();
            break;
          case 6:
            t[n] = o.id;
            break;
          case 7:
            t[n] = o.serialize();
            break;
          case 8:
            t[n] = o.asArray();
            break;
          case 9:
            t[n] = o.serialize();
            break;
          case 10:
            t[n] = o.asArray();
            break;
          case 11:
            t[n] = o.id;
            break;
          case 12:
            t[n] = o.asArray();
            break;
        }
    }
    return t;
  }
  /**
   * 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(e, t, i, s) {
    s || (s = "");
    const r = Ri(t);
    for (const n in r) {
      const a = r[n], o = e[a.sourceName || n], h = a.type;
      if (o != null && (n !== "uniqueId" || he.AllowLoadingUniqueId)) {
        const c = t;
        switch (h) {
          case 0:
            c[n] = o;
            break;
          case 1:
            i && (c[n] = he._TextureParser(o, i, s));
            break;
          case 2:
            c[n] = te.FromArray(o);
            break;
          case 3:
            c[n] = he._FresnelParametersParser(o);
            break;
          case 4:
            c[n] = le.FromArray(o);
            break;
          case 5:
            c[n] = p.FromArray(o);
            break;
          case 6:
            i && (c[n] = i.getLastMeshById(o));
            break;
          case 7:
            c[n] = he._ColorCurvesParser(o);
            break;
          case 8:
            c[n] = Oe.FromArray(o);
            break;
          case 9:
            c[n] = he._ImageProcessingConfigurationParser(o);
            break;
          case 10:
            c[n] = X.FromArray(o);
            break;
          case 11:
            i && (c[n] = i.getCameraById(o));
            break;
          case 12:
            c[n] = R.FromArray(o);
            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(e, t, i, s = null) {
    const r = e();
    return re && re.AddTagsTo(r, t.tags), he.ParseProperties(t, r, i, s), r;
  }
  /**
   * Clones an object
   * @param creationFunction defines the function used to instanciate the new object
   * @param source defines the source object
   * @returns the cloned object
   */
  static Clone(e, t) {
    return Wi(e, t, !1);
  }
  /**
   * 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(e, t) {
    return Wi(e, t, !0);
  }
}
he.AllowLoadingUniqueId = !1;
he._ImageProcessingConfigurationParser = (l) => {
  throw Y("ImageProcessingConfiguration");
};
he._FresnelParametersParser = (l) => {
  throw Y("FresnelParameters");
};
he._ColorCurvesParser = (l) => {
  throw Y("ColorCurves");
};
he._TextureParser = (l, e, t) => {
  throw Y("Texture");
};
function yt(l, e, t, i) {
  const s = t.value;
  t.value = (...r) => {
    let n = s;
    if (typeof _native < "u" && _native[e]) {
      const a = _native[e];
      i ? n = (...o) => i(...o) ? a(...o) : s(...o) : n = a;
    }
    return l[e] = n, n(...r);
  };
}
yt.filter = function(l) {
  return (e, t, i) => yt(e, t, i, l);
};
class ue {
  constructor() {
    this._dirty = !0, this._tempColor = new Oe(0, 0, 0, 0), this._globalCurve = new Oe(0, 0, 0, 0), this._highlightsCurve = new Oe(0, 0, 0, 0), this._midtonesCurve = new Oe(0, 0, 0, 0), this._shadowsCurve = new Oe(0, 0, 0, 0), this._positiveCurve = new Oe(0, 0, 0, 0), this._negativeCurve = new Oe(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(e) {
    this._globalHue = e, this._dirty = !0;
  }
  /**
   * 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(e) {
    this._globalDensity = e, this._dirty = !0;
  }
  /**
   * 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(e) {
    this._globalSaturation = e, this._dirty = !0;
  }
  /**
   * 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(e) {
    this._globalExposure = e, this._dirty = !0;
  }
  /**
   * 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(e) {
    this._highlightsHue = e, this._dirty = !0;
  }
  /**
   * 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(e) {
    this._highlightsDensity = e, this._dirty = !0;
  }
  /**
   * 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(e) {
    this._highlightsSaturation = e, this._dirty = !0;
  }
  /**
   * 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(e) {
    this._highlightsExposure = e, this._dirty = !0;
  }
  /**
   * 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(e) {
    this._midtonesHue = e, this._dirty = !0;
  }
  /**
   * 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(e) {
    this._midtonesDensity = e, this._dirty = !0;
  }
  /**
   * 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(e) {
    this._midtonesSaturation = e, this._dirty = !0;
  }
  /**
   * 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(e) {
    this._midtonesExposure = e, this._dirty = !0;
  }
  /**
   * 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(e) {
    this._shadowsHue = e, this._dirty = !0;
  }
  /**
   * 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(e) {
    this._shadowsDensity = e, this._dirty = !0;
  }
  /**
   * 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(e) {
    this._shadowsSaturation = e, this._dirty = !0;
  }
  /**
   * 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(e) {
    this._shadowsExposure = e, this._dirty = !0;
  }
  /**
   * 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(e, t, i = "vCameraColorCurvePositive", s = "vCameraColorCurveNeutral", r = "vCameraColorCurveNegative") {
    e._dirty && (e._dirty = !1, e._getColorGradingDataToRef(e._globalHue, e._globalDensity, e._globalSaturation, e._globalExposure, e._globalCurve), e._getColorGradingDataToRef(e._highlightsHue, e._highlightsDensity, e._highlightsSaturation, e._highlightsExposure, e._tempColor), e._tempColor.multiplyToRef(e._globalCurve, e._highlightsCurve), e._getColorGradingDataToRef(e._midtonesHue, e._midtonesDensity, e._midtonesSaturation, e._midtonesExposure, e._tempColor), e._tempColor.multiplyToRef(e._globalCurve, e._midtonesCurve), e._getColorGradingDataToRef(e._shadowsHue, e._shadowsDensity, e._shadowsSaturation, e._shadowsExposure, e._tempColor), e._tempColor.multiplyToRef(e._globalCurve, e._shadowsCurve), e._highlightsCurve.subtractToRef(e._midtonesCurve, e._positiveCurve), e._midtonesCurve.subtractToRef(e._shadowsCurve, e._negativeCurve)), t && (t.setFloat4(i, e._positiveCurve.r, e._positiveCurve.g, e._positiveCurve.b, e._positiveCurve.a), t.setFloat4(s, e._midtonesCurve.r, e._midtonesCurve.g, e._midtonesCurve.b, e._midtonesCurve.a), t.setFloat4(r, e._negativeCurve.r, e._negativeCurve.g, e._negativeCurve.b, e._negativeCurve.a));
  }
  /**
   * Prepare the list of uniforms associated with the ColorCurves effects.
   * @param uniformsList The list of uniforms used in the effect
   */
  static PrepareUniforms(e) {
    e.push("vCameraColorCurveNeutral", "vCameraColorCurvePositive", "vCameraColorCurveNegative");
  }
  /**
   * 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(e, t, i, s, r) {
    e != null && (e = ue._Clamp(e, 0, 360), t = ue._Clamp(t, -100, 100), i = ue._Clamp(i, -100, 100), s = ue._Clamp(s, -100, 100), t = ue._ApplyColorGradingSliderNonlinear(t), t *= 0.5, s = ue._ApplyColorGradingSliderNonlinear(s), t < 0 && (t *= -1, e = (e + 180) % 360), ue._FromHSBToRef(e, t, 50 + 0.25 * s, r), r.scaleToRef(2, r), r.a = 1 + 0.01 * i);
  }
  /**
   * 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(e) {
    e /= 100;
    let t = Math.abs(e);
    return t = Math.pow(t, 2), e < 0 && (t *= -1), t *= 100, t;
  }
  /**
   * 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
   * @result An RGBA color represented as Vector4.
   */
  static _FromHSBToRef(e, t, i, s) {
    let r = ue._Clamp(e, 0, 360);
    const n = ue._Clamp(t / 100, 0, 1), a = ue._Clamp(i / 100, 0, 1);
    if (n === 0)
      s.r = a, s.g = a, s.b = a;
    else {
      r /= 60;
      const o = Math.floor(r), h = r - o, c = a * (1 - n), u = a * (1 - n * h), d = a * (1 - n * (1 - h));
      switch (o) {
        case 0:
          s.r = a, s.g = d, s.b = c;
          break;
        case 1:
          s.r = u, s.g = a, s.b = c;
          break;
        case 2:
          s.r = c, s.g = a, s.b = d;
          break;
        case 3:
          s.r = c, s.g = u, s.b = a;
          break;
        case 4:
          s.r = d, s.g = c, s.b = a;
          break;
        default:
          s.r = a, s.g = c, s.b = u;
          break;
      }
    }
    s.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(e, t, i) {
    return Math.min(Math.max(e, t), i);
  }
  /**
   * Clones the current color curve instance.
   * @returns The cloned curves
   */
  clone() {
    return he.Clone(() => new ue(), this);
  }
  /**
   * Serializes the current color curve instance to a json representation.
   * @returns a JSON representation
   */
  serialize() {
    return he.Serialize(this);
  }
  /**
   * Parses the color curve from a json representation.
   * @param source the JSON source to parse
   * @returns The parsed curves
   */
  static Parse(e) {
    return he.Parse(() => new ue(), e, null, null);
  }
}
F([
  B()
], ue.prototype, "_globalHue", void 0);
F([
  B()
], ue.prototype, "_globalDensity", void 0);
F([
  B()
], ue.prototype, "_globalSaturation", void 0);
F([
  B()
], ue.prototype, "_globalExposure", void 0);
F([
  B()
], ue.prototype, "_highlightsHue", void 0);
F([
  B()
], ue.prototype, "_highlightsDensity", void 0);
F([
  B()
], ue.prototype, "_highlightsSaturation", void 0);
F([
  B()
], ue.prototype, "_highlightsExposure", void 0);
F([
  B()
], ue.prototype, "_midtonesHue", void 0);
F([
  B()
], ue.prototype, "_midtonesDensity", void 0);
F([
  B()
], ue.prototype, "_midtonesSaturation", void 0);
F([
  B()
], ue.prototype, "_midtonesExposure", void 0);
he._ColorCurvesParser = ue.Parse;
class ae {
  constructor() {
    this.colorCurves = new ue(), this._colorCurvesEnabled = !1, this._colorGradingEnabled = !1, this._colorGradingWithGreenDepth = !0, this._colorGradingBGR = !0, this._exposure = 1, this._toneMappingEnabled = !1, this._toneMappingType = ae.TONEMAPPING_STANDARD, this._contrast = 1, this.vignetteStretch = 0, this.vignetteCenterX = 0, this.vignetteCenterY = 0, this.vignetteWeight = 1.5, this.vignetteColor = new Oe(0, 0, 0, 0), this.vignetteCameraFov = 0.5, this._vignetteBlendMode = ae.VIGNETTEMODE_MULTIPLY, this._vignetteEnabled = !1, this._ditheringEnabled = !1, this._ditheringIntensity = 1 / 255, this._skipFinalColorClamp = !1, this._applyByPostProcess = !1, this._isEnabled = !0, this.onUpdateParameters = new w();
  }
  /**
   * Gets whether the color curves effect is enabled.
   */
  get colorCurvesEnabled() {
    return this._colorCurvesEnabled;
  }
  /**
   * Sets whether the color curves effect is enabled.
   */
  set colorCurvesEnabled(e) {
    this._colorCurvesEnabled !== e && (this._colorCurvesEnabled = e, 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(e) {
    this._colorGradingTexture !== e && (this._colorGradingTexture = e, 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(e) {
    this._colorGradingEnabled !== e && (this._colorGradingEnabled = e, 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(e) {
    this._colorGradingWithGreenDepth !== e && (this._colorGradingWithGreenDepth = e, 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(e) {
    this._colorGradingBGR !== e && (this._colorGradingBGR = e, this._updateParameters());
  }
  /**
   * Gets the Exposure used in the effect.
   */
  get exposure() {
    return this._exposure;
  }
  /**
   * Sets the Exposure used in the effect.
   */
  set exposure(e) {
    this._exposure !== e && (this._exposure = e, 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(e) {
    this._toneMappingEnabled !== e && (this._toneMappingEnabled = e, 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(e) {
    this._toneMappingType !== e && (this._toneMappingType = e, this._updateParameters());
  }
  /**
   * Gets the contrast used in the effect.
   */
  get contrast() {
    return this._contrast;
  }
  /**
   * Sets the contrast used in the effect.
   */
  set contrast(e) {
    this._contrast !== e && (this._contrast = e, this._updateParameters());
  }
  /**
   * Back Compat: Vignette center Y Offset.
   * @deprecated use vignetteCenterY instead
   */
  get vignetteCentreY() {
    return this.vignetteCenterY;
  }
  set vignetteCentreY(e) {
    this.vignetteCenterY = e;
  }
  /**
   * Back Compat: Vignette center X Offset.
   * @deprecated use vignetteCenterX instead
   */
  get vignetteCentreX() {
    return this.vignetteCenterX;
  }
  set vignetteCentreX(e) {
    this.vignetteCenterX = e;
  }
  /**
   * 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(e) {
    this._vignetteBlendMode !== e && (this._vignetteBlendMode = e, this._updateParameters());
  }
  /**
   * Gets whether the vignette effect is enabled.
   */
  get vignetteEnabled() {
    return this._vignetteEnabled;
  }
  /**
   * Sets whether the vignette effect is enabled.
   */
  set vignetteEnabled(e) {
    this._vignetteEnabled !== e && (this._vignetteEnabled = e, 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(e) {
    this._ditheringEnabled !== e && (this._ditheringEnabled = e, 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(e) {
    this._ditheringIntensity !== e && (this._ditheringIntensity = e, this._updateParameters());
  }
  /**
   * If apply by post process is set to true, setting this to true will skip the 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 the final color clamp step in the fragment shader
   * Applies to PBR materials.
   */
  set skipFinalColorClamp(e) {
    this._skipFinalColorClamp !== e && (this._skipFinalColorClamp = e, 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(e) {
    this._applyByPostProcess !== e && (this._applyByPostProcess = e, 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(e) {
    this._isEnabled !== e && (this._isEnabled = e, 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 uniforms associated with the Image Processing effects.
   * @param uniforms The list of uniforms used in the effect
   * @param defines the list of defines currently in use
   */
  static PrepareUniforms(e, t) {
    t.EXPOSURE && e.push("exposureLinear"), t.CONTRAST && e.push("contrast"), t.COLORGRADING && e.push("colorTransformSettings"), (t.VIGNETTE || t.DITHER) && e.push("vInverseScreenSize"), t.VIGNETTE && (e.push("vignetteSettings1"), e.push("vignetteSettings2")), t.COLORCURVES && ue.PrepareUniforms(e), t.DITHER && e.push("ditherIntensity");
  }
  /**
   * Prepare the list of samplers associated with the Image Processing effects.
   * @param samplersList The list of uniforms used in the effect
   * @param defines the list of defines currently in use
   */
  static PrepareSamplers(e, t) {
    t.COLORGRADING && e.push("txColorTransform");
  }
  /**
   * 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(e, t = !1) {
    if (t !== this.applyByPostProcess || !this._isEnabled) {
      e.VIGNETTE = !1, e.TONEMAPPING = !1, e.TONEMAPPING_ACES = !1, e.CONTRAST = !1, e.EXPOSURE = !1, e.COLORCURVES = !1, e.COLORGRADING = !1, e.COLORGRADING3D = !1, e.DITHER = !1, e.IMAGEPROCESSING = !1, e.SKIPFINALCOLORCLAMP = this.skipFinalColorClamp, e.IMAGEPROCESSINGPOSTPROCESS = this.applyByPostProcess && this._isEnabled;
      return;
    }
    switch (e.VIGNETTE = this.vignetteEnabled, e.VIGNETTEBLENDMODEMULTIPLY = this.vignetteBlendMode === ae._VIGNETTEMODE_MULTIPLY, e.VIGNETTEBLENDMODEOPAQUE = !e.VIGNETTEBLENDMODEMULTIPLY, e.TONEMAPPING = this.toneMappingEnabled, this._toneMappingType) {
      case ae.TONEMAPPING_ACES:
        e.TONEMAPPING_ACES = !0;
        break;
      default:
        e.TONEMAPPING_ACES = !1;
        break;
    }
    e.CONTRAST = this.contrast !== 1, e.EXPOSURE = this.exposure !== 1, e.COLORCURVES = this.colorCurvesEnabled && !!this.colorCurves, e.COLORGRADING = this.colorGradingEnabled && !!this.colorGradingTexture, e.COLORGRADING ? e.COLORGRADING3D = this.colorGradingTexture.is3D : e.COLORGRADING3D = !1, e.SAMPLER3DGREENDEPTH = this.colorGradingWithGreenDepth, e.SAMPLER3DBGRMAP = this.colorGradingBGR, e.DITHER = this._ditheringEnabled, e.IMAGEPROCESSINGPOSTPROCESS = this.applyByPostProcess, e.SKIPFINALCOLORCLAMP = this.skipFinalColorClamp, e.IMAGEPROCESSING = e.VIGNETTE || e.TONEMAPPING || e.CONTRAST || e.EXPOSURE || e.COLORCURVES || e.COLORGRADING || e.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(e, t) {
    if (this._colorCurvesEnabled && this.colorCurves && ue.Bind(this.colorCurves, e), this._vignetteEnabled || this._ditheringEnabled) {
      const i = 1 / e.getEngine().getRenderWidth(), s = 1 / e.getEngine().getRenderHeight();
      if (e.setFloat2("vInverseScreenSize", i, s), this._ditheringEnabled && e.setFloat("ditherIntensity", 0.5 * this._ditheringIntensity), this._vignetteEnabled) {
        const r = t ?? s / i;
        let n = Math.tan(this.vignetteCameraFov * 0.5), a = n * r;
        const o = Math.sqrt(a * n);
        a = k.Mix(a, o, this.vignetteStretch), n = k.Mix(n, o, this.vignetteStretch), e.setFloat4("vignetteSettings1", a, n, -a * this.vignetteCenterX, -n * this.vignetteCenterY);
        const h = -2 * this.vignetteWeight;
        e.setFloat4("vignetteSettings2", this.vignetteColor.r, this.vignetteColor.g, this.vignetteColor.b, h);
      }
    }
    if (e.setFloat("exposureLinear", this.exposure), e.setFloat("contrast", this.contrast), this.colorGradingTexture) {
      e.setTexture("txColorTransform", this.colorGradingTexture);
      const i = this.colorGradingTexture.getSize().height;
      e.setFloat4(
        "colorTransformSettings",
        (i - 1) / i,
        // textureScale
        0.5 / i,
        // textureOffset
        i,
        // textureSize
        this.colorGradingTexture.level
        // weight
      );
    }
  }
  /**
   * Clones the current image processing instance.
   * @returns The cloned image processing
   */
  clone() {
    return he.Clone(() => new ae(), this);
  }
  /**
   * Serializes the current image processing instance to a json representation.
   * @returns a JSON representation
   */
  serialize() {
    return he.Serialize(this);
  }
  /**
   * Parses the image processing from a json representation.
   * @param source the JSON source to parse
   * @returns The parsed image processing
   */
  static Parse(e) {
    const t = he.Parse(() => new ae(), e, null, null);
    return e.vignetteCentreX !== void 0 && (t.vignetteCenterX = e.vignetteCentreX), e.vignetteCentreY !== void 0 && (t.vignetteCenterY = e.vignetteCentreY), t;
  }
  /**
   * 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;
  }
}
ae.TONEMAPPING_STANDARD = 0;
ae.TONEMAPPING_ACES = 1;
ae._VIGNETTEMODE_MULTIPLY = 0;
ae._VIGNETTEMODE_OPAQUE = 1;
F([
  ir()
], ae.prototype, "colorCurves", void 0);
F([
  B()
], ae.prototype, "_colorCurvesEnabled", void 0);
F([
  tr("colorGradingTexture")
], ae.prototype, "_colorGradingTexture", void 0);
F([
  B()
], ae.prototype, "_colorGradingEnabled", void 0);
F([
  B()
], ae.prototype, "_colorGradingWithGreenDepth", void 0);
F([
  B()
], ae.prototype, "_colorGradingBGR", void 0);
F([
  B()
], ae.prototype, "_exposure", void 0);
F([
  B()
], ae.prototype, "_toneMappingEnabled", void 0);
F([
  B()
], ae.prototype, "_toneMappingType", void 0);
F([
  B()
], ae.prototype, "_contrast", void 0);
F([
  B()
], ae.prototype, "vignetteStretch", void 0);
F([
  B()
], ae.prototype, "vignetteCenterX", void 0);
F([
  B()
], ae.prototype, "vignetteCenterY", void 0);
F([
  B()
], ae.prototype, "vignetteWeight", void 0);
F([
  sr()
], ae.prototype, "vignetteColor", void 0);
F([
  B()
], ae.prototype, "vignetteCameraFov", void 0);
F([
  B()
], ae.prototype, "_vignetteBlendMode", void 0);
F([
  B()
], ae.prototype, "_vignetteEnabled", void 0);
F([
  B()
], ae.prototype, "_ditheringEnabled", void 0);
F([
  B()
], ae.prototype, "_ditheringIntensity", void 0);
F([
  B()
], ae.prototype, "_skipFinalColorClamp", void 0);
F([
  B()
], ae.prototype, "_applyByPostProcess", void 0);
F([
  B()
], ae.prototype, "_isEnabled", void 0);
he._ImageProcessingConfigurationParser = ae.Parse;
se.prototype.createUniformBuffer = function(l) {
  const e = this._gl.createBuffer();
  if (!e)
    throw new Error("Unable to create uniform buffer");
  const t = new Gt(e);
  return this.bindUniformBuffer(t), l instanceof Float32Array ? this._gl.bufferData(this._gl.UNIFORM_BUFFER, l, this._gl.STATIC_DRAW) : this._gl.bufferData(this._gl.UNIFORM_BUFFER, new Float32Array(l), this._gl.STATIC_DRAW), this.bindUniformBuffer(null), t.references = 1, t;
};
se.prototype.createDynamicUniformBuffer = function(l) {
  const e = this._gl.createBuffer();
  if (!e)
    throw new Error("Unable to create dynamic uniform buffer");
  const t = new Gt(e);
  return this.bindUniformBuffer(t), l instanceof Float32Array ? this._gl.bufferData(this._gl.UNIFORM_BUFFER, l, this._gl.DYNAMIC_DRAW) : this._gl.bufferData(this._gl.UNIFORM_BUFFER, new Float32Array(l), this._gl.DYNAMIC_DRAW), this.bindUniformBuffer(null), t.references = 1, t;
};
se.prototype.updateUniformBuffer = function(l, e, t, i) {
  this.bindUniformBuffer(l), t === void 0 && (t = 0), i === void 0 ? e instanceof Float32Array ? this._gl.bufferSubData(this._gl.UNIFORM_BUFFER, t, e) : this._gl.bufferSubData(this._gl.UNIFORM_BUFFER, t, new Float32Array(e)) : e instanceof Float32Array ? this._gl.bufferSubData(this._gl.UNIFORM_BUFFER, 0, e.subarray(t, t + i)) : this._gl.bufferSubData(this._gl.UNIFORM_BUFFER, 0, new Float32Array(e).subarray(t, t + i)), this.bindUniformBuffer(null);
};
se.prototype.bindUniformBuffer = function(l) {
  this._gl.bindBuffer(this._gl.UNIFORM_BUFFER, l ? l.underlyingResource : null);
};
se.prototype.bindUniformBufferBase = function(l, e, t) {
  this._gl.bindBufferBase(this._gl.UNIFORM_BUFFER, e, l ? l.underlyingResource : null);
};
se.prototype.bindUniformBlock = function(l, e, t) {
  const i = l.program, s = this._gl.getUniformBlockIndex(i, e);
  s !== 4294967295 && this._gl.uniformBlockBinding(i, s, t);
};
class O {
  /**
   * 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
   */
  constructor(e, t, i, s, r = !1) {
    this._valueCache = {}, this._engine = e, this._noUBO = !e.supportsUniformBuffers || r, this._dynamic = i, this._name = s ?? "no-name", this._data = t || [], this._uniformLocations = {}, this._uniformSizes = {}, this._uniformArraySizes = {}, this._uniformLocationPointer = 0, this._needSync = !1, this._engine._features.trackUbosInFrame && (this._buffers = [], this._bufferIndex = -1, this._createBufferOnWrite = !1, this._currentFrameId = 0), 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) : (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 !== void 0;
  }
  /**
   * 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;
  }
  /**
   * 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(e) {
    let t;
    if (e <= 2 ? t = e : t = 4, this._uniformLocationPointer % t !== 0) {
      const i = this._uniformLocationPointer;
      this._uniformLocationPointer += t - this._uniformLocationPointer % t;
      const s = this._uniformLocationPointer - i;
      for (let r = 0; r < s; r++)
        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(e, t, i = 0) {
    if (this._noUBO || this._uniformLocations[e] !== void 0)
      return;
    let s;
    if (i > 0) {
      if (t instanceof Array)
        throw "addUniform should not be use with Array in UBO: " + e;
      if (this._fillAlignment(4), this._uniformArraySizes[e] = { strideSize: t, arraySize: i }, t == 16)
        t = t * i;
      else {
        const n = (4 - t) * i;
        t = t * i + n;
      }
      s = [];
      for (let r = 0; r < t; r++)
        s.push(0);
    } else {
      if (t instanceof Array)
        s = t, t = s.length;
      else {
        t = t, s = [];
        for (let r = 0; r < t; r++)
          s.push(0);
      }
      this._fillAlignment(t);
    }
    this._uniformSizes[e] = t, this._uniformLocations[e] = this._uniformLocationPointer, this._uniformLocationPointer += t;
    for (let r = 0; r < t; r++)
      this._data.push(s[r]);
    this._needSync = !0;
  }
  /**
   * 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(e, t) {
    this.addUniform(e, Array.prototype.slice.call(t.toArray()));
  }
  /**
   * 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(e, t, i) {
    const s = [t, i];
    this.addUniform(e, s);
  }
  /**
   * 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(e, t, i, s) {
    const r = [t, i, s];
    this.addUniform(e, r);
  }
  /**
   * 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(e, t) {
    const i = [t.r, t.g, t.b];
    this.addUniform(e, i);
  }
  /**
   * 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(e, t, i) {
    const s = [t.r, t.g, t.b, i];
    this.addUniform(e, s);
  }
  /**
   * 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(e, t) {
    const i = [t.x, t.y, t.z];
    this.addUniform(e, i);
  }
  /**
   * Adds a Matrix 3x3 to the uniform buffer.
   * @param name Name of the uniform, as used in the uniform block in the shader.
   */
  addMatrix3x3(e) {
    this.addUniform(e, 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(e) {
    this.addUniform(e, 8);
  }
  /**
   * Effectively creates the WebGL Uniform Buffer, once layout is completed with `addUniform`.
   */
  create() {
    this._noUBO || this._buffer || (this._fillAlignment(4), this._bufferData = new Float32Array(this._data), this._rebuild(), this._needSync = !0);
  }
  /** @internal */
  _rebuild() {
    this._noUBO || !this._bufferData || (this._dynamic ? this._buffer = this._engine.createDynamicUniformBuffer(this._bufferData) : this._buffer = this._engine.createUniformBuffer(this._bufferData), this._engine._features.trackUbosInFrame && (this._buffers.push([this._buffer, this._engine._features.checkUbosContentBeforeUpload ? this._bufferData.slice() : void 0]), this._bufferIndex = this._buffers.length - 1, this._createBufferOnWrite = !1));
  }
  /** @internal */
  get _numBuffers() {
    return this._buffers.length;
  }
  /** @internal */
  get _indexBuffer() {
    return this._bufferIndex;
  }
  /** Gets the name of this buffer */
  get name() {
    return this._name;
  }
  /** Gets the current effect */
  get currentEffect() {
    return this._currentEffect;
  }
  _buffersEqual(e, t) {
    for (let i = 0; i < e.length; ++i)
      if (e[i] !== t[i])
        return !1;
    return !0;
  }
  _copyBuffer(e, t) {
    for (let i = 0; i < e.length; ++i)
      t[i] = e[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) {
      if (this.bindUniformBuffer(), !this._buffer) {
        this.create();
        return;
      }
      if (!this._dynamic && !this._needSync) {
        this._createBufferOnWrite = this._engine._features.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 = !1, this._createBufferOnWrite = this._engine._features.trackUbosInFrame;
          return;
        } else
          this._copyBuffer(this._bufferData, this._buffers[this._bufferIndex][1]);
      this._engine.updateUniformBuffer(this._buffer, this._bufferData), this._engine._features._collectUbosUpdatedInFrame && (O._UpdatedUbosInFrame[this._name] || (O._UpdatedUbosInFrame[this._name] = 0), O._UpdatedUbosInFrame[this._name]++), this._needSync = !1, this._createBufferOnWrite = this._engine._features.trackUbosInFrame;
    }
  }
  _createNewBuffer() {
    this._bufferIndex + 1 < this._buffers.length ? (this._bufferIndex++, this._buffer = this._buffers[this._bufferIndex][0], this._createBufferOnWrite = !1, this._needSync = !0) : this._rebuild();
  }
  _checkNewFrame() {
    this._engine._features.trackUbosInFrame && this._currentFrameId !== this._engine.frameId && (this._currentFrameId = this._engine.frameId, this._createBufferOnWrite = !1, this._buffers && this._buffers.length > 0 ? (this._needSync = this._bufferIndex !== 0, this._bufferIndex = 0, this._buffer = this._buffers[this._bufferIndex][0]) : 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(e, t, i) {
    this._checkNewFrame();
    let s = this._uniformLocations[e];
    if (s === void 0) {
      if (this._buffer) {
        S.Error("Cannot add an uniform after UBO has been created.");
        return;
      }
      this.addUniform(e, i), s = this._uniformLocations[e];
    }
    if (this._buffer || this.create(), this._dynamic)
      for (let r = 0; r < i; r++)
        this._bufferData[s + r] = t[r];
    else {
      let r = !1;
      for (let n = 0; n < i; n++)
        (i === 16 && !this._engine._features.uniformBufferHardCheckMatrix || this._bufferData[s + n] !== k.FloatRound(t[n])) && (r = !0, this._createBufferOnWrite && this._createNewBuffer(), this._bufferData[s + n] = t[n]);
      this._needSync = this._needSync || r;
    }
  }
  /**
   * 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(e, t, i) {
    this._checkNewFrame();
    const s = this._uniformLocations[e];
    if (s === void 0) {
      S.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;
    }
    this._buffer || this.create();
    const r = this._uniformArraySizes[e];
    if (this._dynamic)
      for (let n = 0; n < i; n++)
        this._bufferData[s + n] = t[n];
    else {
      let n = !1, a = 0, o = 0;
      for (let h = 0; h < i; h++)
        if (this._bufferData[s + o * 4 + a] !== k.FloatRound(t[h]) && (n = !0, this._createBufferOnWrite && this._createNewBuffer(), this._bufferData[s + o * 4 + a] = t[h]), a++, a === r.strideSize) {
          for (; a < 4; a++)
            this._bufferData[s + o * 4 + a] = 0;
          a = 0, o++;
        }
      this._needSync = this._needSync || n;
    }
  }
  _cacheMatrix(e, t) {
    this._checkNewFrame();
    const i = this._valueCache[e], s = t.updateFlag;
    return i !== void 0 && i === s ? !1 : (this._valueCache[e] = s, !0);
  }
  // Update methods
  _updateMatrix3x3ForUniform(e, t) {
    for (let i = 0; i < 3; i++)
      O._TempBuffer[i * 4] = t[i * 3], O._TempBuffer[i * 4 + 1] = t[i * 3 + 1], O._TempBuffer[i * 4 + 2] = t[i * 3 + 2], O._TempBuffer[i * 4 + 3] = 0;
    this.updateUniform(e, O._TempBuffer, 12);
  }
  _updateMatrix3x3ForEffect(e, t) {
    this._currentEffect.setMatrix3x3(e, t);
  }
  _updateMatrix2x2ForEffect(e, t) {
    this._currentEffect.setMatrix2x2(e, t);
  }
  _updateMatrix2x2ForUniform(e, t) {
    for (let i = 0; i < 2; i++)
      O._TempBuffer[i * 4] = t[i * 2], O._TempBuffer[i * 4 + 1] = t[i * 2 + 1], O._TempBuffer[i * 4 + 2] = 0, O._TempBuffer[i * 4 + 3] = 0;
    this.updateUniform(e, O._TempBuffer, 8);
  }
  _updateFloatForEffect(e, t) {
    this._currentEffect.setFloat(e, t);
  }
  _updateFloatForUniform(e, t) {
    O._TempBuffer[0] = t, this.updateUniform(e, O._TempBuffer, 1);
  }
  _updateFloat2ForEffect(e, t, i, s = "") {
    this._currentEffect.setFloat2(e + s, t, i);
  }
  _updateFloat2ForUniform(e, t, i) {
    O._TempBuffer[0] = t, O._TempBuffer[1] = i, this.updateUniform(e, O._TempBuffer, 2);
  }
  _updateFloat3ForEffect(e, t, i, s, r = "") {
    this._currentEffect.setFloat3(e + r, t, i, s);
  }
  _updateFloat3ForUniform(e, t, i, s) {
    O._TempBuffer[0] = t, O._TempBuffer[1] = i, O._TempBuffer[2] = s, this.updateUniform(e, O._TempBuffer, 3);
  }
  _updateFloat4ForEffect(e, t, i, s, r, n = "") {
    this._currentEffect.setFloat4(e + n, t, i, s, r);
  }
  _updateFloat4ForUniform(e, t, i, s, r) {
    O._TempBuffer[0] = t, O._TempBuffer[1] = i, O._TempBuffer[2] = s, O._TempBuffer[3] = r, this.updateUniform(e, O._TempBuffer, 4);
  }
  _updateFloatArrayForEffect(e, t) {
    this._currentEffect.setFloatArray(e, t);
  }
  _updateFloatArrayForUniform(e, t) {
    this.updateUniformArray(e, t, t.length);
  }
  _updateArrayForEffect(e, t) {
    this._currentEffect.setArray(e, t);
  }
  _updateArrayForUniform(e, t) {
    this.updateUniformArray(e, t, t.length);
  }
  _updateIntArrayForEffect(e, t) {
    this._currentEffect.setIntArray(e, t);
  }
  _updateIntArrayForUniform(e, t) {
    O._TempBufferInt32View.set(t), this.updateUniformArray(e, O._TempBuffer, t.length);
  }
  _updateUIntArrayForEffect(e, t) {
    this._currentEffect.setUIntArray(e, t);
  }
  _updateUIntArrayForUniform(e, t) {
    O._TempBufferUInt32View.set(t), this.updateUniformArray(e, O._TempBuffer, t.length);
  }
  _updateMatrixForEffect(e, t) {
    this._currentEffect.setMatrix(e, t);
  }
  _updateMatrixForUniform(e, t) {
    this._cacheMatrix(e, t) && this.updateUniform(e, t.toArray(), 16);
  }
  _updateMatricesForEffect(e, t) {
    this._currentEffect.setMatrices(e, t);
  }
  _updateMatricesForUniform(e, t) {
    this.updateUniform(e, t, t.length);
  }
  _updateVector3ForEffect(e, t) {
    this._currentEffect.setVector3(e, t);
  }
  _updateVector3ForUniform(e, t) {
    O._TempBuffer[0] = t.x, O._TempBuffer[1] = t.y, O._TempBuffer[2] = t.z, this.updateUniform(e, O._TempBuffer, 3);
  }
  _updateVector4ForEffect(e, t) {
    this._currentEffect.setVector4(e, t);
  }
  _updateVector4ForUniform(e, t) {
    O._TempBuffer[0] = t.x, O._TempBuffer[1] = t.y, O._TempBuffer[2] = t.z, O._TempBuffer[3] = t.w, this.updateUniform(e, O._TempBuffer, 4);
  }
  _updateColor3ForEffect(e, t, i = "") {
    this._currentEffect.setColor3(e + i, t);
  }
  _updateColor3ForUniform(e, t) {
    O._TempBuffer[0] = t.r, O._TempBuffer[1] = t.g, O._TempBuffer[2] = t.b, this.updateUniform(e, O._TempBuffer, 3);
  }
  _updateColor4ForEffect(e, t, i, s = "") {
    this._currentEffect.setColor4(e + s, t, i);
  }
  _updateDirectColor4ForEffect(e, t, i = "") {
    this._currentEffect.setDirectColor4(e + i, t);
  }
  _updateColor4ForUniform(e, t, i) {
    O._TempBuffer[0] = t.r, O._TempBuffer[1] = t.g, O._TempBuffer[2] = t.b, O._TempBuffer[3] = i, this.updateUniform(e, O._TempBuffer, 4);
  }
  _updateDirectColor4ForUniform(e, t) {
    O._TempBuffer[0] = t.r, O._TempBuffer[1] = t.g, O._TempBuffer[2] = t.b, O._TempBuffer[3] = t.a, this.updateUniform(e, O._TempBuffer, 4);
  }
  _updateIntForEffect(e, t, i = "") {
    this._currentEffect.setInt(e + i, t);
  }
  _updateIntForUniform(e, t) {
    O._TempBufferInt32View[0] = t, this.updateUniform(e, O._TempBuffer, 1);
  }
  _updateInt2ForEffect(e, t, i, s = "") {
    this._currentEffect.setInt2(e + s, t, i);
  }
  _updateInt2ForUniform(e, t, i) {
    O._TempBufferInt32View[0] = t, O._TempBufferInt32View[1] = i, this.updateUniform(e, O._TempBuffer, 2);
  }
  _updateInt3ForEffect(e, t, i, s, r = "") {
    this._currentEffect.setInt3(e + r, t, i, s);
  }
  _updateInt3ForUniform(e, t, i, s) {
    O._TempBufferInt32View[0] = t, O._TempBufferInt32View[1] = i, O._TempBufferInt32View[2] = s, this.updateUniform(e, O._TempBuffer, 3);
  }
  _updateInt4ForEffect(e, t, i, s, r, n = "") {
    this._currentEffect.setInt4(e + n, t, i, s, r);
  }
  _updateInt4ForUniform(e, t, i, s, r) {
    O._TempBufferInt32View[0] = t, O._TempBufferInt32View[1] = i, O._TempBufferInt32View[2] = s, O._TempBufferInt32View[3] = r, this.updateUniform(e, O._TempBuffer, 4);
  }
  _updateUIntForEffect(e, t, i = "") {
    this._currentEffect.setUInt(e + i, t);
  }
  _updateUIntForUniform(e, t) {
    O._TempBufferUInt32View[0] = t, this.updateUniform(e, O._TempBuffer, 1);
  }
  _updateUInt2ForEffect(e, t, i, s = "") {
    this._currentEffect.setUInt2(e + s, t, i);
  }
  _updateUInt2ForUniform(e, t, i) {
    O._TempBufferUInt32View[0] = t, O._TempBufferUInt32View[1] = i, this.updateUniform(e, O._TempBuffer, 2);
  }
  _updateUInt3ForEffect(e, t, i, s, r = "") {
    this._currentEffect.setUInt3(e + r, t, i, s);
  }
  _updateUInt3ForUniform(e, t, i, s) {
    O._TempBufferUInt32View[0] = t, O._TempBufferUInt32View[1] = i, O._TempBufferUInt32View[2] = s, this.updateUniform(e, O._TempBuffer, 3);
  }
  _updateUInt4ForEffect(e, t, i, s, r, n = "") {
    this._currentEffect.setUInt4(e + n, t, i, s, r);
  }
  _updateUInt4ForUniform(e, t, i, s, r) {
    O._TempBufferUInt32View[0] = t, O._TempBufferUInt32View[1] = i, O._TempBufferUInt32View[2] = s, O._TempBufferUInt32View[3] = r, this.updateUniform(e, O._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(e, t) {
    this._currentEffect.setTexture(e, t);
  }
  /**
   * 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(e, t) {
    this.updateUniform(e, t, t.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(e, t) {
    this._currentEffect = e, this._currentEffectName = t;
  }
  /**
   * Binds the current (GPU) buffer to the effect
   */
  bindUniformBuffer() {
    !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(e) {
    if (!this._buffers)
      return this._buffer === e;
    for (let t = 0; t < this._buffers.length; ++t)
      if (this._buffers[t][0] === e)
        return this._bufferIndex = t, this._buffer = e, this._createBufferOnWrite = !1, this._currentEffect = void 0, !0;
    return !1;
  }
  /**
   * Disposes the uniform buffer.
   */
  dispose() {
    if (this._noUBO)
      return;
    const e = this._engine._uniformBuffers, t = e.indexOf(this);
    if (t !== -1 && (e[t] = e[e.length - 1], e.pop()), this._engine._features.trackUbosInFrame && this._buffers)
      for (let i = 0; i < this._buffers.length; ++i) {
        const s = this._buffers[i][0];
        this._engine._releaseBuffer(s);
      }
    else
      this._buffer && this._engine._releaseBuffer(this._buffer) && (this._buffer = null);
  }
}
O._UpdatedUbosInFrame = {};
O._MAX_UNIFORM_SIZE = 256;
O._TempBuffer = new Float32Array(O._MAX_UNIFORM_SIZE);
O._TempBufferInt32View = new Int32Array(O._TempBuffer.buffer);
O._TempBufferUInt32View = new Uint32Array(O._TempBuffer.buffer);
class ri {
  /**
   * 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)
   */
  constructor(e, t, i, s = 0, r = !1, n = !1, a = !1, o) {
    this._isAlreadyOwned = !1, e.getScene ? this._engine = e.getScene().getEngine() : this._engine = e, this._updatable = i, this._instanced = n, this._divisor = o || 1, t instanceof Kt ? (this._data = null, this._buffer = t) : (this._data = t, this._buffer = null), this.byteStride = a ? s : s * Float32Array.BYTES_PER_ELEMENT, r || 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(e, t, i, s, r, n = !1, a) {
    const o = n ? t : t * Float32Array.BYTES_PER_ELEMENT, h = s ? n ? s : s * Float32Array.BYTES_PER_ELEMENT : this.byteStride;
    return new _(this._engine, this, e, this._updatable, !0, h, r === void 0 ? this._instanced : r, o, i, void 0, void 0, !0, this._divisor || a);
  }
  // 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(e = null) {
    !e && this._buffer || (e = e || this._data, e && (this._buffer ? this._updatable && (this._engine.updateDynamicVertexBuffer(this._buffer, e), this._data = e) : this._updatable ? (this._buffer = this._engine.createDynamicVertexBuffer(e), this._data = e) : this._buffer = this._engine.createVertexBuffer(e)));
  }
  /** @internal */
  _rebuild() {
    this._buffer = null, this.create(this._data);
  }
  /**
   * Update current buffer data
   * @param data defines the data to store
   */
  update(e) {
    this.create(e);
  }
  /**
   * 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(e, t, i, s = !1) {
    this._buffer && this._updatable && (this._engine.updateDynamicVertexBuffer(this._buffer, e, s ? t : t * Float32Array.BYTES_PER_ELEMENT, i ? i * this.byteStride : void 0), t === 0 && i === void 0 ? this._data = e : this._data = null);
  }
  /** @internal */
  _increaseReferences() {
    if (this._buffer) {
      if (!this._isAlreadyOwned) {
        this._isAlreadyOwned = !0;
        return;
      }
      this._buffer.references++;
    }
  }
  /**
   * Release all resources
   */
  dispose() {
    this._buffer && this._engine._releaseBuffer(this._buffer) && (this._buffer = null, this._data = null);
  }
}
class _ {
  /**
   * Gets or sets the instance divisor when in instanced mode
   */
  get instanceDivisor() {
    return this._instanceDivisor;
  }
  set instanceDivisor(e) {
    const t = e != 0;
    this._instanceDivisor = e, t !== this._instanced && (this._instanced = t, this._computeHashCode());
  }
  /**
   * Constructor
   * @param engine the engine
   * @param data the data to use for this vertex buffer
   * @param kind the vertex buffer kind
   * @param updatable whether the data is updatable
   * @param postponeInternalCreation whether to postpone creating the internal WebGL buffer (optional)
   * @param stride the stride (optional)
   * @param instanced whether the buffer is instanced (optional)
   * @param offset the offset of the data (optional)
   * @param size the number of components (optional)
   * @param type the type of the component (optional)
   * @param normalized whether the data contains normalized data (optional)
   * @param useBytes set to true if stride and offset are in bytes (optional)
   * @param divisor defines the instance divisor to use (1 by default)
   * @param takeBufferOwnership defines if the buffer should be released when the vertex buffer is disposed
   */
  constructor(e, t, i, s, r, n, a, o, h, c, u = !1, d = !1, g = 1, f = !1) {
    if (t instanceof ri ? (this._buffer = t, this._ownsBuffer = f) : (this._buffer = new ri(e, t, s, n, r, a, d), this._ownsBuffer = !0), this.uniqueId = _._Counter++, this._kind = i, c == null) {
      const b = this.getData();
      this.type = _.FLOAT, b instanceof Int8Array ? this.type = _.BYTE : b instanceof Uint8Array ? this.type = _.UNSIGNED_BYTE : b instanceof Int16Array ? this.type = _.SHORT : b instanceof Uint16Array ? this.type = _.UNSIGNED_SHORT : b instanceof Int32Array ? this.type = _.INT : b instanceof Uint32Array && (this.type = _.UNSIGNED_INT);
    } else
      this.type = c;
    const m = _.GetTypeByteLength(this.type);
    d ? (this._size = h || (n ? n / m : _.DeduceStride(i)), this.byteStride = n || this._buffer.byteStride || this._size * m, this.byteOffset = o || 0) : (this._size = h || n || _.DeduceStride(i), this.byteStride = n ? n * m : this._buffer.byteStride || this._size * m, this.byteOffset = (o || 0) * m), this.normalized = u, this._instanced = a !== void 0 ? a : !1, this._instanceDivisor = a ? g : 0, 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 && 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 current buffer's data
   * @returns a DataArray or null
   */
  getData() {
    return this._buffer.getData();
  }
  /**
   * Gets current 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(e, t) {
    const i = this.getData();
    if (!i)
      return null;
    const s = this.getSize() * _.GetTypeByteLength(this.type), r = e * this.getSize();
    if (this.type !== _.FLOAT || this.byteStride !== s) {
      const n = new Float32Array(r);
      return this.forEach(r, (a, o) => n[o] = a), n;
    }
    if (!(i instanceof Array || i instanceof Float32Array) || this.byteOffset !== 0 || i.length !== r)
      if (i instanceof Array) {
        const n = this.byteOffset / 4;
        return i.slice(n, n + r);
      } else {
        if (i instanceof ArrayBuffer)
          return new Float32Array(i, this.byteOffset, r);
        {
          let n = i.byteOffset + this.byteOffset;
          if (t) {
            const o = new Float32Array(r), h = new Float32Array(i.buffer, n, r);
            return o.set(h), o;
          }
          const a = n % 4;
          return a && (n = Math.max(0, n - a)), new Float32Array(i.buffer, n, r);
        }
      }
    return t ? i.slice() : i;
  }
  /**
   * Gets underlying native buffer
   * @returns underlying native buffer
   */
  getBuffer() {
    return this._buffer.getBuffer();
  }
  /**
   * 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(e = !1) {
    return e ? 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(e) {
    this._buffer.create(e);
  }
  /**
   * 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(e) {
    this._buffer.update(e);
  }
  /**
   * 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(e, t, i = !1) {
    this._buffer.updateDirectly(e, t, void 0, i);
  }
  /**
   * Disposes the VertexBuffer and the underlying WebGLBuffer.
   */
  dispose() {
    this._ownsBuffer && this._buffer.dispose();
  }
  /**
   * 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(e, t) {
    _.ForEach(this._buffer.getData(), this.byteOffset, this.byteStride, this._size, this.type, e, this.normalized, t);
  }
  /**
   * Deduces the stride given a kind.
   * @param kind The kind string to deduce
   * @returns The deduced stride
   */
  static DeduceStride(e) {
    switch (e) {
      case _.UVKind:
      case _.UV2Kind:
      case _.UV3Kind:
      case _.UV4Kind:
      case _.UV5Kind:
      case _.UV6Kind:
        return 2;
      case _.NormalKind:
      case _.PositionKind:
        return 3;
      case _.ColorKind:
      case _.MatricesIndicesKind:
      case _.MatricesIndicesExtraKind:
      case _.MatricesWeightsKind:
      case _.MatricesWeightsExtraKind:
      case _.TangentKind:
        return 4;
      default:
        throw new Error("Invalid kind '" + e + "'");
    }
  }
  /**
   * Gets the byte length of the given type.
   * @param type the type
   * @returns the number of bytes
   */
  static GetTypeByteLength(e) {
    switch (e) {
      case _.BYTE:
      case _.UNSIGNED_BYTE:
        return 1;
      case _.SHORT:
      case _.UNSIGNED_SHORT:
        return 2;
      case _.INT:
      case _.UNSIGNED_INT:
      case _.FLOAT:
        return 4;
      default:
        throw new Error(`Invalid type '${e}'`);
    }
  }
  /**
   * 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
   */
  static ForEach(e, t, i, s, r, n, a, o) {
    if (e instanceof Array) {
      let h = t / 4;
      const c = i / 4;
      for (let u = 0; u < n; u += s) {
        for (let d = 0; d < s; d++)
          o(e[h + d], u + d);
        h += c;
      }
    } else {
      const h = e instanceof ArrayBuffer ? new DataView(e) : new DataView(e.buffer, e.byteOffset, e.byteLength), c = _.GetTypeByteLength(r);
      for (let u = 0; u < n; u += s) {
        let d = t;
        for (let g = 0; g < s; g++) {
          const f = _._GetFloatValue(h, r, d, a);
          o(f, u + g), d += c;
        }
        t += i;
      }
    }
  }
  static _GetFloatValue(e, t, i, s) {
    switch (t) {
      case _.BYTE: {
        let r = e.getInt8(i);
        return s && (r = Math.max(r / 127, -1)), r;
      }
      case _.UNSIGNED_BYTE: {
        let r = e.getUint8(i);
        return s && (r = r / 255), r;
      }
      case _.SHORT: {
        let r = e.getInt16(i, !0);
        return s && (r = Math.max(r / 32767, -1)), r;
      }
      case _.UNSIGNED_SHORT: {
        let r = e.getUint16(i, !0);
        return s && (r = r / 65535), r;
      }
      case _.INT:
        return e.getInt32(i, !0);
      case _.UNSIGNED_INT:
        return e.getUint32(i, !0);
      case _.FLOAT:
        return e.getFloat32(i, !0);
      default:
        throw new Error(`Invalid component type ${t}`);
    }
  }
}
_._Counter = 0;
_.BYTE = 5120;
_.UNSIGNED_BYTE = 5121;
_.SHORT = 5122;
_.UNSIGNED_SHORT = 5123;
_.INT = 5124;
_.UNSIGNED_INT = 5125;
_.FLOAT = 5126;
_.PositionKind = "position";
_.NormalKind = "normal";
_.TangentKind = "tangent";
_.UVKind = "uv";
_.UV2Kind = "uv2";
_.UV3Kind = "uv3";
_.UV4Kind = "uv4";
_.UV5Kind = "uv5";
_.UV6Kind = "uv6";
_.ColorKind = "color";
_.ColorInstanceKind = "instanceColor";
_.MatricesIndicesKind = "matricesIndices";
_.MatricesWeightsKind = "matricesWeights";
_.MatricesIndicesExtraKind = "matricesIndicesExtra";
_.MatricesWeightsExtraKind = "matricesWeightsExtra";
class ut {
  constructor() {
    this.hit = !1, 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(e = !1, t = !0) {
    if (!this.pickedMesh || t && !this.pickedMesh.isVerticesDataPresent(_.NormalKind))
      return null;
    const i = this.pickedMesh.getIndices();
    if (!i)
      return null;
    let s;
    if (t) {
      const n = this.pickedMesh.getVerticesData(_.NormalKind);
      let a = p.FromArray(n, i[this.faceId * 3] * 3), o = p.FromArray(n, i[this.faceId * 3 + 1] * 3), h = p.FromArray(n, i[this.faceId * 3 + 2] * 3);
      a = a.scale(this.bu), o = o.scale(this.bv), h = h.scale(1 - this.bu - this.bv), s = new p(a.x + o.x + h.x, a.y + o.y + h.y, a.z + o.z + h.z);
    } else {
      const n = this.pickedMesh.getVerticesData(_.PositionKind), a = p.FromArray(n, i[this.faceId * 3] * 3), o = p.FromArray(n, i[this.faceId * 3 + 1] * 3), h = p.FromArray(n, i[this.faceId * 3 + 2] * 3), c = a.subtract(o), u = h.subtract(o);
      s = p.Cross(c, u);
    }
    const r = (n, a) => {
      let o = n.getWorldMatrix();
      n.nonUniformScaling && (C.Matrix[0].copyFrom(o), o = C.Matrix[0], o.setTranslationFromFloats(0, 0, 0), o.invert(), o.transposeToRef(C.Matrix[1]), o = C.Matrix[1]), p.TransformNormalToRef(a, o, a);
    };
    if (e && r(this.pickedMesh, s), this.ray) {
      const n = C.Vector3[0].copyFrom(s);
      e || r(this.pickedMesh, n), p.Dot(n, this.ray.direction) > 0 && s.negateInPlace();
    }
    return s.normalize(), s;
  }
  /**
   * 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(e = _.UVKind) {
    if (!this.pickedMesh || !this.pickedMesh.isVerticesDataPresent(e))
      return null;
    const t = this.pickedMesh.getIndices();
    if (!t)
      return null;
    const i = this.pickedMesh.getVerticesData(e);
    if (!i)
      return null;
    let s = le.FromArray(i, t[this.faceId * 3] * 2), r = le.FromArray(i, t[this.faceId * 3 + 1] * 2), n = le.FromArray(i, t[this.faceId * 3 + 2] * 2);
    return s = s.scale(this.bu), r = r.scale(this.bv), n = n.scale(1 - this.bu - this.bv), new le(s.x + r.x + n.x, s.y + r.y + n.y);
  }
}
class Re {
  /**
   * 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(e, t, i, s, r, n) {
    this.source = e, this.pointerX = t, this.pointerY = i, this.meshUnderPointer = s, this.sourceEvent = r, this.additionalData = n;
  }
  /**
   * 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(e, t, i) {
    const s = e.getScene();
    return new Re(e, s.pointerX, s.pointerY, s.meshUnderPointer || e, t, i);
  }
  /**
   * 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(e, t, i, s) {
    return new Re(e, t.pointerX, t.pointerY, t.meshUnderPointer, i, s);
  }
  /**
   * 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(e, t) {
    return new Re(null, e.pointerX, e.pointerY, e.meshUnderPointer, t);
  }
  /**
   * 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(e, t, i, s) {
    return new Re(e, t.x, t.y, null, i, s);
  }
}
class Gi {
  /**
   * Creates a new instance PostProcess
   * @param scene The scene that the post process is associated with.
   */
  constructor(e) {
    this._vertexBuffers = {}, this._scene = e;
  }
  _prepareBuffers() {
    if (this._vertexBuffers[_.PositionKind])
      return;
    const e = [];
    e.push(1, 1), e.push(-1, 1), e.push(-1, -1), e.push(1, -1), this._vertexBuffers[_.PositionKind] = new _(this._scene.getEngine(), e, _.PositionKind, !1, !1, 2), this._buildIndexBuffer();
  }
  _buildIndexBuffer() {
    const e = [];
    e.push(0), e.push(1), e.push(2), e.push(0), e.push(2), e.push(3), this._indexBuffer = this._scene.getEngine().createIndexBuffer(e);
  }
  /**
   * Rebuilds the vertex buffers of the manager.
   * @internal
   */
  _rebuild() {
    const e = this._vertexBuffers[_.PositionKind];
    e && (e._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(e = null, t = null) {
    const i = this._scene.activeCamera;
    return !i || (t = t || i._postProcesses.filter((s) => s != null), !t || t.length === 0 || !this._scene.postProcessesEnabled) ? !1 : (t[0].activate(i, e, t != null), !0);
  }
  /**
   * 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
   */
  directRender(e, t = null, i = !1, s = 0, r = 0, n = !1) {
    var a;
    const o = this._scene.getEngine();
    for (let h = 0; h < e.length; h++) {
      h < e.length - 1 ? e[h + 1].activate(this._scene.activeCamera, t == null ? void 0 : t.texture) : (t ? o.bindFramebuffer(t, s, void 0, void 0, i, r) : n || o.restoreDefaultFramebuffer(), (a = o._debugInsertMarker) === null || a === void 0 || a.call(o, `post process ${e[h].name} output`));
      const c = e[h], u = c.apply();
      u && (c.onBeforeRenderObservable.notifyObservers(u), this._prepareBuffers(), o.bindBuffers(this._vertexBuffers, this._indexBuffer, u), o.drawElementsType(0, 0, 6), c.onAfterRenderObservable.notifyObservers(u));
    }
    o.setDepthBuffer(!0), o.setDepthWrite(!0);
  }
  /**
   * 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(e, t, i, s, r = !1) {
    var n;
    const a = this._scene.activeCamera;
    if (!a || (s = s || a._postProcesses.filter((h) => h != null), s.length === 0 || !this._scene.postProcessesEnabled))
      return;
    const o = this._scene.getEngine();
    for (let h = 0, c = s.length; h < c; h++) {
      const u = s[h];
      if (h < c - 1 ? u._outputTexture = s[h + 1].activate(a, t == null ? void 0 : t.texture) : (t ? (o.bindFramebuffer(t, i, void 0, void 0, r), u._outputTexture = t) : (o.restoreDefaultFramebuffer(), u._outputTexture = null), (n = o._debugInsertMarker) === null || n === void 0 || n.call(o, `post process ${s[h].name} output`)), e)
        break;
      const d = u.apply();
      d && (u.onBeforeRenderObservable.notifyObservers(d), this._prepareBuffers(), o.bindBuffers(this._vertexBuffers, this._indexBuffer, d), o.drawElementsType(0, 0, 6), u.onAfterRenderObservable.notifyObservers(d));
    }
    o.setDepthBuffer(!0), o.setDepthWrite(!0), o.setAlphaMode(0);
  }
  /**
   * Disposes of the post process manager.
   */
  dispose() {
    const e = this._vertexBuffers[_.PositionKind];
    e && (e.dispose(), this._vertexBuffers[_.PositionKind] = null), this._indexBuffer && (this._scene.getEngine()._releaseBuffer(this._indexBuffer), this._indexBuffer = null);
  }
}
class je {
  /**
   * Set the opaque sort comparison function.
   * If null the sub meshes will be render in the order they were created
   */
  set opaqueSortCompareFn(e) {
    e ? this._opaqueSortCompareFn = e : this._opaqueSortCompareFn = je.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(e) {
    e ? this._alphaTestSortCompareFn = e : this._alphaTestSortCompareFn = je.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(e) {
    e ? this._transparentSortCompareFn = e : this._transparentSortCompareFn = je.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(e, t, i = null, s = null, r = null) {
    this.index = e, this._opaqueSubMeshes = new We(256), this._transparentSubMeshes = new We(256), this._alphaTestSubMeshes = new We(256), this._depthOnlySubMeshes = new We(256), this._particleSystems = new We(256), this._spriteManagers = new We(256), this._empty = !0, this._edgesRenderers = new Tt(16), this._scene = t, this.opaqueSortCompareFn = i, this.alphaTestSortCompareFn = s, this.transparentSortCompareFn = r;
  }
  /**
   * 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
   * @returns true if rendered some submeshes.
   */
  render(e, t, i, s) {
    if (e) {
      e(this._opaqueSubMeshes, this._alphaTestSubMeshes, this._transparentSubMeshes, this._depthOnlySubMeshes);
      return;
    }
    const r = this._scene.getEngine();
    this._depthOnlySubMeshes.length !== 0 && (r.setColorWrite(!1), this._renderAlphaTest(this._depthOnlySubMeshes), r.setColorWrite(!0)), this._opaqueSubMeshes.length !== 0 && this._renderOpaque(this._opaqueSubMeshes), this._alphaTestSubMeshes.length !== 0 && this._renderAlphaTest(this._alphaTestSubMeshes);
    const n = r.getStencilBuffer();
    if (r.setStencilBuffer(!1), t && this._renderSprites(), i && this._renderParticles(s), this.onBeforeTransparentRendering && this.onBeforeTransparentRendering(), this._transparentSubMeshes.length !== 0 || this._scene.useOrderIndependentTransparency) {
      if (r.setStencilBuffer(n), this._scene.useOrderIndependentTransparency) {
        const a = this._scene.depthPeelingRenderer.render(this._transparentSubMeshes);
        a.length && this._renderTransparent(a);
      } else
        this._renderTransparent(this._transparentSubMeshes);
      r.setAlphaMode(0);
    }
    if (r.setStencilBuffer(!1), this._edgesRenderers.length) {
      for (let a = 0; a < this._edgesRenderers.length; a++)
        this._edgesRenderers.data[a].render();
      r.setAlphaMode(0);
    }
    r.setStencilBuffer(n);
  }
  /**
   * Renders the opaque submeshes in the order from the opaqueSortCompareFn.
   * @param subMeshes The submeshes to render
   */
  _renderOpaqueSorted(e) {
    return je._RenderSorted(e, this._opaqueSortCompareFn, this._scene.activeCamera, !1);
  }
  /**
   * Renders the opaque submeshes in the order from the alphatestSortCompareFn.
   * @param subMeshes The submeshes to render
   */
  _renderAlphaTestSorted(e) {
    return je._RenderSorted(e, this._alphaTestSortCompareFn, this._scene.activeCamera, !1);
  }
  /**
   * Renders the opaque submeshes in the order from the transparentSortCompareFn.
   * @param subMeshes The submeshes to render
   */
  _renderTransparentSorted(e) {
    return je._RenderSorted(e, this._transparentSortCompareFn, this._scene.activeCamera, !0);
  }
  /**
   * 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
   */
  static _RenderSorted(e, t, i, s) {
    let r = 0, n;
    const a = i ? i.globalPosition : je._ZeroVector;
    if (s)
      for (; r < e.length; r++)
        n = e.data[r], n._alphaIndex = n.getMesh().alphaIndex, n._distanceToCamera = p.Distance(n.getBoundingInfo().boundingSphere.centerWorld, a);
    const o = e.length === e.data.length ? e.data : e.data.slice(0, e.length);
    t && o.sort(t);
    const h = o[0].getMesh().getScene();
    for (r = 0; r < o.length; r++)
      if (n = o[r], !(h._activeMeshesFrozenButKeepClipping && !n.isInFrustum(h._frustumPlanes))) {
        if (s) {
          const c = n.getMaterial();
          if (c && c.needDepthPrePass) {
            const u = c.getScene().getEngine();
            u.setColorWrite(!1), u.setAlphaMode(0), n.render(!1), u.setColorWrite(!0);
          }
        }
        n.render(s);
      }
  }
  /**
   * 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(e, t) {
    return e._alphaIndex > t._alphaIndex ? 1 : e._alphaIndex < t._alphaIndex ? -1 : je.backToFrontSortCompare(e, t);
  }
  /**
   * 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(e, t) {
    return e._distanceToCamera < t._distanceToCamera ? 1 : e._distanceToCamera > t._distanceToCamera ? -1 : 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(e, t) {
    return e._distanceToCamera < t._distanceToCamera ? -1 : e._distanceToCamera > t._distanceToCamera ? 1 : 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(e, t) {
    const i = e.getMesh(), s = t.getMesh();
    return i.material && s.material ? i.material.uniqueId - s.material.uniqueId : i.uniqueId - s.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 = !0;
  }
  /**
   * 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(e, t, i) {
    t === void 0 && (t = e.getMesh()), i === void 0 && (i = e.getMaterial()), i != null && (i.needAlphaBlendingForMesh(t) ? this._transparentSubMeshes.push(e) : i.needAlphaTesting() ? (i.needDepthPrePass && this._depthOnlySubMeshes.push(e), this._alphaTestSubMeshes.push(e)) : (i.needDepthPrePass && this._depthOnlySubMeshes.push(e), this._opaqueSubMeshes.push(e)), t._renderingGroup = this, t._edgesRenderer && t._edgesRenderer.isEnabled && this._edgesRenderers.pushNoDuplicate(t._edgesRenderer), this._empty = !1);
  }
  dispatchSprites(e) {
    this._spriteManagers.push(e), this._empty = !1;
  }
  dispatchParticles(e) {
    this._particleSystems.push(e), this._empty = !1;
  }
  _renderParticles(e) {
    if (this._particleSystems.length === 0)
      return;
    const t = this._scene.activeCamera;
    this._scene.onBeforeParticlesRenderingObservable.notifyObservers(this._scene);
    for (let i = 0; i < this._particleSystems.length; i++) {
      const s = this._particleSystems.data[i];
      if ((t && t.layerMask & s.layerMask) === 0)
        continue;
      const r = s.emitter;
      (!r.position || !e || e.indexOf(r) !== -1) && this._scene._activeParticles.addCount(s.render(), !1);
    }
    this._scene.onAfterParticlesRenderingObservable.notifyObservers(this._scene);
  }
  _renderSprites() {
    if (!this._scene.spritesEnabled || this._spriteManagers.length === 0)
      return;
    const e = this._scene.activeCamera;
    this._scene.onBeforeSpritesRenderingObservable.notifyObservers(this._scene);
    for (let t = 0; t < this._spriteManagers.length; t++) {
      const i = this._spriteManagers.data[t];
      (e && e.layerMask & i.layerMask) !== 0 && i.render();
    }
    this._scene.onAfterSpritesRenderingObservable.notifyObservers(this._scene);
  }
}
je._ZeroVector = p.Zero();
class nr {
}
class Se {
  /**
   * 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(e) {
    if (e !== this._maintainStateBetweenFrames && (this._maintainStateBetweenFrames = e, !this._maintainStateBetweenFrames)) {
      for (const t of this._scene.meshes)
        if (t.subMeshes)
          for (const i of t.subMeshes)
            i._wasDispatched = !1;
      if (this._scene.spriteManagers)
        for (const t of this._scene.spriteManagers)
          t._wasDispatched = !1;
      for (const t of this._scene.particleSystems)
        t._wasDispatched = !1;
    }
  }
  /**
   * Instantiates a new rendering group for a particular scene
   * @param scene Defines the scene the groups belongs to
   */
  constructor(e) {
    this._useSceneAutoClearSetup = !1, this._renderingGroups = new Array(), this._autoClearDepthStencil = {}, this._customOpaqueSortCompareFn = {}, this._customAlphaTestSortCompareFn = {}, this._customTransparentSortCompareFn = {}, this._renderingGroupInfo = new nr(), this._maintainStateBetweenFrames = !1, this._scene = e;
    for (let t = Se.MIN_RENDERINGGROUPS; t < Se.MAX_RENDERINGGROUPS; t++)
      this._autoClearDepthStencil[t] = { autoClear: !0, depth: !0, stencil: !0 };
  }
  /**
   * Gets the rendering group with the specified id.
   */
  getRenderingGroup(e) {
    const t = e || 0;
    return this._prepareRenderingGroup(t), this._renderingGroups[t];
  }
  _clearDepthStencilBuffer(e = !0, t = !0) {
    this._depthStencilBufferAlreadyCleaned || (this._scene.getEngine().clear(null, !1, e, t), this._depthStencilBufferAlreadyCleaned = !0);
  }
  /**
   * Renders the entire managed groups. This is used by the scene or the different render targets.
   * @internal
   */
  render(e, t, i, s) {
    const r = this._renderingGroupInfo;
    if (r.scene = this._scene, r.camera = this._scene.activeCamera, this._scene.spriteManagers && s)
      for (let n = 0; n < this._scene.spriteManagers.length; n++) {
        const a = this._scene.spriteManagers[n];
        this.dispatchSprites(a);
      }
    for (let n = Se.MIN_RENDERINGGROUPS; n < Se.MAX_RENDERINGGROUPS; n++) {
      this._depthStencilBufferAlreadyCleaned = n === Se.MIN_RENDERINGGROUPS;
      const a = this._renderingGroups[n];
      if (!a || a._empty)
        continue;
      const o = Math.pow(2, n);
      if (r.renderingGroupId = n, this._scene.onBeforeRenderingGroupObservable.notifyObservers(r, o), Se.AUTOCLEAR) {
        const h = this._useSceneAutoClearSetup ? this._scene.getAutoClearDepthStencilSetup(n) : this._autoClearDepthStencil[n];
        h && h.autoClear && this._clearDepthStencilBuffer(h.depth, h.stencil);
      }
      for (const h of this._scene._beforeRenderingGroupDrawStage)
        h.action(n);
      a.render(e, s, i, t);
      for (const h of this._scene._afterRenderingGroupDrawStage)
        h.action(n);
      this._scene.onAfterRenderingGroupObservable.notifyObservers(r, o);
    }
  }
  /**
   * Resets the different information of the group to prepare a new frame
   * @internal
   */
  reset() {
    if (!this.maintainStateBetweenFrames)
      for (let e = Se.MIN_RENDERINGGROUPS; e < Se.MAX_RENDERINGGROUPS; e++) {
        const t = this._renderingGroups[e];
        t && t.prepare();
      }
  }
  /**
   * Resets the sprites information of the group to prepare a new frame
   * @internal
   */
  resetSprites() {
    if (!this.maintainStateBetweenFrames)
      for (let e = Se.MIN_RENDERINGGROUPS; e < Se.MAX_RENDERINGGROUPS; e++) {
        const t = this._renderingGroups[e];
        t && t.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 e = Se.MIN_RENDERINGGROUPS; e < Se.MAX_RENDERINGGROUPS; e++) {
      const t = this._renderingGroups[e];
      t && t.dispose();
    }
  }
  _prepareRenderingGroup(e) {
    this._renderingGroups[e] === void 0 && (this._renderingGroups[e] = new je(e, this._scene, this._customOpaqueSortCompareFn[e], this._customAlphaTestSortCompareFn[e], this._customTransparentSortCompareFn[e]));
  }
  /**
   * Add a sprite manager to the rendering manager in order to render it this frame.
   * @param spriteManager Define the sprite manager to render
   */
  dispatchSprites(e) {
    this.maintainStateBetweenFrames && e._wasDispatched || (e._wasDispatched = !0, this.getRenderingGroup(e.renderingGroupId).dispatchSprites(e));
  }
  /**
   * Add a particle system to the rendering manager in order to render it this frame.
   * @param particleSystem Define the particle system to render
   */
  dispatchParticles(e) {
    this.maintainStateBetweenFrames && e._wasDispatched || (e._wasDispatched = !0, this.getRenderingGroup(e.renderingGroupId).dispatchParticles(e));
  }
  /**
   * 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(e, t, i) {
    t === void 0 && (t = e.getMesh()), !(this.maintainStateBetweenFrames && e._wasDispatched) && (e._wasDispatched = !0, this.getRenderingGroup(t.renderingGroupId).dispatch(e, t, i));
  }
  /**
   * 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(e, t = null, i = null, s = null) {
    if (this._customOpaqueSortCompareFn[e] = t, this._customAlphaTestSortCompareFn[e] = i, this._customTransparentSortCompareFn[e] = s, this._renderingGroups[e]) {
      const r = this._renderingGroups[e];
      r.opaqueSortCompareFn = this._customOpaqueSortCompareFn[e], r.alphaTestSortCompareFn = this._customAlphaTestSortCompareFn[e], r.transparentSortCompareFn = this._customTransparentSortCompareFn[e];
    }
  }
  /**
   * 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(e, t, i = !0, s = !0) {
    this._autoClearDepthStencil[e] = {
      autoClear: t,
      depth: i,
      stencil: s
    };
  }
  /**
   * 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(e) {
    return this._autoClearDepthStencil[e];
  }
}
Se.MAX_RENDERINGGROUPS = 4;
Se.MIN_RENDERINGGROUPS = 0;
Se.AUTOCLEAR = !0;
class K {
}
K.NAME_EFFECTLAYER = "EffectLayer";
K.NAME_LAYER = "Layer";
K.NAME_LENSFLARESYSTEM = "LensFlareSystem";
K.NAME_BOUNDINGBOXRENDERER = "BoundingBoxRenderer";
K.NAME_PARTICLESYSTEM = "ParticleSystem";
K.NAME_GAMEPAD = "Gamepad";
K.NAME_SIMPLIFICATIONQUEUE = "SimplificationQueue";
K.NAME_GEOMETRYBUFFERRENDERER = "GeometryBufferRenderer";
K.NAME_PREPASSRENDERER = "PrePassRenderer";
K.NAME_DEPTHRENDERER = "DepthRenderer";
K.NAME_DEPTHPEELINGRENDERER = "DepthPeelingRenderer";
K.NAME_POSTPROCESSRENDERPIPELINEMANAGER = "PostProcessRenderPipelineManager";
K.NAME_SPRITE = "Sprite";
K.NAME_SUBSURFACE = "SubSurface";
K.NAME_OUTLINERENDERER = "Outline";
K.NAME_PROCEDURALTEXTURE = "ProceduralTexture";
K.NAME_SHADOWGENERATOR = "ShadowGenerator";
K.NAME_OCTREE = "Octree";
K.NAME_PHYSICSENGINE = "PhysicsEngine";
K.NAME_AUDIO = "Audio";
K.NAME_FLUIDRENDERER = "FluidRenderer";
K.STEP_ISREADYFORMESH_EFFECTLAYER = 0;
K.STEP_BEFOREEVALUATEACTIVEMESH_BOUNDINGBOXRENDERER = 0;
K.STEP_EVALUATESUBMESH_BOUNDINGBOXRENDERER = 0;
K.STEP_PREACTIVEMESH_BOUNDINGBOXRENDERER = 0;
K.STEP_CAMERADRAWRENDERTARGET_EFFECTLAYER = 1;
K.STEP_BEFORECAMERADRAW_PREPASS = 0;
K.STEP_BEFORECAMERADRAW_EFFECTLAYER = 1;
K.STEP_BEFORECAMERADRAW_LAYER = 2;
K.STEP_BEFORERENDERTARGETDRAW_PREPASS = 0;
K.STEP_BEFORERENDERTARGETDRAW_LAYER = 1;
K.STEP_BEFORERENDERINGMESH_PREPASS = 0;
K.STEP_BEFORERENDERINGMESH_OUTLINE = 1;
K.STEP_AFTERRENDERINGMESH_PREPASS = 0;
K.STEP_AFTERRENDERINGMESH_OUTLINE = 1;
K.STEP_AFTERRENDERINGGROUPDRAW_EFFECTLAYER_DRAW = 0;
K.STEP_AFTERRENDERINGGROUPDRAW_BOUNDINGBOXRENDERER = 1;
K.STEP_BEFORECAMERAUPDATE_SIMPLIFICATIONQUEUE = 0;
K.STEP_BEFORECAMERAUPDATE_GAMEPAD = 1;
K.STEP_BEFORECLEAR_PROCEDURALTEXTURE = 0;
K.STEP_BEFORECLEAR_PREPASS = 1;
K.STEP_BEFORERENDERTARGETCLEAR_PREPASS = 0;
K.STEP_AFTERRENDERTARGETDRAW_PREPASS = 0;
K.STEP_AFTERRENDERTARGETDRAW_LAYER = 1;
K.STEP_AFTERCAMERADRAW_PREPASS = 0;
K.STEP_AFTERCAMERADRAW_EFFECTLAYER = 1;
K.STEP_AFTERCAMERADRAW_LENSFLARESYSTEM = 2;
K.STEP_AFTERCAMERADRAW_EFFECTLAYER_DRAW = 3;
K.STEP_AFTERCAMERADRAW_LAYER = 4;
K.STEP_AFTERCAMERADRAW_FLUIDRENDERER = 5;
K.STEP_AFTERCAMERAPOSTPROCESS_LAYER = 0;
K.STEP_AFTERRENDERTARGETPOSTPROCESS_LAYER = 0;
K.STEP_AFTERRENDER_AUDIO = 0;
K.STEP_GATHERRENDERTARGETS_DEPTHRENDERER = 0;
K.STEP_GATHERRENDERTARGETS_GEOMETRYBUFFERRENDERER = 1;
K.STEP_GATHERRENDERTARGETS_SHADOWGENERATOR = 2;
K.STEP_GATHERRENDERTARGETS_POSTPROCESSRENDERPIPELINEMANAGER = 3;
K.STEP_GATHERACTIVECAMERARENDERTARGETS_DEPTHRENDERER = 0;
K.STEP_GATHERACTIVECAMERARENDERTARGETS_FLUIDRENDERER = 1;
K.STEP_POINTERMOVE_SPRITE = 0;
K.STEP_POINTERDOWN_SPRITE = 0;
K.STEP_POINTERUP_SPRITE = 0;
class fe extends Array {
  /**
   * Hide ctor from the rest of the world.
   * @param items The items to add.
   */
  constructor(e) {
    super(...e);
  }
  /**
   * Creates a new Stage.
   * @returns A new instance of a Stage
   */
  static Create() {
    return Object.create(fe.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(e, t, i) {
    let s = 0, r = Number.MAX_VALUE;
    for (; s < this.length && (r = this[s].index, !(e < r)); s++)
      ;
    this.splice(s, 0, { index: e, component: t, action: i.bind(t) });
  }
  /**
   * Clears all the steps from the stage.
   */
  clear() {
    this.length = 0;
  }
}
class ne {
}
ne.POINTERDOWN = 1;
ne.POINTERUP = 2;
ne.POINTERMOVE = 4;
ne.POINTERWHEEL = 8;
ne.POINTERPICK = 16;
ne.POINTERTAP = 32;
ne.POINTERDOUBLETAP = 64;
class ds {
  /**
   * Instantiates the base class of pointers info.
   * @param type Defines the type of event (PointerEventTypes)
   * @param event Defines the related dom event
   */
  constructor(e, t) {
    this.type = e, this.event = t;
  }
}
class ar extends ds {
  /**
   * 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(e, t, i, s) {
    super(e, t), this.ray = null, this.originalPickingInfo = null, this.skipOnPointerObservable = !1, this.localPosition = new le(i, s);
  }
}
class at extends ds {
  /**
   * Defines the picking info associated with this PointerInfo object (if applicable)
   */
  get pickInfo() {
    return this._pickInfo || this._generatePickInfo(), 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(e, t, i, s = null) {
    super(e, t), this._pickInfo = i, this._inputManager = s;
  }
  /**
   * Generates the picking info if needed
   */
  /** @internal */
  _generatePickInfo() {
    this._inputManager && (this._pickInfo = this._inputManager._pickMove(this.event), this._inputManager._setRayOnPointerInfo(this._pickInfo, this.event), this._inputManager = null);
  }
}
class Ke {
  constructor() {
    this.hoverCursor = "", this.actions = new Array(), this.isRecursive = !1;
  }
  /**
   * Does exist one action manager with at least one trigger
   **/
  static get HasTriggers() {
    for (const e in Ke.Triggers)
      if (Object.prototype.hasOwnProperty.call(Ke.Triggers, e))
        return !0;
    return !1;
  }
  /**
   * Does exist one action manager with at least one pick trigger
   **/
  static get HasPickTriggers() {
    for (const e in Ke.Triggers)
      if (Object.prototype.hasOwnProperty.call(Ke.Triggers, e)) {
        const t = parseInt(e);
        if (t >= 1 && t <= 7)
          return !0;
      }
    return !1;
  }
  /**
   * 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(e) {
    for (const t in Ke.Triggers)
      if (Object.prototype.hasOwnProperty.call(Ke.Triggers, t) && parseInt(t) === e)
        return !0;
    return !1;
  }
}
Ke.Triggers = {};
class ni {
}
ni.KEYDOWN = 1;
ni.KEYUP = 2;
class Ai {
  /**
   * 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(e, t) {
    this.type = e, this.event = t;
  }
}
class zi extends Ai {
  /**
   * 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(e) {
    this.skipOnKeyboardObservable = e;
  }
  /**
   * 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(e, t) {
    super(e, t), this.type = e, this.event = t, this.skipOnKeyboardObservable = !1;
  }
}
var L;
(function(l) {
  l[l.Generic = 0] = "Generic", l[l.Keyboard = 1] = "Keyboard", l[l.Mouse = 2] = "Mouse", l[l.Touch = 3] = "Touch", l[l.DualShock = 4] = "DualShock", l[l.Xbox = 5] = "Xbox", l[l.Switch = 6] = "Switch", l[l.DualSense = 7] = "DualSense";
})(L || (L = {}));
var G;
(function(l) {
  l[l.Horizontal = 0] = "Horizontal", l[l.Vertical = 1] = "Vertical", l[l.LeftClick = 2] = "LeftClick", l[l.MiddleClick = 3] = "MiddleClick", l[l.RightClick = 4] = "RightClick", l[l.BrowserBack = 5] = "BrowserBack", l[l.BrowserForward = 6] = "BrowserForward", l[l.MouseWheelX = 7] = "MouseWheelX", l[l.MouseWheelY = 8] = "MouseWheelY", l[l.MouseWheelZ = 9] = "MouseWheelZ", l[l.Move = 12] = "Move";
})(G || (G = {}));
var ai;
(function(l) {
  l[l.Horizontal = 0] = "Horizontal", l[l.Vertical = 1] = "Vertical", l[l.LeftClick = 2] = "LeftClick", l[l.MiddleClick = 3] = "MiddleClick", l[l.RightClick = 4] = "RightClick", l[l.BrowserBack = 5] = "BrowserBack", l[l.BrowserForward = 6] = "BrowserForward", l[l.MouseWheelX = 7] = "MouseWheelX", l[l.MouseWheelY = 8] = "MouseWheelY", l[l.MouseWheelZ = 9] = "MouseWheelZ", l[l.DeltaHorizontal = 10] = "DeltaHorizontal", l[l.DeltaVertical = 11] = "DeltaVertical";
})(ai || (ai = {}));
var Ki;
(function(l) {
  l[l.Cross = 0] = "Cross", l[l.Circle = 1] = "Circle", l[l.Square = 2] = "Square", l[l.Triangle = 3] = "Triangle", l[l.L1 = 4] = "L1", l[l.R1 = 5] = "R1", l[l.L2 = 6] = "L2", l[l.R2 = 7] = "R2", l[l.Share = 8] = "Share", l[l.Options = 9] = "Options", l[l.L3 = 10] = "L3", l[l.R3 = 11] = "R3", l[l.DPadUp = 12] = "DPadUp", l[l.DPadDown = 13] = "DPadDown", l[l.DPadLeft = 14] = "DPadLeft", l[l.DPadRight = 15] = "DPadRight", l[l.Home = 16] = "Home", l[l.TouchPad = 17] = "TouchPad", l[l.LStickXAxis = 18] = "LStickXAxis", l[l.LStickYAxis = 19] = "LStickYAxis", l[l.RStickXAxis = 20] = "RStickXAxis", l[l.RStickYAxis = 21] = "RStickYAxis";
})(Ki || (Ki = {}));
var Hi;
(function(l) {
  l[l.Cross = 0] = "Cross", l[l.Circle = 1] = "Circle", l[l.Square = 2] = "Square", l[l.Triangle = 3] = "Triangle", l[l.L1 = 4] = "L1", l[l.R1 = 5] = "R1", l[l.L2 = 6] = "L2", l[l.R2 = 7] = "R2", l[l.Create = 8] = "Create", l[l.Options = 9] = "Options", l[l.L3 = 10] = "L3", l[l.R3 = 11] = "R3", l[l.DPadUp = 12] = "DPadUp", l[l.DPadDown = 13] = "DPadDown", l[l.DPadLeft = 14] = "DPadLeft", l[l.DPadRight = 15] = "DPadRight", l[l.Home = 16] = "Home", l[l.TouchPad = 17] = "TouchPad", l[l.LStickXAxis = 18] = "LStickXAxis", l[l.LStickYAxis = 19] = "LStickYAxis", l[l.RStickXAxis = 20] = "RStickXAxis", l[l.RStickYAxis = 21] = "RStickYAxis";
})(Hi || (Hi = {}));
var Xi;
(function(l) {
  l[l.A = 0] = "A", l[l.B = 1] = "B", l[l.X = 2] = "X", l[l.Y = 3] = "Y", l[l.LB = 4] = "LB", l[l.RB = 5] = "RB", l[l.LT = 6] = "LT", l[l.RT = 7] = "RT", l[l.Back = 8] = "Back", l[l.Start = 9] = "Start", l[l.LS = 10] = "LS", l[l.RS = 11] = "RS", l[l.DPadUp = 12] = "DPadUp", l[l.DPadDown = 13] = "DPadDown", l[l.DPadLeft = 14] = "DPadLeft", l[l.DPadRight = 15] = "DPadRight", l[l.Home = 16] = "Home", l[l.LStickXAxis = 17] = "LStickXAxis", l[l.LStickYAxis = 18] = "LStickYAxis", l[l.RStickXAxis = 19] = "RStickXAxis", l[l.RStickYAxis = 20] = "RStickYAxis";
})(Xi || (Xi = {}));
var Yi;
(function(l) {
  l[l.B = 0] = "B", l[l.A = 1] = "A", l[l.Y = 2] = "Y", l[l.X = 3] = "X", l[l.L = 4] = "L", l[l.R = 5] = "R", l[l.ZL = 6] = "ZL", l[l.ZR = 7] = "ZR", l[l.Minus = 8] = "Minus", l[l.Plus = 9] = "Plus", l[l.LS = 10] = "LS", l[l.RS = 11] = "RS", l[l.DPadUp = 12] = "DPadUp", l[l.DPadDown = 13] = "DPadDown", l[l.DPadLeft = 14] = "DPadLeft", l[l.DPadRight = 15] = "DPadRight", l[l.Home = 16] = "Home", l[l.Capture = 17] = "Capture", l[l.LStickXAxis = 18] = "LStickXAxis", l[l.LStickYAxis = 19] = "LStickYAxis", l[l.RStickXAxis = 20] = "RStickXAxis", l[l.RStickYAxis = 21] = "RStickYAxis";
})(Yi || (Yi = {}));
var qi;
(function(l) {
  l[l.PointerMove = 0] = "PointerMove", l[l.PointerDown = 1] = "PointerDown", l[l.PointerUp = 2] = "PointerUp";
})(qi || (qi = {}));
class hi {
}
hi.DOM_DELTA_PIXEL = 0;
hi.DOM_DELTA_LINE = 1;
hi.DOM_DELTA_PAGE = 2;
class Mt {
  /**
   * 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
   * @returns IUIEvent object
   */
  static CreateDeviceEvent(e, t, i, s, r, n, a) {
    switch (e) {
      case L.Keyboard:
        return this._CreateKeyboardEvent(i, s, r, n);
      case L.Mouse:
        if (i === G.MouseWheelX || i === G.MouseWheelY || i === G.MouseWheelZ)
          return this._CreateWheelEvent(e, t, i, s, r, n);
      case L.Touch:
        return this._CreatePointerEvent(e, t, i, s, r, n, a);
      default:
        throw `Unable to generate event for device ${L[e]}`;
    }
  }
  /**
   * 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
   * @returns IUIEvent object (Pointer)
   */
  static _CreatePointerEvent(e, t, i, s, r, n, a) {
    const o = this._CreateMouseEvent(e, t, i, s, r, n);
    return e === L.Mouse ? (o.deviceType = L.Mouse, o.pointerId = 1, o.pointerType = "mouse") : (o.deviceType = L.Touch, o.pointerId = a ?? t, o.pointerType = "touch"), i === G.Move ? o.type = "pointermove" : i >= G.LeftClick && i <= G.RightClick && (o.type = s === 1 ? "pointerdown" : "pointerup", o.button = i - 2), o;
  }
  /**
   * 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(e, t, i, s, r, n) {
    const a = this._CreateMouseEvent(e, t, i, s, r, n);
    switch (a.pointerId = 1, a.type = "wheel", a.deltaMode = hi.DOM_DELTA_PIXEL, a.deltaX = 0, a.deltaY = 0, a.deltaZ = 0, i) {
      case G.MouseWheelX:
        a.deltaX = s;
        break;
      case G.MouseWheelY:
        a.deltaY = s;
        break;
      case G.MouseWheelZ:
        a.deltaZ = s;
        break;
    }
    return a;
  }
  /**
   * 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(e, t, i, s, r, n) {
    const a = this._CreateEvent(n), o = r.pollInput(e, t, G.Horizontal), h = r.pollInput(e, t, G.Vertical);
    return n ? (a.movementX = 0, a.movementY = 0, a.offsetX = a.movementX - n.getBoundingClientRect().x, a.offsetY = a.movementY - n.getBoundingClientRect().y) : (a.movementX = r.pollInput(e, t, ai.DeltaHorizontal), a.movementY = r.pollInput(e, t, ai.DeltaVertical), a.offsetX = 0, a.offsetY = 0), this._CheckNonCharacterKeys(a, r), a.clientX = o, a.clientY = h, a.x = o, a.y = h, a.deviceType = e, a.deviceSlot = t, a.inputIndex = i, a;
  }
  /**
   * 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(e, t, i, s) {
    const r = this._CreateEvent(s);
    return this._CheckNonCharacterKeys(r, i), r.deviceType = L.Keyboard, r.deviceSlot = 0, r.inputIndex = e, r.type = t === 1 ? "keydown" : "keyup", r.key = String.fromCharCode(e), r.keyCode = e, r;
  }
  /**
   * 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(e, t) {
    const i = t.isDeviceAvailable(L.Keyboard), s = i && t.pollInput(L.Keyboard, 0, 18) === 1, r = i && t.pollInput(L.Keyboard, 0, 17) === 1, n = i && (t.pollInput(L.Keyboard, 0, 91) === 1 || t.pollInput(L.Keyboard, 0, 92) === 1 || t.pollInput(L.Keyboard, 0, 93) === 1), a = i && t.pollInput(L.Keyboard, 0, 16) === 1;
    e.altKey = s, e.ctrlKey = r, e.metaKey = n, e.shiftKey = a;
  }
  /**
   * Create base event object
   * @param elementToAttachTo Value to use as event target
   * @returns
   */
  static _CreateEvent(e) {
    const t = {};
    return t.preventDefault = () => {
    }, t.target = e, t;
  }
}
class or {
  constructor(e, t, i) {
    this._nativeInput = _native.DeviceInputSystem ? new _native.DeviceInputSystem(e, t, (s, r, n, a) => {
      const o = Mt.CreateDeviceEvent(s, r, n, a, this);
      i(s, r, o);
    }) : 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(e, t, i) {
    return this._nativeInput.pollInput(e, t, i);
  }
  /**
   * 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(e) {
    return e === L.Mouse || e === L.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() {
    return {
      pollInput: () => 0,
      isDeviceAvailable: () => !1,
      dispose: () => {
      }
    };
  }
}
const Zi = 255, ji = Object.keys(G).length / 2;
class hr {
  constructor(e, t, i, s) {
    this._inputs = [], this._keyboardActive = !1, this._pointerActive = !1, this._usingSafari = k.IsSafari(), this._usingMacOS = vi() && /(Mac|iPhone|iPod|iPad)/i.test(navigator.platform), this._keyboardDownEvent = (r) => {
    }, this._keyboardUpEvent = (r) => {
    }, this._keyboardBlurEvent = (r) => {
    }, this._pointerMoveEvent = (r) => {
    }, this._pointerDownEvent = (r) => {
    }, this._pointerUpEvent = (r) => {
    }, this._pointerCancelEvent = (r) => {
    }, this._pointerWheelEvent = (r) => {
    }, this._pointerBlurEvent = (r) => {
    }, this._eventsAttached = !1, this._mouseId = -1, this._isUsingFirefox = Mi.IsNavigatorAvailable() && navigator.userAgent && navigator.userAgent.indexOf("Firefox") !== -1, this._maxTouchPoints = 0, this._pointerInputClearObserver = null, this._gamepadConnectedEvent = (r) => {
    }, this._gamepadDisconnectedEvent = (r) => {
    }, this._eventPrefix = k.GetPointerPrefix(e), this._engine = e, this._onDeviceConnected = t, this._onDeviceDisconnected = i, this._onInputChanged = s, this._mouseId = this._isUsingFirefox ? 0 : 1, this._enableEvents(), this._usingMacOS && (this._metaKeys = []), 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(e, t, i) {
    const s = this._inputs[e][t];
    if (!s)
      throw `Unable to find device ${L[e]}`;
    e >= L.DualShock && e <= L.DualSense && this._updateDevice(e, t, i);
    const r = s[i];
    if (r === void 0)
      throw `Unable to find input ${i} for device ${L[e]} in slot ${t}`;
    return i === G.Move && k.Warn("Unable to provide information for PointerInput.Move.  Try using PointerInput.Horizontal or PointerInput.Vertical for move data."), r;
  }
  /**
   * 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(e) {
    return this._inputs[e] !== void 0;
  }
  /**
   * Dispose of all the eventlisteners
   */
  dispose() {
    this._onDeviceConnected = () => {
    }, this._onDeviceDisconnected = () => {
    }, this._onInputChanged = () => {
    }, delete this._engine._onEngineViewChanged, this._elementToAttachTo && this._disableEvents();
  }
  /**
   * Enable listening for user input events
   */
  _enableEvents() {
    const e = this === null || this === void 0 ? void 0 : this._engine.getInputElement();
    if (e && (!this._eventsAttached || this._elementToAttachTo !== e)) {
      if (this._disableEvents(), this._inputs) {
        for (const t of this._inputs)
          if (t)
            for (const i in t) {
              const s = +i, r = t[s];
              if (r)
                for (let n = 0; n < r.length; n++)
                  r[n] = 0;
            }
      }
      this._elementToAttachTo = e, this._elementToAttachTo.tabIndex = this._elementToAttachTo.tabIndex !== -1 ? this._elementToAttachTo.tabIndex : this._engine.canvasTabIndex, this._handleKeyActions(), this._handlePointerActions(), this._handleGamepadActions(), this._eventsAttached = !0, this._checkForConnectedDevices();
    }
  }
  /**
   * Disable listening for user input events
   */
  _disableEvents() {
    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._wheelEventName, this._pointerWheelEvent), window.removeEventListener("gamepadconnected", this._gamepadConnectedEvent), window.removeEventListener("gamepaddisconnected", this._gamepadDisconnectedEvent)), this._pointerInputClearObserver && this._engine.onEndFrameObservable.remove(this._pointerInputClearObserver), this._eventsAttached = !1;
  }
  /**
   * Checks for existing connections to devices and register them, if necessary
   * Currently handles gamepads and mouse
   */
  _checkForConnectedDevices() {
    if (navigator.getGamepads) {
      const e = navigator.getGamepads();
      for (const t of e)
        t && this._addGamePad(t);
    }
    typeof matchMedia == "function" && matchMedia("(pointer:fine)").matches && this._addPointerDevice(L.Mouse, 0, 0, 0);
  }
  // Private functions
  /**
   * Add a gamepad to the DeviceInputSystem
   * @param gamepad A single DOM Gamepad object
   */
  _addGamePad(e) {
    const t = this._getGamepadDeviceType(e.id), i = e.index;
    this._gamepads = this._gamepads || new Array(e.index + 1), this._registerDevice(t, i, e.buttons.length + e.axes.length), this._gamepads[i] = t;
  }
  /**
   * 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(e, t, i, s) {
    this._pointerActive || (this._pointerActive = !0), this._registerDevice(e, t, ji);
    const r = this._inputs[e][t];
    r[0] = i, r[1] = s;
  }
  /**
   * 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(e, t, i) {
    if (t === void 0)
      throw `Unable to register device ${L[e]} to undefined slot.`;
    if (this._inputs[e] || (this._inputs[e] = {}), !this._inputs[e][t]) {
      const s = new Array(i);
      s.fill(0), this._inputs[e][t] = s, this._onDeviceConnected(e, t);
    }
  }
  /**
   * 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(e, t) {
    this._inputs[e][t] && (delete this._inputs[e][t], this._onDeviceDisconnected(e, t));
  }
  /**
   * Handle all actions that come from keyboard interaction
   */
  _handleKeyActions() {
    this._keyboardDownEvent = (e) => {
      this._keyboardActive || (this._keyboardActive = !0, this._registerDevice(L.Keyboard, 0, Zi));
      const t = this._inputs[L.Keyboard][0];
      if (t) {
        t[e.keyCode] = 1;
        const i = e;
        i.inputIndex = e.keyCode, this._usingMacOS && e.metaKey && e.key !== "Meta" && (this._metaKeys.includes(e.keyCode) || this._metaKeys.push(e.keyCode)), this._onInputChanged(L.Keyboard, 0, i);
      }
    }, this._keyboardUpEvent = (e) => {
      this._keyboardActive || (this._keyboardActive = !0, this._registerDevice(L.Keyboard, 0, Zi));
      const t = this._inputs[L.Keyboard][0];
      if (t) {
        t[e.keyCode] = 0;
        const i = e;
        if (i.inputIndex = e.keyCode, this._usingMacOS && e.key === "Meta" && this._metaKeys.length > 0) {
          for (const s of this._metaKeys) {
            const r = Mt.CreateDeviceEvent(L.Keyboard, 0, s, 0, this, this._elementToAttachTo);
            t[s] = 0, this._onInputChanged(L.Keyboard, 0, r);
          }
          this._metaKeys.splice(0, this._metaKeys.length);
        }
        this._onInputChanged(L.Keyboard, 0, i);
      }
    }, this._keyboardBlurEvent = () => {
      if (this._keyboardActive) {
        const e = this._inputs[L.Keyboard][0];
        for (let t = 0; t < e.length; t++)
          if (e[t] !== 0) {
            e[t] = 0;
            const i = Mt.CreateDeviceEvent(L.Keyboard, 0, t, 0, this, this._elementToAttachTo);
            this._onInputChanged(L.Keyboard, 0, i);
          }
        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 = Mi.IsNavigatorAvailable() && navigator.maxTouchPoints || 2, this._activeTouchIds || (this._activeTouchIds = new Array(this._maxTouchPoints));
    for (let i = 0; i < this._maxTouchPoints; i++)
      this._activeTouchIds[i] = -1;
    this._pointerMoveEvent = (i) => {
      const s = this._getPointerType(i), r = s === L.Mouse ? 0 : this._activeTouchIds.indexOf(i.pointerId);
      this._inputs[s] || (this._inputs[s] = {}), this._inputs[s][r] || this._addPointerDevice(s, r, i.clientX, i.clientY);
      const n = this._inputs[s][r];
      if (n) {
        const a = i;
        a.inputIndex = G.Move, n[G.Horizontal] = i.clientX, n[G.Vertical] = i.clientY, i.pointerId === void 0 && (i.pointerId = this._mouseId), this._onInputChanged(s, r, a), !this._usingSafari && i.button !== -1 && (a.inputIndex = i.button + 2, n[i.button + 2] = n[i.button + 2] ? 0 : 1, this._onInputChanged(s, r, a));
      }
    }, this._pointerDownEvent = (i) => {
      const s = this._getPointerType(i);
      let r = s === L.Mouse ? 0 : i.pointerId;
      if (s === L.Touch) {
        const a = this._activeTouchIds.indexOf(-1);
        if (a >= 0)
          r = a, this._activeTouchIds[a] = i.pointerId;
        else {
          k.Warn(`Max number of touches exceeded.  Ignoring touches in excess of ${this._maxTouchPoints}`);
          return;
        }
      }
      this._inputs[s] || (this._inputs[s] = {}), this._inputs[s][r] ? s === L.Touch && this._onDeviceConnected(s, r) : this._addPointerDevice(s, r, i.clientX, i.clientY);
      const n = this._inputs[s][r];
      if (n) {
        const a = n[G.Horizontal], o = n[G.Vertical];
        if (s === L.Mouse) {
          if (i.pointerId === void 0 && (i.pointerId = this._mouseId), !document.pointerLockElement)
            try {
              this._elementToAttachTo.setPointerCapture(this._mouseId);
            } catch {
            }
        } else if (i.pointerId && !document.pointerLockElement)
          try {
            this._elementToAttachTo.setPointerCapture(i.pointerId);
          } catch {
          }
        n[G.Horizontal] = i.clientX, n[G.Vertical] = i.clientY, n[i.button + 2] = 1;
        const h = i;
        h.inputIndex = i.button + 2, this._onInputChanged(s, r, h), (a !== i.clientX || o !== i.clientY) && (h.inputIndex = G.Move, this._onInputChanged(s, r, h));
      }
    }, this._pointerUpEvent = (i) => {
      var s, r, n, a, o;
      const h = this._getPointerType(i), c = h === L.Mouse ? 0 : this._activeTouchIds.indexOf(i.pointerId);
      if (h === L.Touch) {
        if (c === -1)
          return;
        this._activeTouchIds[c] = -1;
      }
      const u = (s = this._inputs[h]) === null || s === void 0 ? void 0 : s[c];
      if (u && u[i.button + 2] !== 0) {
        const d = u[G.Horizontal], g = u[G.Vertical];
        u[G.Horizontal] = i.clientX, u[G.Vertical] = i.clientY, u[i.button + 2] = 0;
        const f = i;
        i.pointerId === void 0 && (i.pointerId = this._mouseId), (d !== i.clientX || g !== i.clientY) && (f.inputIndex = G.Move, this._onInputChanged(h, c, f)), f.inputIndex = i.button + 2, h === L.Mouse && this._mouseId >= 0 && (!((n = (r = this._elementToAttachTo).hasPointerCapture) === null || n === void 0) && n.call(r, this._mouseId)) ? this._elementToAttachTo.releasePointerCapture(this._mouseId) : i.pointerId && (!((o = (a = this._elementToAttachTo).hasPointerCapture) === null || o === void 0) && o.call(a, i.pointerId)) && this._elementToAttachTo.releasePointerCapture(i.pointerId), this._onInputChanged(h, c, f), h === L.Touch && this._onDeviceDisconnected(h, c);
      }
    }, this._pointerCancelEvent = (i) => {
      var s, r, n, a;
      if (i.pointerType === "mouse") {
        const o = this._inputs[L.Mouse][0];
        this._mouseId >= 0 && (!((r = (s = this._elementToAttachTo).hasPointerCapture) === null || r === void 0) && r.call(s, this._mouseId)) && this._elementToAttachTo.releasePointerCapture(this._mouseId);
        for (let h = G.LeftClick; h <= G.BrowserForward; h++)
          if (o[h] === 1) {
            o[h] = 0;
            const c = Mt.CreateDeviceEvent(L.Mouse, 0, h, 0, this, this._elementToAttachTo);
            this._onInputChanged(L.Mouse, 0, c);
          }
      } else {
        const o = this._activeTouchIds.indexOf(i.pointerId);
        !((a = (n = this._elementToAttachTo).hasPointerCapture) === null || a === void 0) && a.call(n, i.pointerId) && this._elementToAttachTo.releasePointerCapture(i.pointerId), this._inputs[L.Touch][o][G.LeftClick] = 0;
        const h = Mt.CreateDeviceEvent(L.Touch, o, G.LeftClick, 0, this, this._elementToAttachTo, i.pointerId);
        this._onInputChanged(L.Touch, o, h), this._activeTouchIds[o] = -1, this._onDeviceDisconnected(L.Touch, o);
      }
    }, this._wheelEventName = "onwheel" in document.createElement("div") ? "wheel" : document.onmousewheel !== void 0 ? "mousewheel" : "DOMMouseScroll";
    let e = !1;
    const t = function() {
    };
    try {
      const i = Object.defineProperty({}, "passive", {
        get: function() {
          e = !0;
        }
      });
      this._elementToAttachTo.addEventListener("test", t, i), this._elementToAttachTo.removeEventListener("test", t, i);
    } catch {
    }
    this._pointerBlurEvent = () => {
      var i, s, r, n, a;
      if (this.isDeviceAvailable(L.Mouse)) {
        const o = this._inputs[L.Mouse][0];
        this._mouseId >= 0 && (!((s = (i = this._elementToAttachTo).hasPointerCapture) === null || s === void 0) && s.call(i, this._mouseId)) && this._elementToAttachTo.releasePointerCapture(this._mouseId);
        for (let h = G.LeftClick; h <= G.BrowserForward; h++)
          if (o[h] === 1) {
            o[h] = 0;
            const c = Mt.CreateDeviceEvent(L.Mouse, 0, h, 0, this, this._elementToAttachTo);
            this._onInputChanged(L.Mouse, 0, c);
          }
      }
      if (this.isDeviceAvailable(L.Touch)) {
        const o = this._inputs[L.Touch];
        for (let h = 0; h < this._activeTouchIds.length; h++) {
          const c = this._activeTouchIds[h];
          if (!((n = (r = this._elementToAttachTo).hasPointerCapture) === null || n === void 0) && n.call(r, c) && this._elementToAttachTo.releasePointerCapture(c), c !== -1 && ((a = o[h]) === null || a === void 0 ? void 0 : a[G.LeftClick]) === 1) {
            o[h][G.LeftClick] = 0;
            const u = Mt.CreateDeviceEvent(L.Touch, h, G.LeftClick, 0, this, this._elementToAttachTo, c);
            this._onInputChanged(L.Touch, h, u), this._activeTouchIds[h] = -1, this._onDeviceDisconnected(L.Touch, h);
          }
        }
      }
    }, this._pointerWheelEvent = (i) => {
      const s = L.Mouse, r = 0;
      this._inputs[s] || (this._inputs[s] = []), this._inputs[s][r] || (this._pointerActive = !0, this._registerDevice(s, r, ji));
      const n = this._inputs[s][r];
      if (n) {
        n[G.MouseWheelX] = i.deltaX || 0, n[G.MouseWheelY] = i.deltaY || i.wheelDelta || 0, n[G.MouseWheelZ] = i.deltaZ || 0;
        const a = i;
        i.pointerId === void 0 && (i.pointerId = this._mouseId), n[G.MouseWheelX] !== 0 && (a.inputIndex = G.MouseWheelX, this._onInputChanged(s, r, a)), n[G.MouseWheelY] !== 0 && (a.inputIndex = G.MouseWheelY, this._onInputChanged(s, r, a)), n[G.MouseWheelZ] !== 0 && (a.inputIndex = G.MouseWheelZ, this._onInputChanged(s, r, a));
      }
    }, 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("blur", this._pointerBlurEvent), this._elementToAttachTo.addEventListener(this._wheelEventName, this._pointerWheelEvent, e ? { passive: !1 } : !1), this._pointerInputClearObserver = this._engine.onEndFrameObservable.add(() => {
      if (this.isDeviceAvailable(L.Mouse)) {
        const i = this._inputs[L.Mouse][0];
        i[G.MouseWheelX] = 0, i[G.MouseWheelY] = 0, i[G.MouseWheelZ] = 0;
      }
    });
  }
  /**
   * Handle all actions that come from gamepad interaction
   */
  _handleGamepadActions() {
    this._gamepadConnectedEvent = (e) => {
      this._addGamePad(e.gamepad);
    }, this._gamepadDisconnectedEvent = (e) => {
      if (this._gamepads) {
        const t = this._getGamepadDeviceType(e.gamepad.id), i = e.gamepad.index;
        this._unregisterDevice(t, i), delete this._gamepads[i];
      }
    }, 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(e, t, i) {
    const s = navigator.getGamepads()[t];
    if (s && e === this._gamepads[t]) {
      const r = this._inputs[e][t];
      i >= s.buttons.length ? r[i] = s.axes[i - s.buttons.length].valueOf() : r[i] = s.buttons[i].value;
    }
  }
  /**
   * Gets DeviceType from the device name
   * @param deviceName Name of Device from DeviceInputSystem
   * @returns DeviceType enum value
   */
  _getGamepadDeviceType(e) {
    return e.indexOf("054c") !== -1 ? e.indexOf("0ce6") !== -1 ? L.DualSense : L.DualShock : e.indexOf("Xbox One") !== -1 || e.search("Xbox 360") !== -1 || e.search("xinput") !== -1 ? L.Xbox : e.indexOf("057e") !== -1 ? L.Switch : L.Generic;
  }
  /**
   * Get DeviceType from a given pointer/mouse/touch event.
   * @param evt PointerEvent to evaluate
   * @returns DeviceType interpreted from event
   */
  _getPointerType(e) {
    let t = L.Mouse;
    return (e.pointerType === "touch" || e.pointerType === "pen" || e.touches) && (t = L.Touch), t;
  }
}
class Qi {
  /**
   * Default Constructor
   * @param deviceInputSystem - Reference to DeviceInputSystem
   * @param deviceType - Type of device
   * @param deviceSlot - "Slot" or index that device is referenced in
   */
  constructor(e, t, i = 0) {
    this.deviceType = t, this.deviceSlot = i, this.onInputChangedObservable = new w(), this._deviceInputSystem = e;
  }
  /**
   * Get input for specific input
   * @param inputIndex - index of specific input on device
   * @returns Input value from DeviceInputSystem
   */
  getInput(e) {
    return this._deviceInputSystem.pollInput(this.deviceType, this.deviceSlot, e);
  }
}
class lr {
  constructor(e) {
    this._registeredManagers = new Array(), this._refCount = 0, this.registerManager = (n) => {
      for (let a = 0; a < this._devices.length; a++) {
        const o = this._devices[a];
        for (const h in o) {
          const c = +h;
          n._addDevice(new Qi(this._deviceInputSystem, a, c));
        }
      }
      this._registeredManagers.push(n);
    }, this.unregisterManager = (n) => {
      const a = this._registeredManagers.indexOf(n);
      a > -1 && this._registeredManagers.splice(a, 1);
    };
    const t = Object.keys(L).length / 2;
    this._devices = new Array(t);
    const i = (n, a) => {
      this._devices[n] || (this._devices[n] = new Array()), this._devices[n][a] || (this._devices[n][a] = a);
      for (const o of this._registeredManagers) {
        const h = new Qi(this._deviceInputSystem, n, a);
        o._addDevice(h);
      }
    }, s = (n, a) => {
      var o;
      !((o = this._devices[n]) === null || o === void 0) && o[a] && delete this._devices[n][a];
      for (const h of this._registeredManagers)
        h._removeDevice(n, a);
    }, r = (n, a, o) => {
      if (o)
        for (const h of this._registeredManagers)
          h._onInputChanged(n, a, o);
    };
    typeof _native < "u" ? this._deviceInputSystem = new or(i, s, r) : this._deviceInputSystem = new hr(e, i, s, r);
  }
  dispose() {
    this._deviceInputSystem.dispose();
  }
}
class cr {
  // 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(e, t) {
    if (t === void 0) {
      if (this._firstDevice[e] === void 0)
        return null;
      t = this._firstDevice[e];
    }
    return !this._devices[e] || this._devices[e][t] === void 0 ? null : this._devices[e][t];
  }
  /**
   * 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(e) {
    return this._devices[e] ? this._devices[e].filter((t) => !!t) : [];
  }
  /**
   * Default constructor
   * @param engine - Used to get canvas (if applicable)
   */
  constructor(e) {
    const t = Object.keys(L).length / 2;
    this._devices = new Array(t), this._firstDevice = new Array(t), this._engine = e, this._engine._deviceSourceManager || (this._engine._deviceSourceManager = new lr(e)), this._engine._deviceSourceManager._refCount++, this.onDeviceConnectedObservable = new w((i) => {
      for (const s of this._devices)
        if (s)
          for (const r of s)
            r && this.onDeviceConnectedObservable.notifyObserver(i, r);
    }), this.onDeviceDisconnectedObservable = new w(), this._engine._deviceSourceManager.registerManager(this), this._onDisposeObserver = e.onDisposeObservable.add(() => {
      this.dispose();
    });
  }
  /**
   * Dispose of DeviceSourceManager
   */
  dispose() {
    this.onDeviceConnectedObservable.clear(), this.onDeviceDisconnectedObservable.clear(), this._engine._deviceSourceManager && (this._engine._deviceSourceManager.unregisterManager(this), --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(e) {
    this._devices[e.deviceType] || (this._devices[e.deviceType] = new Array()), this._devices[e.deviceType][e.deviceSlot] || (this._devices[e.deviceType][e.deviceSlot] = e, this._updateFirstDevices(e.deviceType)), this.onDeviceConnectedObservable.notifyObservers(e);
  }
  /**
   * @param deviceType - DeviceType
   * @param deviceSlot - DeviceSlot
   * @internal
   */
  _removeDevice(e, t) {
    var i, s;
    const r = (i = this._devices[e]) === null || i === void 0 ? void 0 : i[t];
    this.onDeviceDisconnectedObservable.notifyObservers(r), !((s = this._devices[e]) === null || s === void 0) && s[t] && delete this._devices[e][t], this._updateFirstDevices(e);
  }
  /**
   * @param deviceType - DeviceType
   * @param deviceSlot - DeviceSlot
   * @param eventData - Event
   * @internal
   */
  _onInputChanged(e, t, i) {
    var s, r;
    (r = (s = this._devices[e]) === null || s === void 0 ? void 0 : s[t]) === null || r === void 0 || r.onInputChangedObservable.notifyObservers(i);
  }
  // Private Functions
  _updateFirstDevices(e) {
    switch (e) {
      case L.Keyboard:
      case L.Mouse:
        this._firstDevice[e] = 0;
        break;
      case L.Touch:
      case L.DualSense:
      case L.DualShock:
      case L.Xbox:
      case L.Switch:
      case L.Generic: {
        delete this._firstDevice[e];
        const t = this._devices[e];
        if (t) {
          for (let i = 0; i < t.length; i++)
            if (t[i]) {
              this._firstDevice[e] = i;
              break;
            }
        }
        break;
      }
    }
  }
}
class $i {
  constructor() {
    this._singleClick = !1, this._doubleClick = !1, this._hasSwiped = !1, this._ignore = !1;
  }
  get singleClick() {
    return this._singleClick;
  }
  get doubleClick() {
    return this._doubleClick;
  }
  get hasSwiped() {
    return this._hasSwiped;
  }
  get ignore() {
    return this._ignore;
  }
  set singleClick(e) {
    this._singleClick = e;
  }
  set doubleClick(e) {
    this._doubleClick = e;
  }
  set hasSwiped(e) {
    this._hasSwiped = e;
  }
  set ignore(e) {
    this._ignore = e;
  }
}
class _e {
  /**
   * Creates a new InputManager
   * @param scene - defines the hosting scene
   */
  constructor(e) {
    this._alreadyAttached = !1, this._meshPickProceed = !1, this._currentPickResult = null, this._previousPickResult = null, this._totalPointersPressed = 0, this._doubleClickOccured = !1, this._isSwiping = !1, this._swipeButtonPressed = -1, this._skipPointerTap = !1, this._isMultiTouchGesture = !1, this._pointerX = 0, this._pointerY = 0, this._startingPointerPosition = new le(0, 0), this._previousStartingPointerPosition = new le(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 = e || J.LastCreatedScene, this._scene;
  }
  /**
   * Gets the mesh that is currently under the pointer
   * @returns Mesh that the pointer is pointer is hovering over
   */
  get meshUnderPointer() {
    return this._movePointerInfo && (this._movePointerInfo._generatePickInfo(), this._movePointerInfo = null), 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(e) {
    return this._meshUnderPointerId[e] || 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 le(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(e) {
    this._pointerX = e;
  }
  /**
   * 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(e) {
    this._pointerY = e;
  }
  _updatePointerPosition(e) {
    const t = this._scene.getEngine().getInputElementClientRect();
    t && (this._pointerX = e.clientX - t.left, this._pointerY = e.clientY - t.top, this._unTranslatedPointerX = this._pointerX, this._unTranslatedPointerY = this._pointerY);
  }
  _processPointerMove(e, t) {
    const i = this._scene, s = i.getEngine(), r = s.getInputElement();
    r && (r.tabIndex = s.canvasTabIndex, i.doNotHandleCursors || (r.style.cursor = i.defaultCursor)), this._setCursorAndPointerOverMesh(e, t, i);
    for (const o of i._pointerMoveStage) {
      const h = !!(e != null && e.pickedMesh);
      e = o.action(this._unTranslatedPointerX, this._unTranslatedPointerY, e, h, r);
    }
    const n = t.inputIndex >= G.MouseWheelX && t.inputIndex <= G.MouseWheelZ ? ne.POINTERWHEEL : ne.POINTERMOVE;
    i.onPointerMove && (e = e || this._pickMove(t), i.onPointerMove(t, e, n));
    let a;
    e ? (a = new at(n, t, e), this._setRayOnPointerInfo(e, t)) : (a = new at(n, t, null, this), this._movePointerInfo = a), i.onPointerObservable.hasObservers() && i.onPointerObservable.notifyObservers(a, n);
  }
  // Pointers handling
  /** @internal */
  _setRayOnPointerInfo(e, t) {
    const i = this._scene;
    e && i._pickingAvailable && (e.ray || (e.ray = i.createPickingRay(t.offsetX, t.offsetY, R.Identity(), i.activeCamera)));
  }
  /** @internal */
  _addCameraPointerObserver(e, t) {
    return this._cameraObserverCount++, this._scene.onPointerObservable.add(e, t);
  }
  /** @internal */
  _removeCameraPointerObserver(e) {
    return this._cameraObserverCount--, this._scene.onPointerObservable.remove(e);
  }
  _checkForPicking() {
    return !!(this._scene.onPointerObservable.observers.length > this._cameraObserverCount || this._scene.onPointerPick);
  }
  _checkPrePointerObservable(e, t, i) {
    const s = this._scene, r = new ar(i, t, this._unTranslatedPointerX, this._unTranslatedPointerY);
    return e && (r.originalPickingInfo = e, r.ray = e.ray, e.originMesh && (r.nearInteractionPickingInfo = e)), s.onPrePointerObservable.notifyObservers(r, i), !!r.skipOnPointerObservable;
  }
  /** @internal */
  _pickMove(e) {
    const t = this._scene, i = t.pick(this._unTranslatedPointerX, this._unTranslatedPointerY, t.pointerMovePredicate, !1, t.cameraToUseForPointers, t.pointerMoveTrianglePredicate);
    return this._setCursorAndPointerOverMesh(i, e, t), i;
  }
  _setCursorAndPointerOverMesh(e, t, i) {
    const r = i.getEngine().getInputElement();
    if (e != null && e.pickedMesh) {
      if (this.setPointerOverMesh(e.pickedMesh, t.pointerId, e, t), !i.doNotHandleCursors && r && this._pointerOverMesh) {
        const n = this._pointerOverMesh._getActionManagerForTrigger();
        n && n.hasPointerTriggers && (r.style.cursor = n.hoverCursor || i.hoverCursor);
      }
    } else
      this.setPointerOverMesh(null, t.pointerId, e, t);
  }
  /**
   * 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(e, t) {
    const i = new PointerEvent("pointermove", t);
    i.inputIndex = G.Move, !this._checkPrePointerObservable(e, i, ne.POINTERMOVE) && this._processPointerMove(e, i);
  }
  /**
   * 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(e, t) {
    const i = new PointerEvent("pointerdown", t);
    i.inputIndex = i.button + 2, !this._checkPrePointerObservable(e, i, ne.POINTERDOWN) && this._processPointerDown(e, i);
  }
  _processPointerDown(e, t) {
    const i = this._scene;
    if (e != null && e.pickedMesh) {
      this._pickedDownMesh = e.pickedMesh;
      const n = e.pickedMesh._getActionManagerForTrigger();
      if (n) {
        if (n.hasPickTriggers)
          switch (n.processTrigger(5, Re.CreateNew(e.pickedMesh, t)), t.button) {
            case 0:
              n.processTrigger(2, Re.CreateNew(e.pickedMesh, t));
              break;
            case 1:
              n.processTrigger(4, Re.CreateNew(e.pickedMesh, t));
              break;
            case 2:
              n.processTrigger(3, Re.CreateNew(e.pickedMesh, t));
              break;
          }
        n.hasSpecificTrigger(8) && window.setTimeout(() => {
          const a = i.pick(this._unTranslatedPointerX, this._unTranslatedPointerY, (o) => o.isPickable && o.isVisible && o.isReady() && o.actionManager && o.actionManager.hasSpecificTrigger(8) && o === this._pickedDownMesh, !1, i.cameraToUseForPointers);
          a != null && a.pickedMesh && n && this._totalPointersPressed !== 0 && Date.now() - this._startingPointerTime > _e.LongPressDelay && !this._isPointerSwiping() && (this._startingPointerTime = 0, n.processTrigger(8, Re.CreateNew(a.pickedMesh, t)));
        }, _e.LongPressDelay);
      }
    } else
      for (const n of i._pointerDownStage)
        e = n.action(this._unTranslatedPointerX, this._unTranslatedPointerY, e, t, !1);
    let s;
    const r = ne.POINTERDOWN;
    e ? (i.onPointerDown && i.onPointerDown(t, e, r), s = new at(r, t, e), this._setRayOnPointerInfo(e, t)) : s = new at(r, t, null, this), i.onPointerObservable.hasObservers() && i.onPointerObservable.notifyObservers(s, r);
  }
  /**
   * @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(e, t, i) {
    const s = new PointerEvent("pointerup", t);
    s.inputIndex = G.Move;
    const r = new $i();
    i ? r.doubleClick = !0 : r.singleClick = !0, !this._checkPrePointerObservable(e, s, ne.POINTERUP) && this._processPointerUp(e, s, r);
  }
  _processPointerUp(e, t, i) {
    const s = this._scene;
    if (e != null && e.pickedMesh) {
      if (this._pickedUpMesh = e.pickedMesh, this._pickedDownMesh === this._pickedUpMesh && (s.onPointerPick && s.onPointerPick(t, e), i.singleClick && !i.ignore && s.onPointerObservable.observers.length > this._cameraObserverCount)) {
        const n = ne.POINTERPICK, a = new at(n, t, e);
        this._setRayOnPointerInfo(e, t), s.onPointerObservable.notifyObservers(a, n);
      }
      const r = e.pickedMesh._getActionManagerForTrigger();
      if (r && !i.ignore) {
        r.processTrigger(7, Re.CreateNew(e.pickedMesh, t, e)), !i.hasSwiped && i.singleClick && r.processTrigger(1, Re.CreateNew(e.pickedMesh, t, e));
        const n = e.pickedMesh._getActionManagerForTrigger(6);
        i.doubleClick && n && n.processTrigger(6, Re.CreateNew(e.pickedMesh, t, e));
      }
    } else if (!i.ignore)
      for (const r of s._pointerUpStage)
        e = r.action(this._unTranslatedPointerX, this._unTranslatedPointerY, e, t, i.doubleClick);
    if (this._pickedDownMesh && this._pickedDownMesh !== this._pickedUpMesh) {
      const r = this._pickedDownMesh._getActionManagerForTrigger(16);
      r && r.processTrigger(16, Re.CreateNew(this._pickedDownMesh, t));
    }
    if (!i.ignore) {
      const r = new at(ne.POINTERUP, t, e);
      if (this._setRayOnPointerInfo(e, t), s.onPointerObservable.notifyObservers(r, ne.POINTERUP), s.onPointerUp && s.onPointerUp(t, e, ne.POINTERUP), !i.hasSwiped && !this._skipPointerTap && !this._isMultiTouchGesture) {
        let n = 0;
        if (i.singleClick ? n = ne.POINTERTAP : i.doubleClick && (n = ne.POINTERDOUBLETAP), n) {
          const a = new at(n, t, e);
          s.onPointerObservable.hasObservers() && s.onPointerObservable.hasSpecificMask(n) && s.onPointerObservable.notifyObservers(a, n);
        }
      }
    }
  }
  /**
   * 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(e = 0) {
    return this._pointerCaptures[e];
  }
  /**
   * 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(e = !0, t = !0, i = !0, s = null) {
    const r = this._scene, n = r.getEngine();
    s || (s = n.getInputElement()), this._alreadyAttached && this.detachControl(), s && (this._alreadyAttachedTo = s), this._deviceSourceManager = new cr(n), this._initActionManager = (a) => {
      if (!this._meshPickProceed) {
        const o = r.skipPointerUpPicking || r._registeredActions === 0 && !this._checkForPicking() && !r.onPointerUp ? null : r.pick(this._unTranslatedPointerX, this._unTranslatedPointerY, r.pointerUpPredicate, !1, r.cameraToUseForPointers);
        this._currentPickResult = o, o && (a = o.hit && o.pickedMesh ? o.pickedMesh._getActionManagerForTrigger() : null), this._meshPickProceed = !0;
      }
      return a;
    }, this._delayedSimpleClick = (a, o, h) => {
      if ((Date.now() - this._previousStartingPointerTime > _e.DoubleClickDelay && !this._doubleClickOccured || a !== this._previousButtonPressed) && (this._doubleClickOccured = !1, o.singleClick = !0, o.ignore = !1, this._delayedClicks[a])) {
        const c = this._delayedClicks[a].evt, u = ne.POINTERTAP, d = new at(u, c, this._currentPickResult);
        r.onPointerObservable.hasObservers() && r.onPointerObservable.hasSpecificMask(u) && r.onPointerObservable.notifyObservers(d, u), this._delayedClicks[a] = null;
      }
    }, this._initClickEvent = (a, o, h, c) => {
      var u, d;
      const g = new $i();
      this._currentPickResult = null;
      let f = null, m = a.hasSpecificMask(ne.POINTERPICK) || o.hasSpecificMask(ne.POINTERPICK) || a.hasSpecificMask(ne.POINTERTAP) || o.hasSpecificMask(ne.POINTERTAP) || a.hasSpecificMask(ne.POINTERDOUBLETAP) || o.hasSpecificMask(ne.POINTERDOUBLETAP);
      !m && Ke && (f = this._initActionManager(f, g), f && (m = f.hasPickTriggers));
      let b = !1;
      if (m) {
        const T = h.button;
        if (g.hasSwiped = this._isPointerSwiping(), !g.hasSwiped) {
          let M = !_e.ExclusiveDoubleClickMode;
          if (M || (M = !a.hasSpecificMask(ne.POINTERDOUBLETAP) && !o.hasSpecificMask(ne.POINTERDOUBLETAP), M && !Ke.HasSpecificTrigger(6) && (f = this._initActionManager(f, g), f && (M = !f.hasSpecificTrigger(6)))), M)
            (Date.now() - this._previousStartingPointerTime > _e.DoubleClickDelay || T !== this._previousButtonPressed) && (g.singleClick = !0, c(g, this._currentPickResult), b = !0);
          else {
            const A = {
              evt: h,
              clickInfo: g,
              timeoutId: window.setTimeout(this._delayedSimpleClick.bind(this, T, g, c), _e.DoubleClickDelay)
            };
            this._delayedClicks[T] = A;
          }
          let v = a.hasSpecificMask(ne.POINTERDOUBLETAP) || o.hasSpecificMask(ne.POINTERDOUBLETAP);
          !v && Ke.HasSpecificTrigger(6) && (f = this._initActionManager(f, g), f && (v = f.hasSpecificTrigger(6))), v && (T === this._previousButtonPressed && Date.now() - this._previousStartingPointerTime < _e.DoubleClickDelay && !this._doubleClickOccured ? (!g.hasSwiped && !this._isPointerSwiping() ? (this._previousStartingPointerTime = 0, this._doubleClickOccured = !0, g.doubleClick = !0, g.ignore = !1, _e.ExclusiveDoubleClickMode && this._delayedClicks[T] && (clearTimeout((u = this._delayedClicks[T]) === null || u === void 0 ? void 0 : u.timeoutId), this._delayedClicks[T] = null), c(g, this._currentPickResult)) : (this._doubleClickOccured = !1, this._previousStartingPointerTime = this._startingPointerTime, this._previousStartingPointerPosition.x = this._startingPointerPosition.x, this._previousStartingPointerPosition.y = this._startingPointerPosition.y, this._previousButtonPressed = T, _e.ExclusiveDoubleClickMode ? (this._delayedClicks[T] && (clearTimeout((d = this._delayedClicks[T]) === null || d === void 0 ? void 0 : d.timeoutId), this._delayedClicks[T] = null), c(g, this._previousPickResult)) : c(g, this._currentPickResult)), b = !0) : (this._doubleClickOccured = !1, this._previousStartingPointerTime = this._startingPointerTime, this._previousStartingPointerPosition.x = this._startingPointerPosition.x, this._previousStartingPointerPosition.y = this._startingPointerPosition.y, this._previousButtonPressed = T));
        }
      }
      b || c(g, this._currentPickResult);
    }, this._onPointerMove = (a) => {
      if (this._updatePointerPosition(a), !this._isSwiping && this._swipeButtonPressed !== -1 && (this._isSwiping = Math.abs(this._startingPointerPosition.x - this._pointerX) > _e.DragMovementThreshold || Math.abs(this._startingPointerPosition.y - this._pointerY) > _e.DragMovementThreshold), n.isPointerLock && n._verifyPointerLock(), this._checkPrePointerObservable(null, a, a.inputIndex >= G.MouseWheelX && a.inputIndex <= G.MouseWheelZ ? ne.POINTERWHEEL : ne.POINTERMOVE) || !r.cameraToUseForPointers && !r.activeCamera)
        return;
      if (r.skipPointerMovePicking) {
        this._processPointerMove(new ut(), a);
        return;
      }
      r.pointerMovePredicate || (r.pointerMovePredicate = (h) => h.isPickable && h.isVisible && h.isReady() && h.isEnabled() && (h.enablePointerMoveEvents || r.constantlyUpdateMeshUnderPointer || h._getActionManagerForTrigger() !== null) && (!r.cameraToUseForPointers || (r.cameraToUseForPointers.layerMask & h.layerMask) !== 0));
      const o = r._registeredActions > 0 ? this._pickMove(a) : null;
      this._processPointerMove(o, a);
    }, this._onPointerDown = (a) => {
      var o;
      if (this._totalPointersPressed++, this._pickedDownMesh = null, this._meshPickProceed = !1, _e.ExclusiveDoubleClickMode) {
        for (let c = 0; c < this._delayedClicks.length; c++)
          if (this._delayedClicks[c])
            if (a.button === c)
              clearTimeout((o = this._delayedClicks[c]) === null || o === void 0 ? void 0 : o.timeoutId);
            else {
              const u = this._delayedClicks[c].clickInfo;
              this._doubleClickOccured = !1, u.singleClick = !0, u.ignore = !1;
              const d = this._delayedClicks[c].evt, g = ne.POINTERTAP, f = new at(g, d, this._currentPickResult);
              r.onPointerObservable.hasObservers() && r.onPointerObservable.hasSpecificMask(g) && r.onPointerObservable.notifyObservers(f, g), this._delayedClicks[c] = null;
            }
      }
      if (this._updatePointerPosition(a), this._swipeButtonPressed === -1 && (this._swipeButtonPressed = a.button), r.preventDefaultOnPointerDown && s && (a.preventDefault(), s.focus()), this._startingPointerPosition.x = this._pointerX, this._startingPointerPosition.y = this._pointerY, this._startingPointerTime = Date.now(), this._checkPrePointerObservable(null, a, ne.POINTERDOWN) || !r.cameraToUseForPointers && !r.activeCamera)
        return;
      this._pointerCaptures[a.pointerId] = !0, r.pointerDownPredicate || (r.pointerDownPredicate = (c) => c.isPickable && c.isVisible && c.isReady() && c.isEnabled() && (!r.cameraToUseForPointers || (r.cameraToUseForPointers.layerMask & c.layerMask) !== 0)), this._pickedDownMesh = null;
      let h;
      r.skipPointerDownPicking || r._registeredActions === 0 && !this._checkForPicking() && !r.onPointerDown ? h = new ut() : h = r.pick(this._unTranslatedPointerX, this._unTranslatedPointerY, r.pointerDownPredicate, !1, r.cameraToUseForPointers), this._processPointerDown(h, a);
    }, this._onPointerUp = (a) => {
      this._totalPointersPressed !== 0 && (this._totalPointersPressed--, this._pickedUpMesh = null, this._meshPickProceed = !1, this._updatePointerPosition(a), r.preventDefaultOnPointerUp && s && (a.preventDefault(), s.focus()), this._initClickEvent(r.onPrePointerObservable, r.onPointerObservable, a, (o, h) => {
        if (r.onPrePointerObservable.hasObservers() && (this._skipPointerTap = !1, !o.ignore)) {
          if (this._checkPrePointerObservable(null, a, ne.POINTERUP)) {
            this._swipeButtonPressed === a.button && (this._isSwiping = !1, this._swipeButtonPressed = -1);
            return;
          }
          o.hasSwiped || (o.singleClick && r.onPrePointerObservable.hasSpecificMask(ne.POINTERTAP) && this._checkPrePointerObservable(null, a, ne.POINTERTAP) && (this._skipPointerTap = !0), o.doubleClick && r.onPrePointerObservable.hasSpecificMask(ne.POINTERDOUBLETAP) && this._checkPrePointerObservable(null, a, ne.POINTERDOUBLETAP) && (this._skipPointerTap = !0));
        }
        if (!this._pointerCaptures[a.pointerId]) {
          this._swipeButtonPressed === a.button && (this._isSwiping = !1, this._swipeButtonPressed = -1);
          return;
        }
        a.buttons === 0 && (this._pointerCaptures[a.pointerId] = !1), !(!r.cameraToUseForPointers && !r.activeCamera) && (r.pointerUpPredicate || (r.pointerUpPredicate = (c) => c.isPickable && c.isVisible && c.isReady() && c.isEnabled() && (!r.cameraToUseForPointers || (r.cameraToUseForPointers.layerMask & c.layerMask) !== 0)), !this._meshPickProceed && (Ke && Ke.HasTriggers || this._checkForPicking() || r.onPointerUp) && this._initActionManager(null, o), h || (h = this._currentPickResult), this._processPointerUp(h, a, o), this._previousPickResult = this._currentPickResult, this._swipeButtonPressed === a.button && (this._isSwiping = !1, this._swipeButtonPressed = -1));
      }));
    }, this._onKeyDown = (a) => {
      const o = ni.KEYDOWN;
      if (r.onPreKeyboardObservable.hasObservers()) {
        const h = new zi(o, a);
        if (r.onPreKeyboardObservable.notifyObservers(h, o), h.skipOnKeyboardObservable)
          return;
      }
      if (r.onKeyboardObservable.hasObservers()) {
        const h = new Ai(o, a);
        r.onKeyboardObservable.notifyObservers(h, o);
      }
      r.actionManager && r.actionManager.processTrigger(14, Re.CreateNewFromScene(r, a));
    }, this._onKeyUp = (a) => {
      const o = ni.KEYUP;
      if (r.onPreKeyboardObservable.hasObservers()) {
        const h = new zi(o, a);
        if (r.onPreKeyboardObservable.notifyObservers(h, o), h.skipOnKeyboardObservable)
          return;
      }
      if (r.onKeyboardObservable.hasObservers()) {
        const h = new Ai(o, a);
        r.onKeyboardObservable.notifyObservers(h, o);
      }
      r.actionManager && r.actionManager.processTrigger(15, Re.CreateNewFromScene(r, a));
    }, this._deviceSourceManager.onDeviceConnectedObservable.add((a) => {
      a.deviceType === L.Mouse ? a.onInputChangedObservable.add((o) => {
        o.inputIndex === G.LeftClick || o.inputIndex === G.MiddleClick || o.inputIndex === G.RightClick || o.inputIndex === G.BrowserBack || o.inputIndex === G.BrowserForward ? t && a.getInput(o.inputIndex) === 1 ? this._onPointerDown(o) : e && a.getInput(o.inputIndex) === 0 && this._onPointerUp(o) : i && (o.inputIndex === G.Move ? this._onPointerMove(o) : (o.inputIndex === G.MouseWheelX || o.inputIndex === G.MouseWheelY || o.inputIndex === G.MouseWheelZ) && this._onPointerMove(o));
      }) : a.deviceType === L.Touch ? a.onInputChangedObservable.add((o) => {
        o.inputIndex === G.LeftClick && (t && a.getInput(o.inputIndex) === 1 ? (this._onPointerDown(o), this._totalPointersPressed > 1 && (this._isMultiTouchGesture = !0)) : e && a.getInput(o.inputIndex) === 0 && (this._onPointerUp(o), this._totalPointersPressed === 0 && (this._isMultiTouchGesture = !1))), i && o.inputIndex === G.Move && this._onPointerMove(o);
      }) : a.deviceType === L.Keyboard && a.onInputChangedObservable.add((o) => {
        o.type === "keydown" ? this._onKeyDown(o) : o.type === "keyup" && this._onKeyUp(o);
      });
    }), this._alreadyAttached = !0;
  }
  /**
   * Detaches all event handlers
   */
  detachControl() {
    this._alreadyAttached && (this._deviceSourceManager.dispose(), this._deviceSourceManager = null, this._alreadyAttachedTo && !this._scene.doNotHandleCursors && (this._alreadyAttachedTo.style.cursor = this._scene.defaultCursor), this._alreadyAttached = !1, this._alreadyAttachedTo = null);
  }
  /**
   * Force the value of meshUnderPointer
   * @param mesh - defines the mesh to use
   * @param pointerId - optional pointer id when using more than one pointer. Defaults to 0
   * @param pickResult - optional pickingInfo data used to find mesh
   * @param evt - optional pointer event
   */
  setPointerOverMesh(e, t = 0, i, s) {
    if (this._meshUnderPointerId[t] === e && (!e || !e._internalAbstractMeshDataInfo._pointerOverDisableMeshTesting))
      return;
    const r = this._meshUnderPointerId[t];
    let n;
    r && (n = r._getActionManagerForTrigger(10), n && n.processTrigger(10, Re.CreateNew(r, s, { pointerId: t }))), e ? (this._meshUnderPointerId[t] = e, this._pointerOverMesh = e, n = e._getActionManagerForTrigger(9), n && n.processTrigger(9, Re.CreateNew(e, s, { pointerId: t, pickResult: i }))) : (delete this._meshUnderPointerId[t], this._pointerOverMesh = null);
  }
  /**
   * 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(e) {
    this._pointerOverMesh === e && (this._pointerOverMesh = null), this._pickedDownMesh === e && (this._pickedDownMesh = null), this._pickedUpMesh === e && (this._pickedUpMesh = null);
    for (const t in this._meshUnderPointerId)
      this._meshUnderPointerId[t] === e && delete this._meshUnderPointerId[t];
  }
}
_e.DragMovementThreshold = 10;
_e.LongPressDelay = 500;
_e.DoubleClickDelay = 300;
_e.ExclusiveDoubleClickMode = !1;
class Je {
  /**
   * 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(e, t) {
    Je.Enabled && (this._current += e, t && this._fetchResult());
  }
  /**
   * Start monitoring this performance counter
   */
  beginMonitoring() {
    Je.Enabled && (this._startMonitoringTime = Et.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(e = !0) {
    if (!Je.Enabled)
      return;
    e && this.fetchNewFrame();
    const t = Et.Now;
    this._current = t - this._startMonitoringTime, e && this._fetchResult();
  }
  _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 e = Et.Now;
    e - this._lastSecTime > 1e3 && (this._lastSecAverage = this._lastSecAccumulated / this._lastSecValueCount, this._lastSecTime = e, this._lastSecAccumulated = 0, this._lastSecValueCount = 0);
  }
}
Je.Enabled = !0;
class $e {
  /**
   * 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(e, t, i, s) {
    this.normal = new p(e, t, i), this.d = s;
  }
  /**
   * @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 $e(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 e = this.normal.getHashCode();
    return e = e * 397 ^ (this.d | 0), e;
  }
  /**
   * Normalize the current Plane in place.
   * @returns the updated Plane.
   */
  normalize() {
    const e = Math.sqrt(this.normal.x * this.normal.x + this.normal.y * this.normal.y + this.normal.z * this.normal.z);
    let t = 0;
    return e !== 0 && (t = 1 / e), this.normal.x *= t, this.normal.y *= t, this.normal.z *= t, this.d *= t, 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(e) {
    const t = $e._TmpMatrix;
    e.invertToRef(t);
    const i = t.m, s = this.normal.x, r = this.normal.y, n = this.normal.z, a = this.d, o = s * i[0] + r * i[1] + n * i[2] + a * i[3], h = s * i[4] + r * i[5] + n * i[6] + a * i[7], c = s * i[8] + r * i[9] + n * i[10] + a * i[11], u = s * i[12] + r * i[13] + n * i[14] + a * i[15];
    return new $e(o, h, c, u);
  }
  /**
   * 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(e) {
    return this.normal.x * e.x + this.normal.y * e.y + this.normal.z * e.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(e, t, i) {
    const s = t.x - e.x, r = t.y - e.y, n = t.z - e.z, a = i.x - e.x, o = i.y - e.y, h = i.z - e.z, c = r * h - n * o, u = n * a - s * h, d = s * o - r * a, g = Math.sqrt(c * c + u * u + d * d);
    let f;
    return g !== 0 ? f = 1 / g : f = 0, this.normal.x = c * f, this.normal.y = u * f, this.normal.z = d * f, this.d = -(this.normal.x * e.x + this.normal.y * e.y + this.normal.z * e.z), 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(e, t) {
    return p.Dot(this.normal, e) <= t;
  }
  /**
   * 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(e) {
    return p.Dot(e, 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(e) {
    return new $e(e[0], e[1], e[2], e[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(e, t, i) {
    const s = new $e(0, 0, 0, 0);
    return s.copyFromPoints(e, t, i), s;
  }
  /**
   * 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.
   * Note : the vector "normal" is updated because normalized.
   */
  static FromPositionAndNormal(e, t) {
    const i = new $e(0, 0, 0, 0);
    return t.normalize(), i.normal = t, i.d = -(t.x * e.x + t.y * e.y + t.z * e.z), i;
  }
  /**
   * 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(e, t, i) {
    const s = -(t.x * e.x + t.y * e.y + t.z * e.z);
    return p.Dot(i, t) + s;
  }
}
$e._TmpMatrix = R.Identity();
class Xe {
  /**
   * 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(e) {
    const t = [];
    for (let i = 0; i < 6; i++)
      t.push(new $e(0, 0, 0, 0));
    return Xe.GetPlanesToRef(e, t), t;
  }
  /**
   * 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(e, t) {
    const i = e.m;
    t.normal.x = i[3] + i[2], t.normal.y = i[7] + i[6], t.normal.z = i[11] + i[10], t.d = i[15] + i[14], t.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(e, t) {
    const i = e.m;
    t.normal.x = i[3] - i[2], t.normal.y = i[7] - i[6], t.normal.z = i[11] - i[10], t.d = i[15] - i[14], t.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(e, t) {
    const i = e.m;
    t.normal.x = i[3] + i[0], t.normal.y = i[7] + i[4], t.normal.z = i[11] + i[8], t.d = i[15] + i[12], t.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(e, t) {
    const i = e.m;
    t.normal.x = i[3] - i[0], t.normal.y = i[7] - i[4], t.normal.z = i[11] - i[8], t.d = i[15] - i[12], t.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(e, t) {
    const i = e.m;
    t.normal.x = i[3] - i[1], t.normal.y = i[7] - i[5], t.normal.z = i[11] - i[9], t.d = i[15] - i[13], t.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(e, t) {
    const i = e.m;
    t.normal.x = i[3] + i[1], t.normal.y = i[7] + i[5], t.normal.z = i[11] + i[9], t.d = i[15] + i[13], t.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(e, t) {
    Xe.GetNearPlaneToRef(e, t[0]), Xe.GetFarPlaneToRef(e, t[1]), Xe.GetLeftPlaneToRef(e, t[2]), Xe.GetRightPlaneToRef(e, t[3]), Xe.GetTopPlaneToRef(e, t[4]), Xe.GetBottomPlaneToRef(e, t[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(e, t) {
    for (let i = 0; i < 6; i++)
      if (t[i].dotCoordinate(e) < 0)
        return !1;
    return !0;
  }
}
class fs {
  /**
   * Gets an unique (relatively to the current scene) Id
   */
  static get UniqueId() {
    const e = this._UniqueIdCounter;
    return this._UniqueIdCounter++, e;
  }
}
fs._UniqueIdCounter = 1;
class me {
  /**
   * 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(e, t) {
    return e.shadowEnabled !== t.shadowEnabled ? (t.shadowEnabled ? 1 : 0) - (e.shadowEnabled ? 1 : 0) : t.renderPriority - e.renderPriority;
  }
}
me.FALLOFF_DEFAULT = 0;
me.FALLOFF_PHYSICAL = 1;
me.FALLOFF_GLTF = 2;
me.FALLOFF_STANDARD = 3;
me.LIGHTMAP_DEFAULT = 0;
me.LIGHTMAP_SPECULAR = 1;
me.LIGHTMAP_SHADOWSONLY = 2;
me.INTENSITYMODE_AUTOMATIC = 0;
me.INTENSITYMODE_LUMINOUSPOWER = 1;
me.INTENSITYMODE_LUMINOUSINTENSITY = 2;
me.INTENSITYMODE_ILLUMINANCE = 3;
me.INTENSITYMODE_LUMINANCE = 4;
me.LIGHTTYPEID_POINTLIGHT = 0;
me.LIGHTTYPEID_DIRECTIONALLIGHT = 1;
me.LIGHTTYPEID_SPOTLIGHT = 2;
me.LIGHTTYPEID_HEMISPHERICLIGHT = 3;
var et;
(function(l) {
  l[l.BackwardCompatible = 0] = "BackwardCompatible", l[l.Intermediate = 1] = "Intermediate", l[l.Aggressive = 2] = "Aggressive";
})(et || (et = {}));
class Q extends Li {
  /**
   * Factory used to create the default material.
   * @param scene The scene to create the material for
   * @returns The default material
   */
  static DefaultMaterialFactory(e) {
    throw Y("StandardMaterial");
  }
  /**
   * Factory used to create the a collision coordinator.
   * @returns The collision coordinator
   */
  static CollisionCoordinatorFactory() {
    throw Y("DefaultCollisionCoordinator");
  }
  /**
   * 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(e) {
    this._environmentTexture !== e && (this._environmentTexture = e, this.markAllMaterialsAsDirty(1));
  }
  /**
   * 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(e) {
    if (e !== this._performancePriority) {
      switch (this._performancePriority = e, e) {
        case et.BackwardCompatible:
          this.skipFrustumClipping = !1, this._renderingManager.maintainStateBetweenFrames = !1, this.skipPointerMovePicking = !1, this.autoClear = !0;
          break;
        case et.Intermediate:
          this.skipFrustumClipping = !1, this._renderingManager.maintainStateBetweenFrames = !1, this.skipPointerMovePicking = !0, this.autoClear = !1;
          break;
        case et.Aggressive:
          this.skipFrustumClipping = !0, this._renderingManager.maintainStateBetweenFrames = !0, this.skipPointerMovePicking = !0, this.autoClear = !1;
          break;
      }
      this.onScenePerformancePriorityChangedObservable.notifyObservers(e);
    }
  }
  /**
   * Gets or sets a boolean indicating if all rendering must be done in wireframe
   */
  set forceWireframe(e) {
    this._forceWireframe !== e && (this._forceWireframe = e, 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(e) {
    this._skipFrustumClipping !== e && (this._skipFrustumClipping = e);
  }
  get skipFrustumClipping() {
    return this._skipFrustumClipping;
  }
  /**
   * Gets or sets a boolean indicating if all rendering must be done in point cloud
   */
  set forcePointsCloud(e) {
    this._forcePointsCloud !== e && (this._forcePointsCloud = e, this.markAllMaterialsAsDirty(16));
  }
  get forcePointsCloud() {
    return this._forcePointsCloud;
  }
  /**
   * Gets or sets the animation properties override
   */
  get animationPropertiesOverride() {
    return this._animationPropertiesOverride;
  }
  set animationPropertiesOverride(e) {
    this._animationPropertiesOverride = e;
  }
  /** Sets a function to be executed when this scene is disposed. */
  set onDispose(e) {
    this._onDisposeObserver && this.onDisposeObservable.remove(this._onDisposeObserver), this._onDisposeObserver = this.onDisposeObservable.add(e);
  }
  /** Sets a function to be executed before rendering this scene */
  set beforeRender(e) {
    this._onBeforeRenderObserver && this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver), e && (this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(e));
  }
  /** Sets a function to be executed after rendering this scene */
  set afterRender(e) {
    this._onAfterRenderObserver && this.onAfterRenderObservable.remove(this._onAfterRenderObserver), e && (this._onAfterRenderObserver = this.onAfterRenderObservable.add(e));
  }
  /** Sets a function to be executed before rendering a camera*/
  set beforeCameraRender(e) {
    this._onBeforeCameraRenderObserver && this.onBeforeCameraRenderObservable.remove(this._onBeforeCameraRenderObserver), this._onBeforeCameraRenderObserver = this.onBeforeCameraRenderObservable.add(e);
  }
  /** Sets a function to be executed after rendering a camera*/
  set afterCameraRender(e) {
    this._onAfterCameraRenderObserver && this.onAfterCameraRenderObservable.remove(this._onAfterCameraRenderObserver), this._onAfterCameraRenderObserver = this.onAfterCameraRenderObservable.add(e);
  }
  /**
   * 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 _e.DragMovementThreshold;
  }
  static set DragMovementThreshold(e) {
    _e.DragMovementThreshold = e;
  }
  /**
   * Time in milliseconds to wait to raise long press events if button is still pressed. Default is 500 ms
   */
  static get LongPressDelay() {
    return _e.LongPressDelay;
  }
  static set LongPressDelay(e) {
    _e.LongPressDelay = e;
  }
  /**
   * Time in milliseconds to wait to raise long press events if button is still pressed. Default is 300 ms
   */
  static get DoubleClickDelay() {
    return _e.DoubleClickDelay;
  }
  static set DoubleClickDelay(e) {
    _e.DoubleClickDelay = e;
  }
  /** If you need to check double click without raising a single click at first click, enable this flag */
  static get ExclusiveDoubleClickMode() {
    return _e.ExclusiveDoubleClickMode;
  }
  static set ExclusiveDoubleClickMode(e) {
    _e.ExclusiveDoubleClickMode = e;
  }
  /**
   * 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(e, t = "vEyePosition", i = !1) {
    var s;
    const r = this._forcedViewPosition ? this._forcedViewPosition : this._mirroredCameraPosition ? this._mirroredCameraPosition : (s = this.activeCamera.globalPosition) !== null && s !== void 0 ? s : this.activeCamera.devicePosition, n = this.useRightHandedSystem === (this._mirroredCameraPosition != null);
    return C.Vector4[0].set(r.x, r.y, r.z, n ? -1 : 1), e && (i ? e.setFloat3(t, C.Vector4[0].x, C.Vector4[0].y, C.Vector4[0].z) : e.setVector4(t, C.Vector4[0])), C.Vector4[0];
  }
  /**
   * Update the scene ubo before it can be used in rendering processing
   * @returns the scene UniformBuffer
   */
  finalizeSceneUbo() {
    const e = this.getSceneUniformBuffer(), t = this.bindEyePosition(null);
    return e.updateFloat4("vEyePosition", t.x, t.y, t.z, t.w), e.update(), e;
  }
  /**
   * Gets or sets a boolean indicating if the scene must use right-handed coordinates system
   */
  set useRightHandedSystem(e) {
    this._useRightHandedSystem !== e && (this._useRightHandedSystem = e, 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(e) {
    this._currentStepId = e;
  }
  /**
   * 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(e) {
    this._fogEnabled !== e && (this._fogEnabled = e, 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(e) {
    this._fogMode !== e && (this._fogMode = e, 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(e) {
    this._shadowsEnabled !== e && (this._shadowsEnabled = e, this.markAllMaterialsAsDirty(2));
  }
  get shadowsEnabled() {
    return this._shadowsEnabled;
  }
  /**
   * Gets or sets a boolean indicating if lights are enabled on this scene
   */
  set lightsEnabled(e) {
    this._lightsEnabled !== e && (this._lightsEnabled = e, this.markAllMaterialsAsDirty(2));
  }
  get lightsEnabled() {
    return this._lightsEnabled;
  }
  /** All of the active cameras added to this scene. */
  get activeCameras() {
    return this._activeCameras;
  }
  set activeCameras(e) {
    this._unObserveActiveCameras && (this._unObserveActiveCameras(), this._unObserveActiveCameras = null), e && (this._unObserveActiveCameras = $s(e, () => {
      this.onActiveCamerasChanged.notifyObservers(this);
    })), this._activeCameras = e;
  }
  /** Gets or sets the current active camera */
  get activeCamera() {
    return this._activeCamera;
  }
  set activeCamera(e) {
    e !== this._activeCamera && (this._activeCamera = e, this.onActiveCameraChanged.notifyObservers(this));
  }
  /** The default material used on meshes when no material is affected */
  get defaultMaterial() {
    return this._defaultMaterial || (this._defaultMaterial = Q.DefaultMaterialFactory(this)), this._defaultMaterial;
  }
  /** The default material used on meshes when no material is affected */
  set defaultMaterial(e) {
    this._defaultMaterial = e;
  }
  /**
   * Gets or sets a boolean indicating if textures are enabled on this scene
   */
  set texturesEnabled(e) {
    this._texturesEnabled !== e && (this._texturesEnabled = e, this.markAllMaterialsAsDirty(1));
  }
  get texturesEnabled() {
    return this._texturesEnabled;
  }
  /**
   * Gets or sets a boolean indicating if skeletons are enabled on this scene
   */
  set skeletonsEnabled(e) {
    this._skeletonsEnabled !== e && (this._skeletonsEnabled = e, this.markAllMaterialsAsDirty(8));
  }
  get skeletonsEnabled() {
    return this._skeletonsEnabled;
  }
  /** @internal */
  get collisionCoordinator() {
    return this._collisionCoordinator || (this._collisionCoordinator = Q.CollisionCoordinatorFactory(), this._collisionCoordinator.init(this)), 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 e of this._transientComponents)
        e.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(e) {
    this._components.push(e), this._transientComponents.push(e);
    const t = e;
    t.addFromContainer && t.serialize && this._serializableComponents.push(t);
  }
  /**
   * @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(e) {
    for (const t of this._components)
      if (t.name === e)
        return t;
    return null;
  }
  /**
   * Creates a new Scene
   * @param engine defines the engine to use to render this scene
   * @param options defines the scene options
   */
  constructor(e, t) {
    super(), this._inputManager = new _e(this), this.cameraToUseForPointers = null, this._isScene = !0, this._blockEntityCollection = !1, this.autoClear = !0, this.autoClearDepthAndStencil = !0, this.clearColor = new Oe(0.2, 0.2, 0.3, 1), this.ambientColor = new te(0, 0, 0), this.environmentIntensity = 1, this._performancePriority = et.BackwardCompatible, this.onScenePerformancePriorityChangedObservable = new w(), this._forceWireframe = !1, this._skipFrustumClipping = !1, this._forcePointsCloud = !1, this.animationsEnabled = !0, this._animationPropertiesOverride = null, this.useConstantAnimationDeltaTime = !1, this.constantlyUpdateMeshUnderPointer = !1, this.hoverCursor = "pointer", this.defaultCursor = "", this.doNotHandleCursors = !1, this.preventDefaultOnPointerDown = !0, this.preventDefaultOnPointerUp = !0, this.metadata = null, this.reservedDataStore = null, this.disableOfflineSupportExceptionRules = new Array(), this.onDisposeObservable = new w(), this._onDisposeObserver = null, this.onBeforeRenderObservable = new w(), this._onBeforeRenderObserver = null, this.onAfterRenderObservable = new w(), this.onAfterRenderCameraObservable = new w(), this._onAfterRenderObserver = null, this.onBeforeAnimationsObservable = new w(), this.onAfterAnimationsObservable = new w(), this.onBeforeDrawPhaseObservable = new w(), this.onAfterDrawPhaseObservable = new w(), this.onReadyObservable = new w(), this.onBeforeCameraRenderObservable = new w(), this._onBeforeCameraRenderObserver = null, this.onAfterCameraRenderObservable = new w(), this._onAfterCameraRenderObserver = null, this.onBeforeActiveMeshesEvaluationObservable = new w(), this.onAfterActiveMeshesEvaluationObservable = new w(), this.onBeforeParticlesRenderingObservable = new w(), this.onAfterParticlesRenderingObservable = new w(), this.onDataLoadedObservable = new w(), this.onNewCameraAddedObservable = new w(), this.onCameraRemovedObservable = new w(), this.onNewLightAddedObservable = new w(), this.onLightRemovedObservable = new w(), this.onNewGeometryAddedObservable = new w(), this.onGeometryRemovedObservable = new w(), this.onNewTransformNodeAddedObservable = new w(), this.onTransformNodeRemovedObservable = new w(), this.onNewMeshAddedObservable = new w(), this.onMeshRemovedObservable = new w(), this.onNewSkeletonAddedObservable = new w(), this.onSkeletonRemovedObservable = new w(), this.onNewMaterialAddedObservable = new w(), this.onNewMultiMaterialAddedObservable = new w(), this.onMaterialRemovedObservable = new w(), this.onMultiMaterialRemovedObservable = new w(), this.onNewTextureAddedObservable = new w(), this.onTextureRemovedObservable = new w(), this.onBeforeRenderTargetsRenderObservable = new w(), this.onAfterRenderTargetsRenderObservable = new w(), this.onBeforeStepObservable = new w(), this.onAfterStepObservable = new w(), this.onActiveCameraChanged = new w(), this.onActiveCamerasChanged = new w(), this.onBeforeRenderingGroupObservable = new w(), this.onAfterRenderingGroupObservable = new w(), this.onMeshImportedObservable = new w(), this.onAnimationFileImportedObservable = new w(), this._registeredForLateAnimationBindings = new Tt(256), this.skipPointerMovePicking = !1, this.skipPointerDownPicking = !1, this.skipPointerUpPicking = !1, this.onPrePointerObservable = new w(), this.onPointerObservable = new w(), this.onPreKeyboardObservable = new w(), this.onKeyboardObservable = new w(), this._useRightHandedSystem = !1, this._timeAccumulator = 0, this._currentStepId = 0, this._currentInternalStep = 0, this._fogEnabled = !0, this._fogMode = Q.FOGMODE_NONE, this.fogColor = new te(0.2, 0.2, 0.3), this.fogDensity = 0.1, this.fogStart = 0, this.fogEnd = 1e3, this.needsPreviousWorldMatrices = !1, this._shadowsEnabled = !0, this._lightsEnabled = !0, this._unObserveActiveCameras = null, this._texturesEnabled = !0, this.physicsEnabled = !0, this.particlesEnabled = !0, this.spritesEnabled = !0, this._skeletonsEnabled = !0, this.lensFlaresEnabled = !0, this.collisionsEnabled = !0, this.gravity = new p(0, -9.807, 0), this.postProcessesEnabled = !0, this.renderTargetsEnabled = !0, this.dumpNextRenderTargets = !1, this.customRenderTargets = new Array(), this.importedMeshesFiles = new Array(), this.probesEnabled = !0, this._meshesForIntersections = new Tt(256), this.proceduralTexturesEnabled = !0, this._totalVertices = new Je(), this._activeIndices = new Je(), this._activeParticles = new Je(), this._activeBones = new Je(), this._animationTime = 0, this.animationTimeScale = 1, this._renderId = 0, this._frameId = 0, this._executeWhenReadyTimeoutId = null, this._intermediateRendering = !1, this._defaultFrameBufferCleared = !1, this._viewUpdateFlag = -1, this._projectionUpdateFlag = -1, this._toBeDisposed = new Array(256), this._activeRequests = new Array(), this._pendingData = new Array(), this._isDisposed = !1, this.dispatchAllSubMeshesOfActiveMeshes = !1, this._activeMeshes = new We(256), this._processedMaterials = new We(256), this._renderTargets = new Tt(256), this._materialsRenderTargets = new Tt(256), this._activeParticleSystems = new We(256), this._activeSkeletons = new Tt(32), this._softwareSkinnedMeshes = new Tt(32), this._activeAnimatables = new Array(), this._transformMatrix = R.Zero(), this.requireLightSorting = !1, this._components = [], this._serializableComponents = [], this._transientComponents = [], this._beforeCameraUpdateStage = fe.Create(), this._beforeClearStage = fe.Create(), this._beforeRenderTargetClearStage = fe.Create(), this._gatherRenderTargetsStage = fe.Create(), this._gatherActiveCameraRenderTargetsStage = fe.Create(), this._isReadyForMeshStage = fe.Create(), this._beforeEvaluateActiveMeshStage = fe.Create(), this._evaluateSubMeshStage = fe.Create(), this._preActiveMeshStage = fe.Create(), this._cameraDrawRenderTargetStage = fe.Create(), this._beforeCameraDrawStage = fe.Create(), this._beforeRenderTargetDrawStage = fe.Create(), this._beforeRenderingGroupDrawStage = fe.Create(), this._beforeRenderingMeshStage = fe.Create(), this._afterRenderingMeshStage = fe.Create(), this._afterRenderingGroupDrawStage = fe.Create(), this._afterCameraDrawStage = fe.Create(), this._afterCameraPostProcessStage = fe.Create(), this._afterRenderTargetDrawStage = fe.Create(), this._afterRenderTargetPostProcessStage = fe.Create(), this._afterRenderStage = fe.Create(), this._pointerMoveStage = fe.Create(), this._pointerDownStage = fe.Create(), this._pointerUpStage = fe.Create(), this._geometriesByUniqueId = null, this._defaultMeshCandidates = {
      data: [],
      length: 0
    }, this._defaultSubMeshCandidates = {
      data: [],
      length: 0
    }, this._preventFreeActiveMeshesAndRenderingGroups = !1, this._activeMeshesFrozen = !1, this._activeMeshesFrozenButKeepClipping = !1, this._skipEvaluateActiveMeshesCompletely = !1, this._allowPostProcessClearColor = !0, this.getDeterministicFrameTime = () => this._engine.getTimeStep(), this._registeredActions = 0, this._blockMaterialDirtyMechanism = !1, this._perfCollector = null, this.activeCameras = new Array();
    const i = {
      useGeometryUniqueIdsMap: !0,
      useMaterialMeshMap: !0,
      useClonedMeshMap: !0,
      virtual: !1,
      ...t
    };
    this._engine = e || J.LastCreatedEngine, i.virtual ? this._engine._virtualScenes.push(this) : (J._LastCreatedScene = this, this._engine.scenes.push(this)), this._uid = null, this._renderingManager = new Se(this), Gi && (this.postProcessManager = new Gi(this)), Ie() && this.attachControl(), this._createUbo(), ae && (this._imageProcessingConfiguration = new ae()), this.setDefaultCandidateProviders(), i.useGeometryUniqueIdsMap && (this._geometriesByUniqueId = {}), this.useMaterialMeshMap = i.useMaterialMeshMap, this.useClonedMeshMap = i.useClonedMeshMap, (!t || !t.virtual) && this._engine.onNewSceneAddedObservable.notifyObservers(this);
  }
  /**
   * Gets a string identifying the name of the class
   * @returns "Scene" string
   */
  getClassName() {
    return "Scene";
  }
  /**
   * @internal
   */
  _getDefaultMeshCandidates() {
    return this._defaultMeshCandidates.data = this.meshes, this._defaultMeshCandidates.length = this.meshes.length, this._defaultMeshCandidates;
  }
  /**
   * @internal
   */
  _getDefaultSubMeshCandidates(e) {
    return this._defaultSubMeshCandidates.data = e.subMeshes, this._defaultSubMeshCandidates.length = e.subMeshes.length, 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.bind(this), this.getActiveSubMeshCandidates = this._getDefaultSubMeshCandidates.bind(this), this.getIntersectingSubMeshCandidates = this._getDefaultSubMeshCandidates.bind(this), this.getCollidingSubMeshCandidates = this._getDefaultSubMeshCandidates.bind(this);
  }
  /**
   * 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(e) {
    this._inputManager.pointerX = e;
  }
  /**
   * Gets or sets the current on-screen Y position of the pointer
   */
  get pointerY() {
    return this._inputManager.pointerY;
  }
  set pointerY(e) {
    this._inputManager.pointerY = e;
  }
  /**
   * 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(e, t, i = 1) {
    return this._cachedEffect !== t || this._cachedMaterial !== e || this._cachedVisibility !== i;
  }
  /**
   * 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(e, t) {
    return this._inputManager.simulatePointerMove(e, t), 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(e, t) {
    return this._inputManager.simulatePointerDown(e, t), 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(e, t, i) {
    return this._inputManager.simulatePointerUp(e, t, i), 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(e = 0) {
    return this._inputManager.isPointerCaptured(e);
  }
  /**
   * 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(e = !0, t = !0, i = !0) {
    this._inputManager.attachControl(e, t, i);
  }
  /** 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(e = !0) {
    if (this._isDisposed)
      return !1;
    let t;
    const i = this.getEngine();
    let s = !0;
    for (this._pendingData.length > 0 && (s = !1), e && (this._processedMaterials.reset(), this._materialsRenderTargets.reset()), t = 0; t < this.meshes.length; t++) {
      const r = this.meshes[t];
      if (!r.subMeshes || r.subMeshes.length === 0)
        continue;
      if (!r.isReady(!0)) {
        s = !1;
        continue;
      }
      const n = r.hasThinInstances || r.getClassName() === "InstancedMesh" || r.getClassName() === "InstancedLinesMesh" || i.getCaps().instancedArrays && r.instances.length > 0;
      for (const o of this._isReadyForMeshStage)
        o.action(r, n) || (s = !1);
      if (!e)
        continue;
      const a = r.material || this.defaultMaterial;
      if (a)
        if (a._storeEffectOnSubMeshes)
          for (const o of r.subMeshes) {
            const h = o.getMaterial();
            h && h.hasRenderTargetTextures && h.getRenderTargetTextures != null && this._processedMaterials.indexOf(h) === -1 && (this._processedMaterials.push(h), this._materialsRenderTargets.concatWithNoDuplicate(h.getRenderTargetTextures()));
          }
        else
          a.hasRenderTargetTextures && a.getRenderTargetTextures != null && this._processedMaterials.indexOf(a) === -1 && (this._processedMaterials.push(a), this._materialsRenderTargets.concatWithNoDuplicate(a.getRenderTargetTextures()));
    }
    if (!s || !i.areAllEffectsReady())
      return !1;
    if (e) {
      for (t = 0; t < this._materialsRenderTargets.length; ++t)
        if (!this._materialsRenderTargets.data[t].isReadyForRendering())
          return !1;
    }
    for (t = 0; t < this.geometries.length; t++)
      if (this.geometries[t].delayLoadState === 2)
        return !1;
    if (this.activeCameras && this.activeCameras.length > 0) {
      for (const r of this.activeCameras)
        if (!r.isReady(!0))
          return !1;
    } else if (this.activeCamera && !this.activeCamera.isReady(!0))
      return !1;
    for (const r of this.particleSystems)
      if (!r.isReady())
        return !1;
    return !0;
  }
  /** 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(e) {
    this.onBeforeRenderObservable.add(e);
  }
  /**
   * Unregisters a function called before every frame render
   * @param func defines the function to unregister
   */
  unregisterBeforeRender(e) {
    this.onBeforeRenderObservable.removeCallback(e);
  }
  /**
   * Registers a function to be called after every frame render
   * @param func defines the function to register
   */
  registerAfterRender(e) {
    this.onAfterRenderObservable.add(e);
  }
  /**
   * Unregisters a function called after every frame render
   * @param func defines the function to unregister
   */
  unregisterAfterRender(e) {
    this.onAfterRenderObservable.removeCallback(e);
  }
  _executeOnceBeforeRender(e) {
    const t = () => {
      e(), setTimeout(() => {
        this.unregisterBeforeRender(t);
      });
    };
    this.registerBeforeRender(t);
  }
  /**
   * 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(e, t) {
    t !== void 0 ? setTimeout(() => {
      this._executeOnceBeforeRender(e);
    }, t) : this._executeOnceBeforeRender(e);
  }
  /**
   * 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(e) {
    this._pendingData.push(e);
  }
  /**
   * 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(e) {
    const t = this.isLoading, i = this._pendingData.indexOf(e);
    i !== -1 && this._pendingData.splice(i, 1), t && !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(e, t = !1) {
    this.onReadyObservable.addOnce(e), this._executeWhenReadyTimeoutId === null && this._checkIsReady(t);
  }
  /**
   * 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
   */
  whenReadyAsync(e = !1) {
    return new Promise((t) => {
      this.executeWhenReady(() => {
        t();
      }, e);
    });
  }
  /**
   * @internal
   */
  _checkIsReady(e = !1) {
    if (this._registerTransientComponents(), this.isReady(e)) {
      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(e);
    }, 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 = Et.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(e, t, i, s) {
    !i && !s && this._multiviewSceneUbo && (this._multiviewSceneUbo.dispose(), this._multiviewSceneUbo = null), !(this._viewUpdateFlag === e.updateFlag && this._projectionUpdateFlag === t.updateFlag) && (this._viewUpdateFlag = e.updateFlag, this._projectionUpdateFlag = t.updateFlag, this._viewMatrix = e, this._projectionMatrix = t, this._viewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix), this._frustumPlanes ? Xe.GetPlanesToRef(this._transformMatrix, this._frustumPlanes) : this._frustumPlanes = Xe.GetPlanes(this._transformMatrix), this._multiviewSceneUbo && this._multiviewSceneUbo.useUbo ? this._updateMultiviewUbo(i, s) : 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)
   * @returns a new ubo
   */
  createSceneUniformBuffer(e) {
    const t = new O(this._engine, void 0, !1, e ?? "scene");
    return t.addUniform("viewProjection", 16), t.addUniform("view", 16), t.addUniform("projection", 16), t.addUniform("vEyePosition", 4), t;
  }
  /**
   * Sets the scene ubo
   * @param ubo the ubo to set for the scene
   */
  setSceneUniformBuffer(e) {
    this._sceneUbo = e, this._viewUpdateFlag = -1, this._projectionUpdateFlag = -1;
  }
  /**
   * Gets an unique (relatively to the current scene) Id
   * @returns an unique number for the scene
   */
  getUniqueId() {
    return fs.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(e, t = !1) {
    this._blockEntityCollection || (this.meshes.push(e), e._resyncLightSources(), e.parent || e._addToSceneRootNodes(), this.onNewMeshAddedObservable.notifyObservers(e), t && e.getChildMeshes().forEach((i) => {
      this.addMesh(i);
    }));
  }
  /**
   * 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(e, t = !1) {
    const i = this.meshes.indexOf(e);
    return i !== -1 && (this.meshes[i] = this.meshes[this.meshes.length - 1], this.meshes.pop(), e.parent || e._removeFromSceneRootNodes()), this._inputManager._invalidateMesh(e), this.onMeshRemovedObservable.notifyObservers(e), t && e.getChildMeshes().forEach((s) => {
      this.removeMesh(s);
    }), i;
  }
  /**
   * Add a transform node to the list of scene's transform nodes
   * @param newTransformNode defines the transform node to add
   */
  addTransformNode(e) {
    this._blockEntityCollection || e.getScene() === this && e._indexInSceneTransformNodesArray !== -1 || (e._indexInSceneTransformNodesArray = this.transformNodes.length, this.transformNodes.push(e), e.parent || e._addToSceneRootNodes(), this.onNewTransformNodeAddedObservable.notifyObservers(e));
  }
  /**
   * 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(e) {
    const t = e._indexInSceneTransformNodesArray;
    if (t !== -1) {
      if (t !== this.transformNodes.length - 1) {
        const i = this.transformNodes[this.transformNodes.length - 1];
        this.transformNodes[t] = i, i._indexInSceneTransformNodesArray = t;
      }
      e._indexInSceneTransformNodesArray = -1, this.transformNodes.pop(), e.parent || e._removeFromSceneRootNodes();
    }
    return this.onTransformNodeRemovedObservable.notifyObservers(e), t;
  }
  /**
   * 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(e) {
    const t = this.skeletons.indexOf(e);
    return t !== -1 && (this.skeletons.splice(t, 1), this.onSkeletonRemovedObservable.notifyObservers(e), this._executeActiveContainerCleanup(this._activeSkeletons)), t;
  }
  /**
   * 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(e) {
    const t = this.morphTargetManagers.indexOf(e);
    return t !== -1 && this.morphTargetManagers.splice(t, 1), t;
  }
  /**
   * 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(e) {
    const t = this.lights.indexOf(e);
    if (t !== -1) {
      for (const i of this.meshes)
        i._removeLightSource(e, !1);
      this.lights.splice(t, 1), this.sortLightsByPriority(), e.parent || e._removeFromSceneRootNodes();
    }
    return this.onLightRemovedObservable.notifyObservers(e), t;
  }
  /**
   * 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(e) {
    const t = this.cameras.indexOf(e);
    if (t !== -1 && (this.cameras.splice(t, 1), e.parent || e._removeFromSceneRootNodes()), this.activeCameras) {
      const i = this.activeCameras.indexOf(e);
      i !== -1 && this.activeCameras.splice(i, 1);
    }
    return this.activeCamera === e && (this.cameras.length > 0 ? this.activeCamera = this.cameras[0] : this.activeCamera = null), this.onCameraRemovedObservable.notifyObservers(e), t;
  }
  /**
   * 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(e) {
    const t = this.particleSystems.indexOf(e);
    return t !== -1 && (this.particleSystems.splice(t, 1), this._executeActiveContainerCleanup(this._activeParticleSystems)), t;
  }
  /**
   * 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(e) {
    const t = this.animations.indexOf(e);
    return t !== -1 && this.animations.splice(t, 1), t;
  }
  /**
   * 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(e, t, i) {
  }
  /**
   * Removes the given animation group from this scene.
   * @param toRemove The animation group to remove
   * @returns The index of the removed animation group
   */
  removeAnimationGroup(e) {
    const t = this.animationGroups.indexOf(e);
    return t !== -1 && this.animationGroups.splice(t, 1), t;
  }
  /**
   * Removes the given multi-material from this scene.
   * @param toRemove The multi-material to remove
   * @returns The index of the removed multi-material
   */
  removeMultiMaterial(e) {
    const t = this.multiMaterials.indexOf(e);
    return t !== -1 && this.multiMaterials.splice(t, 1), this.onMultiMaterialRemovedObservable.notifyObservers(e), t;
  }
  /**
   * Removes the given material from this scene.
   * @param toRemove The material to remove
   * @returns The index of the removed material
   */
  removeMaterial(e) {
    const t = e._indexInSceneMaterialArray;
    if (t !== -1 && t < this.materials.length) {
      if (t !== this.materials.length - 1) {
        const i = this.materials[this.materials.length - 1];
        this.materials[t] = i, i._indexInSceneMaterialArray = t;
      }
      e._indexInSceneMaterialArray = -1, this.materials.pop();
    }
    return this.onMaterialRemovedObservable.notifyObservers(e), t;
  }
  /**
   * 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(e) {
    const t = this.actionManagers.indexOf(e);
    return t !== -1 && this.actionManagers.splice(t, 1), t;
  }
  /**
   * Removes the given texture from this scene.
   * @param toRemove The texture to remove
   * @returns The index of the removed texture
   */
  removeTexture(e) {
    const t = this.textures.indexOf(e);
    return t !== -1 && this.textures.splice(t, 1), this.onTextureRemovedObservable.notifyObservers(e), t;
  }
  /**
   * Adds the given light to this scene
   * @param newLight The light to add
   */
  addLight(e) {
    if (!this._blockEntityCollection) {
      this.lights.push(e), this.sortLightsByPriority(), e.parent || e._addToSceneRootNodes();
      for (const t of this.meshes)
        t.lightSources.indexOf(e) === -1 && (t.lightSources.push(e), t._resyncLightSources());
      this.onNewLightAddedObservable.notifyObservers(e);
    }
  }
  /**
   * Sorts the list list based on light priorities
   */
  sortLightsByPriority() {
    this.requireLightSorting && this.lights.sort(me.CompareLightsPriority);
  }
  /**
   * Adds the given camera to this scene
   * @param newCamera The camera to add
   */
  addCamera(e) {
    this._blockEntityCollection || (this.cameras.push(e), this.onNewCameraAddedObservable.notifyObservers(e), e.parent || e._addToSceneRootNodes());
  }
  /**
   * Adds the given skeleton to this scene
   * @param newSkeleton The skeleton to add
   */
  addSkeleton(e) {
    this._blockEntityCollection || (this.skeletons.push(e), this.onNewSkeletonAddedObservable.notifyObservers(e));
  }
  /**
   * Adds the given particle system to this scene
   * @param newParticleSystem The particle system to add
   */
  addParticleSystem(e) {
    this._blockEntityCollection || this.particleSystems.push(e);
  }
  /**
   * Adds the given animation to this scene
   * @param newAnimation The animation to add
   */
  addAnimation(e) {
    this._blockEntityCollection || this.animations.push(e);
  }
  /**
   * Adds the given animation group to this scene.
   * @param newAnimationGroup The animation group to add
   */
  addAnimationGroup(e) {
    this._blockEntityCollection || this.animationGroups.push(e);
  }
  /**
   * Adds the given multi-material to this scene
   * @param newMultiMaterial The multi-material to add
   */
  addMultiMaterial(e) {
    this._blockEntityCollection || (this.multiMaterials.push(e), this.onNewMultiMaterialAddedObservable.notifyObservers(e));
  }
  /**
   * Adds the given material to this scene
   * @param newMaterial The material to add
   */
  addMaterial(e) {
    this._blockEntityCollection || e.getScene() === this && e._indexInSceneMaterialArray !== -1 || (e._indexInSceneMaterialArray = this.materials.length, this.materials.push(e), this.onNewMaterialAddedObservable.notifyObservers(e));
  }
  /**
   * Adds the given morph target to this scene
   * @param newMorphTargetManager The morph target to add
   */
  addMorphTargetManager(e) {
    this._blockEntityCollection || this.morphTargetManagers.push(e);
  }
  /**
   * Adds the given geometry to this scene
   * @param newGeometry The geometry to add
   */
  addGeometry(e) {
    this._blockEntityCollection || (this._geometriesByUniqueId && (this._geometriesByUniqueId[e.uniqueId] = this.geometries.length), this.geometries.push(e));
  }
  /**
   * Adds the given action manager to this scene
   * @deprecated
   * @param newActionManager The action manager to add
   */
  addActionManager(e) {
    this.actionManagers.push(e);
  }
  /**
   * Adds the given texture to this scene.
   * @param newTexture The texture to add
   */
  addTexture(e) {
    this._blockEntityCollection || (this.textures.push(e), this.onNewTextureAddedObservable.notifyObservers(e));
  }
  /**
   * 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(e, t = !0) {
    this._engine.getInputElement() && (this.activeCamera && this.activeCamera.detachControl(), this.activeCamera = e, t && e.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(e) {
    const t = this.getCameraById(e);
    return t ? (this.activeCamera = t, t) : 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(e) {
    const t = this.getCameraByName(e);
    return t ? (this.activeCamera = t, t) : 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(e) {
    for (let t = 0; t < this.animationGroups.length; t++)
      if (this.animationGroups[t].name === e)
        return this.animationGroups[t];
    return null;
  }
  _getMaterial(e, t) {
    for (let i = 0; i < this.materials.length; i++) {
      const s = this.materials[i];
      if (t(s))
        return s;
    }
    if (e)
      for (let i = 0; i < this.multiMaterials.length; i++) {
        const s = this.multiMaterials[i];
        if (t(s))
          return s;
      }
    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.
   */
  getMaterialByUniqueID(e, t = !1) {
    return this._getMaterial(t, (i) => i.uniqueId === e);
  }
  /**
   * 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(e, t = !1) {
    return this._getMaterial(t, (i) => i.id === e);
  }
  /**
   * 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(e, t = !1) {
    return this._getMaterial(t, (i) => i.name === e);
  }
  /**
   * 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(e, t = !1) {
    for (let i = this.materials.length - 1; i >= 0; i--)
      if (this.materials[i].id === e)
        return this.materials[i];
    if (t) {
      for (let i = this.multiMaterials.length - 1; i >= 0; i--)
        if (this.multiMaterials[i].id === e)
          return this.multiMaterials[i];
    }
    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(e) {
    for (let t = 0; t < this.textures.length; t++)
      if (this.textures[t].uniqueId === e)
        return this.textures[t];
    return null;
  }
  /**
   * Gets a texture using its name
   * @param name defines the texture's name
   * @returns the texture or null if none found.
   */
  getTextureByName(e) {
    for (let t = 0; t < this.textures.length; t++)
      if (this.textures[t].name === e)
        return this.textures[t];
    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(e) {
    for (let t = 0; t < this.cameras.length; t++)
      if (this.cameras[t].id === e)
        return this.cameras[t];
    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(e) {
    for (let t = 0; t < this.cameras.length; t++)
      if (this.cameras[t].uniqueId === e)
        return this.cameras[t];
    return null;
  }
  /**
   * Gets a camera using its name
   * @param name defines the camera's name
   * @returns the camera or null if none found.
   */
  getCameraByName(e) {
    for (let t = 0; t < this.cameras.length; t++)
      if (this.cameras[t].name === e)
        return this.cameras[t];
    return null;
  }
  /**
   * Gets a bone using its Id
   * @param id defines the bone's Id
   * @returns the bone or null if not found
   */
  getBoneById(e) {
    for (let t = 0; t < this.skeletons.length; t++) {
      const i = this.skeletons[t];
      for (let s = 0; s < i.bones.length; s++)
        if (i.bones[s].id === e)
          return i.bones[s];
    }
    return null;
  }
  /**
   * Gets a bone using its id
   * @param name defines the bone's name
   * @returns the bone or null if not found
   */
  getBoneByName(e) {
    for (let t = 0; t < this.skeletons.length; t++) {
      const i = this.skeletons[t];
      for (let s = 0; s < i.bones.length; s++)
        if (i.bones[s].name === e)
          return i.bones[s];
    }
    return null;
  }
  /**
   * Gets a light node using its name
   * @param name defines the the light's name
   * @returns the light or null if none found.
   */
  getLightByName(e) {
    for (let t = 0; t < this.lights.length; t++)
      if (this.lights[t].name === e)
        return this.lights[t];
    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(e) {
    for (let t = 0; t < this.lights.length; t++)
      if (this.lights[t].id === e)
        return this.lights[t];
    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(e) {
    for (let t = 0; t < this.lights.length; t++)
      if (this.lights[t].uniqueId === e)
        return this.lights[t];
    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(e) {
    for (let t = 0; t < this.particleSystems.length; t++)
      if (this.particleSystems[t].id === e)
        return this.particleSystems[t];
    return null;
  }
  /**
   * Gets a geometry using its Id
   * @param id defines the geometry's Id
   * @returns the geometry or null if none found.
   */
  getGeometryById(e) {
    for (let t = 0; t < this.geometries.length; t++)
      if (this.geometries[t].id === e)
        return this.geometries[t];
    return null;
  }
  _getGeometryByUniqueId(e) {
    if (this._geometriesByUniqueId) {
      const t = this._geometriesByUniqueId[e];
      if (t !== void 0)
        return this.geometries[t];
    } else
      for (let t = 0; t < this.geometries.length; t++)
        if (this.geometries[t].uniqueId === e)
          return this.geometries[t];
    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(e, t) {
    return !t && this._getGeometryByUniqueId(e.uniqueId) ? !1 : (this.addGeometry(e), this.onNewGeometryAddedObservable.notifyObservers(e), !0);
  }
  /**
   * 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(e) {
    let t;
    if (this._geometriesByUniqueId) {
      if (t = this._geometriesByUniqueId[e.uniqueId], t === void 0)
        return !1;
    } else if (t = this.geometries.indexOf(e), t < 0)
      return !1;
    if (t !== this.geometries.length - 1) {
      const i = this.geometries[this.geometries.length - 1];
      i && (this.geometries[t] = i, this._geometriesByUniqueId && (this._geometriesByUniqueId[i.uniqueId] = t));
    }
    return this._geometriesByUniqueId && (this._geometriesByUniqueId[e.uniqueId] = void 0), this.geometries.pop(), this.onGeometryRemovedObservable.notifyObservers(e), !0;
  }
  /**
   * 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(e) {
    for (let t = 0; t < this.meshes.length; t++)
      if (this.meshes[t].id === e)
        return this.meshes[t];
    return null;
  }
  /**
   * Gets a list of meshes using their Id
   * @param id defines the Id to search for
   * @returns a list of meshes
   */
  getMeshesById(e) {
    return this.meshes.filter(function(t) {
      return t.id === e;
    });
  }
  /**
   * 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(e) {
    for (let t = 0; t < this.transformNodes.length; t++)
      if (this.transformNodes[t].id === e)
        return this.transformNodes[t];
    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(e) {
    for (let t = 0; t < this.transformNodes.length; t++)
      if (this.transformNodes[t].uniqueId === e)
        return this.transformNodes[t];
    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(e) {
    return this.transformNodes.filter(function(t) {
      return t.id === e;
    });
  }
  /**
   * 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(e) {
    for (let t = 0; t < this.meshes.length; t++)
      if (this.meshes[t].uniqueId === e)
        return this.meshes[t];
    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(e) {
    for (let t = this.meshes.length - 1; t >= 0; t--)
      if (this.meshes[t].id === e)
        return this.meshes[t];
    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(e) {
    let t;
    for (t = this.meshes.length - 1; t >= 0; t--)
      if (this.meshes[t].id === e)
        return this.meshes[t];
    for (t = this.transformNodes.length - 1; t >= 0; t--)
      if (this.transformNodes[t].id === e)
        return this.transformNodes[t];
    for (t = this.cameras.length - 1; t >= 0; t--)
      if (this.cameras[t].id === e)
        return this.cameras[t];
    for (t = this.lights.length - 1; t >= 0; t--)
      if (this.lights[t].id === e)
        return this.lights[t];
    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(e) {
    const t = this.getMeshById(e);
    if (t)
      return t;
    const i = this.getTransformNodeById(e);
    if (i)
      return i;
    const s = this.getLightById(e);
    if (s)
      return s;
    const r = this.getCameraById(e);
    if (r)
      return r;
    const n = this.getBoneById(e);
    return n || 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(e) {
    const t = this.getMeshByName(e);
    if (t)
      return t;
    const i = this.getTransformNodeByName(e);
    if (i)
      return i;
    const s = this.getLightByName(e);
    if (s)
      return s;
    const r = this.getCameraByName(e);
    if (r)
      return r;
    const n = this.getBoneByName(e);
    return n || 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(e) {
    for (let t = 0; t < this.meshes.length; t++)
      if (this.meshes[t].name === e)
        return this.meshes[t];
    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(e) {
    for (let t = 0; t < this.transformNodes.length; t++)
      if (this.transformNodes[t].name === e)
        return this.transformNodes[t];
    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(e) {
    for (let t = this.skeletons.length - 1; t >= 0; t--)
      if (this.skeletons[t].id === e)
        return this.skeletons[t];
    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(e) {
    for (let t = 0; t < this.skeletons.length; t++)
      if (this.skeletons[t].uniqueId === e)
        return this.skeletons[t];
    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(e) {
    for (let t = 0; t < this.skeletons.length; t++)
      if (this.skeletons[t].id === e)
        return this.skeletons[t];
    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(e) {
    for (let t = 0; t < this.skeletons.length; t++)
      if (this.skeletons[t].name === e)
        return this.skeletons[t];
    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(e) {
    for (let t = 0; t < this.morphTargetManagers.length; t++)
      if (this.morphTargetManagers[t].uniqueId === e)
        return this.morphTargetManagers[t];
    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(e) {
    for (let t = 0; t < this.morphTargetManagers.length; ++t) {
      const i = this.morphTargetManagers[t];
      for (let s = 0; s < i.numTargets; ++s) {
        const r = i.getTarget(s);
        if (r.id === e)
          return r;
      }
    }
    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(e) {
    for (let t = 0; t < this.morphTargetManagers.length; ++t) {
      const i = this.morphTargetManagers[t];
      for (let s = 0; s < i.numTargets; ++s) {
        const r = i.getTarget(s);
        if (r.name === e)
          return r;
      }
    }
    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(e) {
    for (let t = 0; t < this.postProcesses.length; ++t) {
      const i = this.postProcesses[t];
      if (i.name === e)
        return i;
    }
    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(e) {
    return this._activeMeshes.indexOf(e) !== -1;
  }
  /**
   * Return a unique id as a string which can serve as an identifier for the scene
   */
  get uid() {
    return this._uid || (this._uid = k.RandomId()), 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(e, t) {
    return this._externalData || (this._externalData = new Vi()), this._externalData.add(e, t);
  }
  /**
   * 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(e) {
    return this._externalData ? this._externalData.get(e) : null;
  }
  /**
   * 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(e, t) {
    return this._externalData || (this._externalData = new Vi()), this._externalData.getOrAddWithFactory(e, t);
  }
  /**
   * 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(e) {
    return this._externalData.remove(e);
  }
  _evaluateSubMesh(e, t, i, s) {
    if (s || e.isInFrustum(this._frustumPlanes)) {
      for (const n of this._evaluateSubMeshStage)
        n.action(t, e);
      const r = e.getMaterial();
      r != null && (r.hasRenderTargetTextures && r.getRenderTargetTextures != null && this._processedMaterials.indexOf(r) === -1 && (this._processedMaterials.push(r), this._materialsRenderTargets.concatWithNoDuplicate(r.getRenderTargetTextures())), this._renderingManager.dispatch(e, t, r));
    }
  }
  /**
   * 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(e) {
    this._preventFreeActiveMeshesAndRenderingGroups !== e && (e && (this.freeActiveMeshes(), this.freeRenderingGroups()), this._preventFreeActiveMeshesAndRenderingGroups = e);
  }
  /**
   * Clear the active meshes smart array preventing retention point in mesh dispose.
   */
  freeActiveMeshes() {
    if (!this.blockfreeActiveMeshesAndRenderingGroups && (this._activeMeshes.dispose(), this.activeCamera && this.activeCamera._activeMeshes && this.activeCamera._activeMeshes.dispose(), this.activeCameras))
      for (let e = 0; e < this.activeCameras.length; e++) {
        const t = this.activeCameras[e];
        t && t._activeMeshes && t._activeMeshes.dispose();
      }
  }
  /**
   * Clear the info related to rendering groups preventing retention points during dispose.
   */
  freeRenderingGroups() {
    if (!this.blockfreeActiveMeshesAndRenderingGroups && (this._renderingManager && this._renderingManager.freeRenderingGroups(), this.textures))
      for (let e = 0; e < this.textures.length; e++) {
        const t = this.textures[e];
        t && t.renderList && t.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(e = !1, t, i, s = !0, r = !1) {
    return this.executeWhenReady(() => {
      if (!this.activeCamera) {
        i && i("No active camera found");
        return;
      }
      if (this._frustumPlanes || this.updateTransformMatrix(), this._evaluateActiveMeshes(), this._activeMeshesFrozen = !0, this._activeMeshesFrozenButKeepClipping = r, this._skipEvaluateActiveMeshesCompletely = e, s)
        for (let n = 0; n < this._activeMeshes.length; n++)
          this._activeMeshes.data[n]._freeze();
      t && t();
    }), this;
  }
  /**
   * Use this function to restart evaluating active meshes on every frame
   * @returns the current scene
   */
  unfreezeActiveMeshes() {
    for (let e = 0; e < this.meshes.length; e++) {
      const t = this.meshes[e];
      t._internalAbstractMeshDataInfo && (t._internalAbstractMeshDataInfo._isActive = !1);
    }
    for (let e = 0; e < this._activeMeshes.length; e++)
      this._activeMeshes.data[e]._unFreeze();
    return this._activeMeshesFrozen = !1, this;
  }
  _executeActiveContainerCleanup(e) {
    !(this._engine.snapshotRendering && this._engine.snapshotRenderingMode === 1) && this._activeMeshesFrozen && this._activeMeshes.length || this.onBeforeRenderObservable.addOnce(() => e.dispose());
  }
  _evaluateActiveMeshes() {
    var e;
    if (this._engine.snapshotRendering && this._engine.snapshotRenderingMode === 1) {
      this._activeMeshes.length > 0 && ((e = this.activeCamera) === null || e === void 0 || e._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 s = this._activeMeshes.length;
        for (let r = 0; r < s; r++)
          this._activeMeshes.data[r].computeWorldMatrix();
      }
      if (this._activeParticleSystems) {
        const s = this._activeParticleSystems.length;
        for (let r = 0; r < s; r++)
          this._activeParticleSystems.data[r].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 s of this._beforeEvaluateActiveMeshStage)
      s.action();
    const t = this.getActiveMeshCandidates(), i = t.length;
    for (let s = 0; s < i; s++) {
      const r = t.data[s];
      if (r._internalAbstractMeshDataInfo._currentLODIsUpToDate = !1, r.isBlocked || (this._totalVertices.addCount(r.getTotalVertices(), !1), !r.isReady() || !r.isEnabled() || r.scaling.hasAZeroComponent))
        continue;
      r.computeWorldMatrix(), r.actionManager && r.actionManager.hasSpecificTriggers2(12, 13) && this._meshesForIntersections.pushNoDuplicate(r);
      let n = this.customLODSelector ? this.customLODSelector(r, this.activeCamera) : r.getLOD(this.activeCamera);
      if (r._internalAbstractMeshDataInfo._currentLOD = n, r._internalAbstractMeshDataInfo._currentLODIsUpToDate = !0, n != null && (n !== r && n.billboardMode !== 0 && n.computeWorldMatrix(), r._preActivate(), r.isVisible && r.visibility > 0 && r.layerMask & this.activeCamera.layerMask && (this._skipFrustumClipping || r.alwaysSelectAsActiveMesh || r.isInFrustum(this._frustumPlanes)))) {
        this._activeMeshes.push(r), this.activeCamera._activeMeshes.push(r), n !== r && n._activate(this._renderId, !1);
        for (const a of this._preActiveMeshStage)
          a.action(r);
        r._activate(this._renderId, !1) && (r.isAnInstance ? r._internalAbstractMeshDataInfo._actAsRegularMesh && (n = r) : n._internalAbstractMeshDataInfo._onlyForInstances = !1, n._internalAbstractMeshDataInfo._isActive = !0, this._activeMesh(r, n)), r._postActivate();
      }
    }
    if (this.particlesEnabled) {
      this.onBeforeParticlesRenderingObservable.notifyObservers(this);
      for (let s = 0; s < this.particleSystems.length; s++) {
        const r = this.particleSystems[s];
        if (!r.isStarted() || !r.emitter)
          continue;
        const n = r.emitter;
        (!n.position || n.isEnabled()) && (this._activeParticleSystems.push(r), r.animate(), this._renderingManager.dispatchParticles(r));
      }
      this.onAfterParticlesRenderingObservable.notifyObservers(this);
    }
  }
  _activeMesh(e, t) {
    this._skeletonsEnabled && t.skeleton !== null && t.skeleton !== void 0 && (this._activeSkeletons.pushNoDuplicate(t.skeleton) && (t.skeleton.prepare(), this._activeBones.addCount(t.skeleton.bones.length, !1)), t.computeBonesUsingShaders || this._softwareSkinnedMeshes.pushNoDuplicate(t));
    let i = e.hasInstances || e.isAnInstance || this.dispatchAllSubMeshesOfActiveMeshes || this._skipFrustumClipping || t.alwaysSelectAsActiveMesh;
    if (t && t.subMeshes && t.subMeshes.length > 0) {
      const s = this.getActiveSubMeshCandidates(t), r = s.length;
      i = i || r === 1;
      for (let n = 0; n < r; n++) {
        const a = s.data[n];
        this._evaluateSubMesh(a, t, e, i);
      }
    }
  }
  /**
   * 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(e) {
    if (this.activeCamera)
      if (this.activeCamera._renderingMultiview) {
        const t = this.activeCamera._rigCameras[0], i = this.activeCamera._rigCameras[1];
        this.setTransformMatrix(t.getViewMatrix(), t.getProjectionMatrix(e), i.getViewMatrix(), i.getProjectionMatrix(e));
      } else
        this.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix(e));
  }
  _bindFrameBuffer(e, t = !0) {
    e && e._multiviewTexture ? e._multiviewTexture._bindFrameBuffer() : e && e.outputRenderTarget ? e.outputRenderTarget._bindFrameBuffer() : this._engine._currentFrameBufferIsDefaultFrameBuffer() || this._engine.restoreDefaultFramebuffer(), t && this._clearFrameBuffer(e);
  }
  _clearFrameBuffer(e) {
    if (!(e && e._multiviewTexture))
      if (e && e.outputRenderTarget && !e._renderingMultiview) {
        const t = e.outputRenderTarget;
        t.onClearObservable.hasObservers() ? t.onClearObservable.notifyObservers(this._engine) : t.skipInitialClear || (this.autoClear && this._engine.clear(t.clearColor || this.clearColor, !t._cleared, !0, !0), t._cleared = !0);
      } else
        this._defaultFrameBufferCleared ? this._engine.clear(null, !1, !0, !0) : (this._defaultFrameBufferCleared = !0, this._clear());
  }
  /**
   * @internal
   */
  _renderForCamera(e, t, i = !0) {
    var s, r, n;
    if (e && e._skipRendering)
      return;
    const a = this._engine;
    if (this._activeCamera = e, !this.activeCamera)
      throw new Error("Active camera not set");
    if (a.setViewport(this.activeCamera.viewport), this.resetCachedMaterial(), this._renderId++, !this.prePass && i) {
      let h = !0;
      e._renderingMultiview && e.outputRenderTarget && (h = e.outputRenderTarget.skipInitialClear, this.autoClear && (this._defaultFrameBufferCleared = !1, e.outputRenderTarget.skipInitialClear = !1)), this._bindFrameBuffer(this._activeCamera), e._renderingMultiview && e.outputRenderTarget && (e.outputRenderTarget.skipInitialClear = h);
    }
    this.updateTransformMatrix(), this.onBeforeCameraRenderObservable.notifyObservers(this.activeCamera), this._evaluateActiveMeshes();
    for (let h = 0; h < this._softwareSkinnedMeshes.length; h++) {
      const c = this._softwareSkinnedMeshes.data[h];
      c.applySkeleton(c.skeleton);
    }
    this.onBeforeRenderTargetsRenderObservable.notifyObservers(this), this._renderTargets.concatWithNoDuplicate(this._materialsRenderTargets), e.customRenderTargets && e.customRenderTargets.length > 0 && this._renderTargets.concatWithNoDuplicate(e.customRenderTargets), t && t.customRenderTargets && t.customRenderTargets.length > 0 && this._renderTargets.concatWithNoDuplicate(t.customRenderTargets), this.environmentTexture && this.environmentTexture.isRenderTarget && this._renderTargets.pushNoDuplicate(this.environmentTexture);
    for (const h of this._gatherActiveCameraRenderTargetsStage)
      h.action(this._renderTargets);
    let o = !1;
    if (this.renderTargetsEnabled) {
      if (this._intermediateRendering = !0, this._renderTargets.length > 0) {
        k.StartPerformanceCounter("Render targets", this._renderTargets.length > 0);
        for (let h = 0; h < this._renderTargets.length; h++) {
          const c = this._renderTargets.data[h];
          if (c._shouldRender()) {
            this._renderId++;
            const u = c.activeCamera && c.activeCamera !== this.activeCamera;
            c.render(u, this.dumpNextRenderTargets), o = !0;
          }
        }
        k.EndPerformanceCounter("Render targets", this._renderTargets.length > 0), this._renderId++;
      }
      for (const h of this._cameraDrawRenderTargetStage)
        o = h.action(this.activeCamera) || o;
      this._intermediateRendering = !1;
    }
    this._engine.currentRenderPassId = (n = (r = (s = e.outputRenderTarget) === null || s === void 0 ? void 0 : s.renderPassId) !== null && r !== void 0 ? r : e.renderPassId) !== null && n !== void 0 ? n : 0, o && !this.prePass && this._bindFrameBuffer(this._activeCamera, !1), this.onAfterRenderTargetsRenderObservable.notifyObservers(this), this.postProcessManager && !e._multiviewTexture && !this.prePass && this.postProcessManager._prepareFrame();
    for (const h of this._beforeCameraDrawStage)
      h.action(this.activeCamera);
    this.onBeforeDrawPhaseObservable.notifyObservers(this), a.snapshotRendering && a.snapshotRenderingMode === 1 && this.finalizeSceneUbo(), this._renderingManager.render(null, null, !0, !0), this.onAfterDrawPhaseObservable.notifyObservers(this);
    for (const h of this._afterCameraDrawStage)
      h.action(this.activeCamera);
    if (this.postProcessManager && !e._multiviewTexture) {
      const h = e.outputRenderTarget ? e.outputRenderTarget.renderTarget : void 0;
      this.postProcessManager._finalizeFrame(e.isIntermediate, h);
    }
    for (const h of this._afterCameraPostProcessStage)
      h.action(this.activeCamera);
    this._renderTargets.reset(), this.onAfterCameraRenderObservable.notifyObservers(this.activeCamera);
  }
  _processSubCameras(e, t = !0) {
    if (e.cameraRigMode === 0 || e._renderingMultiview) {
      e._renderingMultiview && !this._multiviewSceneUbo && this._createMultiviewUbo(), this._renderForCamera(e, void 0, t), this.onAfterRenderCameraObservable.notifyObservers(e);
      return;
    }
    if (e._useMultiviewToSingleView)
      this._renderMultiviewToSingleView(e);
    else {
      this.onBeforeCameraRenderObservable.notifyObservers(e);
      for (let i = 0; i < e._rigCameras.length; i++)
        this._renderForCamera(e._rigCameras[i], e);
    }
    this._activeCamera = e, this.updateTransformMatrix(), this.onAfterRenderCameraObservable.notifyObservers(e);
  }
  _checkIntersections() {
    for (let e = 0; e < this._meshesForIntersections.length; e++) {
      const t = this._meshesForIntersections.data[e];
      if (t.actionManager)
        for (let i = 0; t.actionManager && i < t.actionManager.actions.length; i++) {
          const s = t.actionManager.actions[i];
          if (s.trigger === 12 || s.trigger === 13) {
            const r = s.getTriggerParameter(), n = r.mesh ? r.mesh : r, a = n.intersectsMesh(t, r.usePreciseIntersection), o = t._intersectionsInProgress.indexOf(n);
            a && o === -1 ? s.trigger === 12 ? (s._executeCurrent(Re.CreateNew(t, void 0, n)), t._intersectionsInProgress.push(n)) : s.trigger === 13 && t._intersectionsInProgress.push(n) : !a && o > -1 && (s.trigger === 13 && s._executeCurrent(Re.CreateNew(t, void 0, n)), (!t.actionManager.hasSpecificTrigger(13, (h) => {
              const c = h.mesh ? h.mesh : h;
              return n === c;
            }) || s.trigger === 13) && t._intersectionsInProgress.splice(o, 1));
          }
        }
    }
  }
  /**
   * @internal
   */
  _advancePhysicsEngineStep(e) {
  }
  /** @internal */
  _animate() {
  }
  /** Execute all animations (for a frame) */
  animate() {
    if (this._engine.isDeterministicLockStep()) {
      let e = Math.max(Q.MinDeltaTime, Math.min(this._engine.getDeltaTime(), Q.MaxDeltaTime)) + this._timeAccumulator;
      const t = this._engine.getTimeStep(), i = 1e3 / t / 1e3;
      let s = 0;
      const r = this._engine.getLockstepMaxSteps();
      let n = Math.floor(e / t);
      for (n = Math.min(n, r); e > 0 && s < n; )
        this.onBeforeStepObservable.notifyObservers(this), this._animationRatio = t * i, this._animate(), this.onAfterAnimationsObservable.notifyObservers(this), this.physicsEnabled && this._advancePhysicsEngineStep(t), this.onAfterStepObservable.notifyObservers(this), this._currentStepId++, s++, e -= t;
      this._timeAccumulator = e < 0 ? 0 : e;
    } else {
      const e = this.useConstantAnimationDeltaTime ? 16 : Math.max(Q.MinDeltaTime, Math.min(this._engine.getDeltaTime(), Q.MaxDeltaTime));
      this._animationRatio = e * (60 / 1e3), this._animate(), this.onAfterAnimationsObservable.notifyObservers(this), this.physicsEnabled && this._advancePhysicsEngineStep(e);
    }
  }
  _clear() {
    (this.autoClearDepthAndStencil || this.autoClear) && this._engine.clear(this.clearColor, this.autoClear || this.forceWireframe || this.forcePointsCloud, this.autoClearDepthAndStencil, this.autoClearDepthAndStencil);
  }
  _checkCameraRenderTarget(e) {
    var t;
    if (e != null && e.outputRenderTarget && !(e != null && e.isRigCamera) && (e.outputRenderTarget._cleared = !1), !((t = e == null ? void 0 : e.rigCameras) === null || t === void 0) && t.length)
      for (let i = 0; i < e.rigCameras.length; ++i) {
        const s = e.rigCameras[i].outputRenderTarget;
        s && (s._cleared = !1);
      }
  }
  /**
   * Resets the draw wrappers cache of all meshes
   * @param passId If provided, releases only the draw wrapper corresponding to this render pass id
   */
  resetDrawCache(e) {
    if (this.meshes)
      for (const t of this.meshes)
        t.resetDrawCache(e);
  }
  /**
   * 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(e = !0, t = !1) {
    var i, s, r;
    if (this.isDisposed)
      return;
    this.onReadyObservable.hasObservers() && this._executeWhenReadyTimeoutId === null && this._checkIsReady(), this._frameId++, this._defaultFrameBufferCleared = !1, this._checkCameraRenderTarget(this.activeCamera), !((i = this.activeCameras) === null || i === void 0) && i.length && this.activeCameras.forEach(this._checkCameraRenderTarget), this._registerTransientComponents(), this._activeParticles.fetchNewFrame(), this._totalVertices.fetchNewFrame(), this._activeIndices.fetchNewFrame(), this._activeBones.fetchNewFrame(), this._meshesForIntersections.reset(), this.resetCachedMaterial(), this.onBeforeAnimationsObservable.notifyObservers(this), this.actionManager && this.actionManager.processTrigger(11), t || this.animate();
    for (const o of this._beforeCameraUpdateStage)
      o.action();
    if (e) {
      if (this.activeCameras && this.activeCameras.length > 0)
        for (let o = 0; o < this.activeCameras.length; o++) {
          const h = this.activeCameras[o];
          if (h.update(), h.cameraRigMode !== 0)
            for (let c = 0; c < h._rigCameras.length; c++)
              h._rigCameras[c].update();
        }
      else if (this.activeCamera && (this.activeCamera.update(), this.activeCamera.cameraRigMode !== 0))
        for (let o = 0; o < this.activeCamera._rigCameras.length; o++)
          this.activeCamera._rigCameras[o].update();
    }
    this.onBeforeRenderObservable.notifyObservers(this);
    const n = this.getEngine();
    this.onBeforeRenderTargetsRenderObservable.notifyObservers(this);
    const a = !((s = this.activeCameras) === null || s === void 0) && s.length ? this.activeCameras[0] : this.activeCamera;
    if (this.renderTargetsEnabled) {
      k.StartPerformanceCounter("Custom render targets", this.customRenderTargets.length > 0), this._intermediateRendering = !0;
      for (let o = 0; o < this.customRenderTargets.length; o++) {
        const h = this.customRenderTargets[o];
        if (h._shouldRender()) {
          if (this._renderId++, this.activeCamera = h.activeCamera || this.activeCamera, !this.activeCamera)
            throw new Error("Active camera not set");
          n.setViewport(this.activeCamera.viewport), this.updateTransformMatrix(), h.render(a !== this.activeCamera, this.dumpNextRenderTargets);
        }
      }
      k.EndPerformanceCounter("Custom render targets", this.customRenderTargets.length > 0), this._intermediateRendering = !1, this._renderId++;
    }
    this._engine.currentRenderPassId = (r = a == null ? void 0 : a.renderPassId) !== null && r !== void 0 ? r : 0, this.activeCamera = a, this._activeCamera && this._activeCamera.cameraRigMode !== 22 && !this.prePass && this._bindFrameBuffer(this._activeCamera, !1), this.onAfterRenderTargetsRenderObservable.notifyObservers(this);
    for (const o of this._beforeClearStage)
      o.action();
    this._clearFrameBuffer(this.activeCamera);
    for (const o of this._gatherRenderTargetsStage)
      o.action(this._renderTargets);
    if (this.activeCameras && this.activeCameras.length > 0)
      for (let o = 0; o < this.activeCameras.length; o++)
        this._processSubCameras(this.activeCameras[o], o > 0);
    else {
      if (!this.activeCamera)
        throw new Error("No camera defined");
      this._processSubCameras(this.activeCamera, !!this.activeCamera.outputRenderTarget);
    }
    this._checkIntersections();
    for (const o of this._afterRenderStage)
      o.action();
    if (this.afterRender && this.afterRender(), this.onAfterRenderObservable.notifyObservers(this), this._toBeDisposed.length) {
      for (let o = 0; o < this._toBeDisposed.length; o++) {
        const h = this._toBeDisposed[o];
        h && h.dispose();
      }
      this._toBeDisposed.length = 0;
    }
    this.dumpNextRenderTargets && (this.dumpNextRenderTargets = !1), this._activeBones.addCount(0, !0), this._activeIndices.addCount(0, !0), this._activeParticles.addCount(0, !0), 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 e = 0; e < this.materials.length; e++)
      this.materials[e].freeze();
  }
  /**
   * Unfreeze all materials
   * A frozen material will not be updatable but should be faster to render
   */
  unfreezeMaterials() {
    for (let e = 0; e < this.materials.length; e++)
      this.materials[e].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 = new Array(), this.stopAllAnimations && this.stopAllAnimations(), this.resetCachedMaterial(), 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 e = this._activeRequests.slice();
    for (const r of e)
      r.abort();
    this._activeRequests.length = 0;
    try {
      this.onDisposeObservable.notifyObservers(this);
    } catch (r) {
      console.error("An error occurred while calling onDisposeObservable!", r);
    }
    if (this.detachControl(), this._engine.getInputElement())
      for (let r = 0; r < this.cameras.length; r++)
        this.cameras[r].detachControl();
    this._disposeList(this.animationGroups), this._disposeList(this.lights), this._disposeList(this.meshes, (r) => r.dispose(!0)), this._disposeList(this.transformNodes, (r) => r.dispose(!0));
    const i = this.cameras;
    this._disposeList(i), this._defaultMaterial && this._defaultMaterial.dispose(), this._disposeList(this.multiMaterials), this._disposeList(this.materials), this._disposeList(this.particleSystems), this._disposeList(this.postProcesses), this._disposeList(this.textures), this._disposeList(this.morphTargetManagers), this._sceneUbo.dispose(), this._multiviewSceneUbo && this._multiviewSceneUbo.dispose(), this.postProcessManager.dispose(), this._disposeList(this._components);
    let s = this._engine.scenes.indexOf(this);
    s > -1 && this._engine.scenes.splice(s, 1), J._LastCreatedScene === this && (this._engine.scenes.length > 0 ? J._LastCreatedScene = this._engine.scenes[this._engine.scenes.length - 1] : J._LastCreatedScene = null), s = this._engine._virtualScenes.indexOf(this), s > -1 && this._engine._virtualScenes.splice(s, 1), this._engine.wipeCaches(!0), 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.onPrePointerObservable.clear(), this.onPointerObservable.clear(), this.onPreKeyboardObservable.clear(), this.onKeyboardObservable.clear(), this.onActiveCameraChanged.clear(), this.onScenePerformancePriorityChangedObservable.clear(), this._isDisposed = !0;
  }
  _disposeList(e, t) {
    const i = e.slice(0);
    t = t ?? ((s) => s.dispose());
    for (const s of i)
      t(s);
    e.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 e = 0; e < this.meshes.length; e++) {
      const i = this.meshes[e].geometry;
      i && i.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 e of this.textures)
      e._buffer && (e._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(e) {
    const t = new p(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE), i = new p(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
    return e = e || (() => !0), this.meshes.filter(e).forEach((s) => {
      if (s.computeWorldMatrix(!0), !s.subMeshes || s.subMeshes.length === 0 || s.infiniteDistance)
        return;
      const r = s.getBoundingInfo(), n = r.boundingBox.minimumWorld, a = r.boundingBox.maximumWorld;
      p.CheckExtends(n, t, i), p.CheckExtends(a, t, i);
    }), {
      min: t,
      max: i
    };
  }
  // Picking
  /**
   * 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(e, t, i, s, r = !1) {
    throw Y("Ray");
  }
  /**
   * 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(e, t, i, s, r, n = !1, a = !1) {
    throw Y("Ray");
  }
  /**
   * 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(e, t, i) {
    throw Y("Ray");
  }
  /**
   * 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(e, t, i, s) {
    throw Y("Ray");
  }
  /** @internal */
  get _pickingAvailable() {
    return !1;
  }
  /** 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
   * @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(e, t, i, s, r, n) {
    return new ut();
  }
  /** 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
   * @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(e, t, i, s, r) {
    return new ut();
  }
  /** Use the given ray to pick a mesh in the scene
   * @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
   * @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(e, t, i, s) {
    throw Y("Ray");
  }
  /**
   * Launch a ray to try to pick a mesh in the scene
   * @param x X position on screen
   * @param y 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
   * @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(e, t, i, s, r) {
    throw Y("Ray");
  }
  /**
   * 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. Can be set to null. In this case, a mesh must be enabled, visible and with isPickable set to true
   * @param trianglePredicate defines an optional predicate used to select faces when a mesh intersection is detected
   * @returns an array of PickingInfo
   */
  multiPickWithRay(e, t, i) {
    throw Y("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(e, t, i) {
    this._inputManager.setPointerOverMesh(e, t, i);
  }
  /**
   * 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 e of this.geometries)
      e._rebuild();
    for (const e of this.meshes)
      e._rebuild();
    this.postProcessManager && this.postProcessManager._rebuild();
    for (const e of this._components)
      e.rebuild();
    for (const e of this.particleSystems)
      e.rebuild();
    if (this.spriteManagers)
      for (const e of this.spriteManagers)
        e.rebuild();
  }
  /** @internal */
  _rebuildTextures() {
    for (const e of this.textures)
      e._rebuild();
    this.markAllMaterialsAsDirty(1);
  }
  // Tags
  _getByTags(e, t, i) {
    if (t === void 0)
      return e;
    const s = [];
    i = i || ((r) => {
    });
    for (const r in e) {
      const n = e[r];
      re && re.MatchesQuery(n, t) && (s.push(n), i(n));
    }
    return s;
  }
  /**
   * Get a list of meshes by tags
   * @param tagsQuery defines the tags query to use
   * @param forEach defines a predicate used to filter results
   * @returns an array of Mesh
   */
  getMeshesByTags(e, t) {
    return this._getByTags(this.meshes, e, t);
  }
  /**
   * Get a list of cameras by tags
   * @param tagsQuery defines the tags query to use
   * @param forEach defines a predicate used to filter results
   * @returns an array of Camera
   */
  getCamerasByTags(e, t) {
    return this._getByTags(this.cameras, e, t);
  }
  /**
   * Get a list of lights by tags
   * @param tagsQuery defines the tags query to use
   * @param forEach defines a predicate used to filter results
   * @returns an array of Light
   */
  getLightsByTags(e, t) {
    return this._getByTags(this.lights, e, t);
  }
  /**
   * Get a list of materials by tags
   * @param tagsQuery defines the tags query to use
   * @param forEach defines a predicate used to filter results
   * @returns an array of Material
   */
  getMaterialByTags(e, t) {
    return this._getByTags(this.materials, e, t).concat(this._getByTags(this.multiMaterials, e, t));
  }
  /**
   * Get a list of transform nodes by tags
   * @param tagsQuery defines the tags query to use
   * @param forEach defines a predicate used to filter results
   * @returns an array of TransformNode
   */
  getTransformNodesByTags(e, t) {
    return this._getByTags(this.transformNodes, e, t);
  }
  /**
   * 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(e, t = null, i = null, s = null) {
    this._renderingManager.setRenderingOrder(e, t, i, s);
  }
  /**
   * 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(e, t, i = !0, s = !0) {
    this._renderingManager.setRenderingAutoClearDepthStencil(e, t, i, s);
  }
  /**
   * 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(e) {
    return this._renderingManager.getAutoClearDepthStencilSetup(e);
  }
  /** 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(e) {
    this._blockMaterialDirtyMechanism !== e && (this._blockMaterialDirtyMechanism = e, e || this.markAllMaterialsAsDirty(63));
  }
  /**
   * 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(e, t) {
    if (!this._blockMaterialDirtyMechanism)
      for (const i of this.materials)
        t && !t(i) || i.markAsDirty(e);
  }
  /**
   * @internal
   */
  _loadFile(e, t, i, s, r, n, a) {
    const o = bt(e, t, i, s ? this.offlineProvider : void 0, r, n, a);
    return this._activeRequests.push(o), o.onCompleteObservable.add((h) => {
      this._activeRequests.splice(this._activeRequests.indexOf(h), 1);
    }), o;
  }
  /**
   * @internal
   */
  _loadFileAsync(e, t, i, s, r) {
    return new Promise((n, a) => {
      this._loadFile(e, (o) => {
        n(o);
      }, t, i, s, (o, h) => {
        a(h);
      }, r);
    });
  }
  /**
   * @internal
   */
  _requestFile(e, t, i, s, r, n, a) {
    const o = wi(e, t, i, s ? this.offlineProvider : void 0, r, n, a);
    return this._activeRequests.push(o), o.onCompleteObservable.add((h) => {
      this._activeRequests.splice(this._activeRequests.indexOf(h), 1);
    }), o;
  }
  /**
   * @internal
   */
  _requestFileAsync(e, t, i, s, r) {
    return new Promise((n, a) => {
      this._requestFile(e, (o) => {
        n(o);
      }, t, i, s, (o) => {
        a(o);
      }, r);
    });
  }
  /**
   * @internal
   */
  _readFile(e, t, i, s, r) {
    const n = zt(e, t, i, s, r);
    return this._activeRequests.push(n), n.onCompleteObservable.add((a) => {
      this._activeRequests.splice(this._activeRequests.indexOf(a), 1);
    }), n;
  }
  /**
   * @internal
   */
  _readFileAsync(e, t, i) {
    return new Promise((s, r) => {
      this._readFile(e, (n) => {
        s(n);
      }, t, i, (n) => {
        r(n);
      });
    });
  }
  /**
   * 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 Y("performanceViewerSceneExtension");
  }
}
Q.FOGMODE_NONE = 0;
Q.FOGMODE_EXP = 1;
Q.FOGMODE_EXP2 = 2;
Q.FOGMODE_LINEAR = 3;
Q.MinDeltaTime = 1;
Q.MaxDeltaTime = 1e3;
Q.prototype.setActiveCameraByID = function(l) {
  return this.setActiveCameraById(l);
};
Q.prototype.getLastMaterialByID = function(l) {
  return this.getLastMaterialById(l);
};
Q.prototype.getMaterialByID = function(l) {
  return this.getMaterialById(l);
};
Q.prototype.getTextureByUniqueID = function(l) {
  return this.getTextureByUniqueId(l);
};
Q.prototype.getCameraByID = function(l) {
  return this.getCameraById(l);
};
Q.prototype.getCameraByUniqueID = function(l) {
  return this.getCameraByUniqueId(l);
};
Q.prototype.getBoneByID = function(l) {
  return this.getBoneById(l);
};
Q.prototype.getLightByID = function(l) {
  return this.getLightById(l);
};
Q.prototype.getLightByUniqueID = function(l) {
  return this.getLightByUniqueId(l);
};
Q.prototype.getParticleSystemByID = function(l) {
  return this.getParticleSystemById(l);
};
Q.prototype.getGeometryByID = function(l) {
  return this.getGeometryById(l);
};
Q.prototype.getMeshByID = function(l) {
  return this.getMeshById(l);
};
Q.prototype.getMeshesByID = function(l) {
  return this.getMeshesById(l);
};
Q.prototype.getTransformNodeByID = function(l) {
  return this.getTransformNodeById(l);
};
Q.prototype.getTransformNodeByUniqueID = function(l) {
  return this.getTransformNodeByUniqueId(l);
};
Q.prototype.getTransformNodesByID = function(l) {
  return this.getTransformNodesById(l);
};
Q.prototype.getMeshByUniqueID = function(l) {
  return this.getMeshByUniqueId(l);
};
Q.prototype.getLastMeshByID = function(l) {
  return this.getLastMeshById(l);
};
Q.prototype.getLastEntryByID = function(l) {
  return this.getLastEntryById(l);
};
Q.prototype.getNodeByID = function(l) {
  return this.getNodeById(l);
};
Q.prototype.getLastSkeletonByID = function(l) {
  return this.getLastSkeletonById(l);
};
class ur {
  /**
   * constructor
   * @param frameSampleSize The number of samples required to saturate the sliding window
   */
  constructor(e = 30) {
    this._enabled = !0, this._rollingFrameTime = new dr(e);
  }
  /**
   * Samples current frame
   * @param timeMs A timestamp in milliseconds of the current frame to compare with other frames
   */
  sampleFrame(e = Et.Now) {
    if (this._enabled) {
      if (this._lastFrameTimeMs != null) {
        const t = e - this._lastFrameTimeMs;
        this._rollingFrameTime.add(t);
      }
      this._lastFrameTimeMs = e;
    }
  }
  /**
   * 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 e = this._rollingFrameTime.history(0);
    return e === 0 ? 0 : 1e3 / e;
  }
  /**
   * 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 = !0;
  }
  /**
   * Disables contributions to the sliding window sample set
   * Samples will not be interpolated over the disabled period
   */
  disable() {
    this._enabled = !1, this._lastFrameTimeMs = null;
  }
  /**
   * Returns true if sampling is enabled
   */
  get isEnabled() {
    return this._enabled;
  }
  /**
   * Resets performance monitor
   */
  reset() {
    this._lastFrameTimeMs = null, this._rollingFrameTime.reset();
  }
}
class dr {
  /**
   * constructor
   * @param length The number of samples required to saturate the sliding window
   */
  constructor(e) {
    this._samples = new Array(e), this.reset();
  }
  /**
   * Adds a sample to the sample set
   * @param v The sample value
   */
  add(e) {
    let t;
    if (this.isSaturated()) {
      const i = this._samples[this._pos];
      t = i - this.average, this.average -= t / (this._sampleCount - 1), this._m2 -= t * (i - this.average);
    } else
      this._sampleCount++;
    t = e - this.average, this.average += t / this._sampleCount, this._m2 += t * (e - this.average), this.variance = this._m2 / (this._sampleCount - 1), this._samples[this._pos] = e, 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(e) {
    if (e >= this._sampleCount || e >= this._samples.length)
      return 0;
    const t = this._wrapPosition(this._pos - 1);
    return this._samples[this._wrapPosition(t - e)];
  }
  /**
   * 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(e) {
    const t = this._samples.length;
    return (e % t + t) % t;
  }
}
se.prototype.setAlphaConstants = function(l, e, t, i) {
  this._alphaState.setAlphaBlendConstants(l, e, t, i);
};
se.prototype.setAlphaMode = function(l, e = !1) {
  if (this._alphaMode === l) {
    if (!e) {
      const t = l === 0;
      this.depthCullingState.depthMask !== t && (this.depthCullingState.depthMask = t);
    }
    return;
  }
  switch (l) {
    case 0:
      this._alphaState.alphaBlend = !1;
      break;
    case 7:
      this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA, this._gl.ONE, this._gl.ONE), this._alphaState.alphaBlend = !0;
      break;
    case 8:
      this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA, this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA), this._alphaState.alphaBlend = !0;
      break;
    case 2:
      this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE_MINUS_SRC_ALPHA, this._gl.ONE, this._gl.ONE), this._alphaState.alphaBlend = !0;
      break;
    case 6:
      this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE, this._gl.ZERO, this._gl.ONE), this._alphaState.alphaBlend = !0;
      break;
    case 1:
      this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE, this._gl.ZERO, this._gl.ONE), this._alphaState.alphaBlend = !0;
      break;
    case 3:
      this._alphaState.setAlphaBlendFunctionParameters(this._gl.ZERO, this._gl.ONE_MINUS_SRC_COLOR, this._gl.ONE, this._gl.ONE), this._alphaState.alphaBlend = !0;
      break;
    case 4:
      this._alphaState.setAlphaBlendFunctionParameters(this._gl.DST_COLOR, this._gl.ZERO, this._gl.ONE, this._gl.ONE), this._alphaState.alphaBlend = !0;
      break;
    case 5:
      this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE_MINUS_SRC_COLOR, this._gl.ONE, this._gl.ONE), this._alphaState.alphaBlend = !0;
      break;
    case 9:
      this._alphaState.setAlphaBlendFunctionParameters(this._gl.CONSTANT_COLOR, this._gl.ONE_MINUS_CONSTANT_COLOR, this._gl.CONSTANT_ALPHA, this._gl.ONE_MINUS_CONSTANT_ALPHA), this._alphaState.alphaBlend = !0;
      break;
    case 10:
      this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE_MINUS_SRC_COLOR, this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA), this._alphaState.alphaBlend = !0;
      break;
    case 11:
      this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE, this._gl.ONE, this._gl.ONE), this._alphaState.alphaBlend = !0;
      break;
    case 12:
      this._alphaState.setAlphaBlendFunctionParameters(this._gl.DST_ALPHA, this._gl.ONE, this._gl.ZERO, this._gl.ZERO), this._alphaState.alphaBlend = !0;
      break;
    case 13:
      this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE_MINUS_DST_COLOR, this._gl.ONE_MINUS_SRC_COLOR, this._gl.ONE_MINUS_DST_ALPHA, this._gl.ONE_MINUS_SRC_ALPHA), this._alphaState.alphaBlend = !0;
      break;
    case 14:
      this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA, this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA), this._alphaState.alphaBlend = !0;
      break;
    case 15:
      this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE, this._gl.ONE, this._gl.ZERO), this._alphaState.alphaBlend = !0;
      break;
    case 16:
      this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE_MINUS_DST_COLOR, this._gl.ONE_MINUS_SRC_COLOR, this._gl.ZERO, this._gl.ONE), this._alphaState.alphaBlend = !0;
      break;
    case 17:
      this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE_MINUS_SRC_ALPHA, this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA), this._alphaState.alphaBlend = !0;
      break;
  }
  e || (this.depthCullingState.depthMask = l === 0), this._alphaMode = l;
};
se.prototype.getAlphaMode = function() {
  return this._alphaMode;
};
se.prototype.setAlphaEquation = function(l) {
  if (this._alphaEquation !== l) {
    switch (l) {
      case 0:
        this._alphaState.setAlphaEquationParameters(32774, 32774);
        break;
      case 1:
        this._alphaState.setAlphaEquationParameters(32778, 32778);
        break;
      case 2:
        this._alphaState.setAlphaEquationParameters(32779, 32779);
        break;
      case 3:
        this._alphaState.setAlphaEquationParameters(32776, 32776);
        break;
      case 4:
        this._alphaState.setAlphaEquationParameters(32775, 32775);
        break;
      case 5:
        this._alphaState.setAlphaEquationParameters(32775, 32774);
        break;
    }
    this._alphaEquation = l;
  }
};
se.prototype.getAlphaEquation = function() {
  return this._alphaEquation;
};
function fr(l, e, t = !1, i) {
  switch (l) {
    case 3: {
      const r = e instanceof ArrayBuffer ? new Int8Array(e) : new Int8Array(e);
      return i && r.set(new Int8Array(i)), r;
    }
    case 0: {
      const r = e instanceof ArrayBuffer ? new Uint8Array(e) : new Uint8Array(e);
      return i && r.set(new Uint8Array(i)), r;
    }
    case 4: {
      const r = e instanceof ArrayBuffer ? new Int16Array(e) : new Int16Array(t ? e / 2 : e);
      return i && r.set(new Int16Array(i)), r;
    }
    case 5:
    case 8:
    case 9:
    case 10:
    case 2: {
      const r = e instanceof ArrayBuffer ? new Uint16Array(e) : new Uint16Array(t ? e / 2 : e);
      return i && r.set(new Uint16Array(i)), r;
    }
    case 6: {
      const r = e instanceof ArrayBuffer ? new Int32Array(e) : new Int32Array(t ? e / 4 : e);
      return i && r.set(new Int32Array(i)), r;
    }
    case 7:
    case 11:
    case 12:
    case 13:
    case 14:
    case 15: {
      const r = e instanceof ArrayBuffer ? new Uint32Array(e) : new Uint32Array(t ? e / 4 : e);
      return i && r.set(new Uint32Array(i)), r;
    }
    case 1: {
      const r = e instanceof ArrayBuffer ? new Float32Array(e) : new Float32Array(t ? e / 4 : e);
      return i && r.set(new Float32Array(i)), r;
    }
  }
  const s = e instanceof ArrayBuffer ? new Uint8Array(e) : new Uint8Array(e);
  return i && s.set(new Uint8Array(i)), s;
}
se.prototype._readTexturePixelsSync = function(l, e, t, i = -1, s = 0, r = null, n = !0, a = !1, o = 0, h = 0) {
  var c, u;
  const d = this._gl;
  if (!d)
    throw new Error("Engine does not have gl rendering context.");
  if (!this._dummyFramebuffer) {
    const f = d.createFramebuffer();
    if (!f)
      throw new Error("Unable to create dummy framebuffer");
    this._dummyFramebuffer = f;
  }
  d.bindFramebuffer(d.FRAMEBUFFER, this._dummyFramebuffer), i > -1 ? d.framebufferTexture2D(d.FRAMEBUFFER, d.COLOR_ATTACHMENT0, d.TEXTURE_CUBE_MAP_POSITIVE_X + i, (c = l._hardwareTexture) === null || c === void 0 ? void 0 : c.underlyingResource, s) : d.framebufferTexture2D(d.FRAMEBUFFER, d.COLOR_ATTACHMENT0, d.TEXTURE_2D, (u = l._hardwareTexture) === null || u === void 0 ? void 0 : u.underlyingResource, s);
  let g = l.type !== void 0 ? this._getWebGLTextureType(l.type) : d.UNSIGNED_BYTE;
  if (a)
    r || (r = fr(l.type, 4 * e * t));
  else
    switch (g) {
      case d.UNSIGNED_BYTE:
        r || (r = new Uint8Array(4 * e * t)), g = d.UNSIGNED_BYTE;
        break;
      default:
        r || (r = new Float32Array(4 * e * t)), g = d.FLOAT;
        break;
    }
  return n && this.flushFramebuffer(), d.readPixels(o, h, e, t, d.RGBA, g, r), d.bindFramebuffer(d.FRAMEBUFFER, this._currentFramebuffer), r;
};
se.prototype._readTexturePixels = function(l, e, t, i = -1, s = 0, r = null, n = !0, a = !1, o = 0, h = 0) {
  return Promise.resolve(this._readTexturePixelsSync(l, e, t, i, s, r, n, a, o, h));
};
se.prototype.updateDynamicIndexBuffer = function(l, e, t = 0) {
  this._currentBoundBuffer[this._gl.ELEMENT_ARRAY_BUFFER] = null, this.bindIndexBuffer(l);
  let i;
  l.is32Bits ? i = e instanceof Uint32Array ? e : new Uint32Array(e) : i = e instanceof Uint16Array ? e : new Uint16Array(e), this._gl.bufferData(this._gl.ELEMENT_ARRAY_BUFFER, i, this._gl.DYNAMIC_DRAW), this._resetIndexBufferBinding();
};
se.prototype.updateDynamicVertexBuffer = function(l, e, t, i) {
  this.bindArrayBuffer(l), t === void 0 && (t = 0);
  const s = e.byteLength || e.length;
  i === void 0 || i >= s && t === 0 ? e instanceof Array ? this._gl.bufferSubData(this._gl.ARRAY_BUFFER, t, new Float32Array(e)) : this._gl.bufferSubData(this._gl.ARRAY_BUFFER, t, e) : e instanceof Array ? this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, new Float32Array(e).subarray(t, t + i)) : (e instanceof ArrayBuffer ? e = new Uint8Array(e, t, i) : e = new Uint8Array(e.buffer, e.byteOffset + t, i), this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, e)), this._resetVertexBufferBinding();
};
class P extends se {
  /**
   * Returns the current npm package of the sdk
   */
  // Not mixed with Version for tooling purpose.
  static get NpmPackage() {
    return se.NpmPackage;
  }
  /**
   * Returns the current version of the framework
   */
  static get Version() {
    return se.Version;
  }
  /** Gets the list of created engines */
  static get Instances() {
    return J.Instances;
  }
  /**
   * Gets the latest created engine
   */
  static get LastCreatedEngine() {
    return J.LastCreatedEngine;
  }
  /**
   * Gets the latest created scene
   */
  static get LastCreatedScene() {
    return J.LastCreatedScene;
  }
  /** @internal */
  /**
   * 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.
   */
  _createImageBitmapFromSource(e, t) {
    return new Promise((s, r) => {
      const n = new Image();
      n.onload = () => {
        n.decode().then(() => {
          this.createImageBitmap(n, t).then((a) => {
            s(a);
          });
        });
      }, n.onerror = () => {
        r(`Error loading image ${n.src}`);
      }, n.src = e;
    });
  }
  /**
   * Engine abstraction for createImageBitmap
   * @param image source for image
   * @param options An object that sets options for the image's extraction.
   * @returns ImageBitmap
   */
  createImageBitmap(e, t) {
    return createImageBitmap(e, t);
  }
  /**
   * 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(e, t, i) {
    const r = this.createCanvas(t, i).getContext("2d");
    if (!r)
      throw new Error("Unable to get 2d context for resizeImageBitmap");
    return r.drawImage(e, 0, 0), r.getImageData(0, 0, t, i).data;
  }
  /**
   * 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(e, t) {
    for (let i = 0; i < P.Instances.length; i++) {
      const s = P.Instances[i];
      for (let r = 0; r < s.scenes.length; r++)
        s.scenes[r].markAllMaterialsAsDirty(e, t);
    }
  }
  /**
   * 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(e) {
    throw Y("LoadingScreen");
  }
  get _supportsHardwareTextureRescaling() {
    return !!P._RescalePostProcessFactory;
  }
  /**
   * 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;
  }
  /**
   * (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(e) {
    this._compatibilityMode = !0;
  }
  // Events
  /**
   * Gets the HTML element used to attach event listeners
   * @returns a HTML element
   */
  getInputElement() {
    return this._renderingCanvas;
  }
  /**
   * 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(e, t, i, s = !1) {
    if (super(e, t, i, s), this.enableOfflineSupport = !1, this.disableManifestCheck = !1, this.disableContextMenu = !0, this.scenes = new Array(), this._virtualScenes = new Array(), this.onNewSceneAddedObservable = new w(), this.postProcesses = new Array(), this.isPointerLock = !1, this.onResizeObservable = new w(), this.onCanvasBlurObservable = new w(), this.onCanvasFocusObservable = new w(), this.onCanvasPointerOutObservable = new w(), this.onBeginFrameObservable = new w(), this.customAnimationFrameRequester = null, this.onEndFrameObservable = new w(), this.onBeforeShaderCompilationObservable = new w(), this.onAfterShaderCompilationObservable = new w(), this._deterministicLockstep = !1, this._lockstepMaxSteps = 4, this._timeStep = 1 / 60, this._fps = 60, this._deltaTime = 0, this._drawCalls = new Je(), this.canvasTabIndex = 1, this.disablePerformanceMonitorInBackground = !1, this._performanceMonitor = new ur(), this._compatibilityMode = !0, this.currentRenderPassId = 0, this._renderPassNames = ["main"], P.Instances.push(this), !!e) {
      if (this._features.supportRenderPasses = !0, i = this._creationOptions, e.getContext) {
        const r = e;
        this._sharedInit(r), this._connectVREvents();
      }
      this._prepareVRComponent(), i.autoEnableWebVR && this.initWebVR();
    }
  }
  _initGLContext() {
    super._initGLContext(), this._rescalePostProcess = null;
  }
  /**
   * Shared initialization across engines types.
   * @param canvas The canvas associated with this instance of the engine.
   */
  _sharedInit(e) {
    super._sharedInit(e), this._onCanvasFocus = () => {
      this.onCanvasFocusObservable.notifyObservers(this);
    }, this._onCanvasBlur = () => {
      this.onCanvasBlurObservable.notifyObservers(this);
    }, this._onCanvasContextMenu = (i) => {
      this.disableContextMenu && i.preventDefault();
    }, e.addEventListener("focus", this._onCanvasFocus), e.addEventListener("blur", this._onCanvasBlur), e.addEventListener("contextmenu", this._onCanvasContextMenu), this._onBlur = () => {
      this.disablePerformanceMonitorInBackground && this._performanceMonitor.disable(), this._windowIsBackground = !0;
    }, this._onFocus = () => {
      this.disablePerformanceMonitorInBackground && this._performanceMonitor.enable(), this._windowIsBackground = !1;
    }, this._onCanvasPointerOut = (i) => {
      document.elementFromPoint(i.clientX, i.clientY) !== e && this.onCanvasPointerOutObservable.notifyObservers(i);
    };
    const t = this.getHostWindow();
    t && typeof t.addEventListener == "function" && (t.addEventListener("blur", this._onBlur), t.addEventListener("focus", this._onFocus)), e.addEventListener("pointerout", this._onCanvasPointerOut), this._creationOptions.doNotHandleTouchAction || this._disableTouchAction(), !P.audioEngine && this._creationOptions.audioEngine && P.AudioEngineFactory && (P.audioEngine = P.AudioEngineFactory(this.getRenderingCanvas(), this.getAudioContext(), this.getAudioDestination())), Wt() && (this._onFullscreenChange = () => {
      this.isFullscreen = !!document.fullscreenElement, this.isFullscreen && this._pointerLockRequested && e && P._RequestPointerlock(e);
    }, document.addEventListener("fullscreenchange", this._onFullscreenChange, !1), document.addEventListener("webkitfullscreenchange", this._onFullscreenChange, !1), this._onPointerLockChange = () => {
      this.isPointerLock = document.pointerLockElement === e;
    }, document.addEventListener("pointerlockchange", this._onPointerLockChange, !1), document.addEventListener("webkitpointerlockchange", this._onPointerLockChange, !1)), this.enableOfflineSupport = P.OfflineProviderFactory !== void 0, this._deterministicLockstep = !!this._creationOptions.deterministicLockstep, this._lockstepMaxSteps = this._creationOptions.lockstepMaxSteps || 0, this._timeStep = this._creationOptions.timeStep || 1 / 60;
  }
  /** @internal */
  _verifyPointerLock() {
    var e;
    (e = this._onPointerLockChange) === null || e === void 0 || e.call(this);
  }
  /**
   * Gets current aspect ratio
   * @param viewportOwner defines the camera to use to get the aspect ratio
   * @param useScreen defines if screen size must be used (or the current render target if any)
   * @returns a number defining the aspect ratio
   */
  getAspectRatio(e, t = !1) {
    const i = e.viewport;
    return this.getRenderWidth(t) * i.width / (this.getRenderHeight(t) * i.height);
  }
  /**
   * Gets current screen aspect ratio
   * @returns a number defining the aspect ratio
   */
  getScreenAspectRatio() {
    return this.getRenderWidth(!0) / this.getRenderHeight(!0);
  }
  /**
   * Gets the client rect of the HTML canvas attached with the current webGL context
   * @returns a client rectangle
   */
  getRenderingCanvasClientRect() {
    return this._renderingCanvas ? this._renderingCanvas.getBoundingClientRect() : null;
  }
  /**
   * Gets the client rect of the HTML element used for events
   * @returns a client rectangle
   */
  getInputElementClientRect() {
    return this._renderingCanvas ? this.getInputElement().getBoundingClientRect() : null;
  }
  /**
   * 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;
  }
  /**
   * Force the mipmap generation for the given render target texture
   * @param texture defines the render target texture to use
   * @param unbind defines whether or not to unbind the texture after generation. Defaults to true.
   */
  generateMipMapsForCubemap(e, t = !0) {
    if (e.generateMipMaps) {
      const i = this._gl;
      this._bindTextureDirectly(i.TEXTURE_CUBE_MAP, e, !0), i.generateMipmap(i.TEXTURE_CUBE_MAP), t && this._bindTextureDirectly(i.TEXTURE_CUBE_MAP, null);
    }
  }
  /** States */
  /**
   * Gets a boolean indicating if depth writing is enabled
   * @returns the current depth writing state
   */
  getDepthWrite() {
    return this._depthCullingState.depthMask;
  }
  /**
   * Enable or disable depth writing
   * @param enable defines the state to set
   */
  setDepthWrite(e) {
    this._depthCullingState.depthMask = e;
  }
  /**
   * Gets a boolean indicating if stencil buffer is enabled
   * @returns the current stencil buffer state
   */
  getStencilBuffer() {
    return this._stencilState.stencilTest;
  }
  /**
   * Enable or disable the stencil buffer
   * @param enable defines if the stencil buffer must be enabled or disabled
   */
  setStencilBuffer(e) {
    this._stencilState.stencilTest = e;
  }
  /**
   * Gets the current stencil mask
   * @returns a number defining the new stencil mask to use
   */
  getStencilMask() {
    return this._stencilState.stencilMask;
  }
  /**
   * Sets the current stencil mask
   * @param mask defines the new stencil mask to use
   */
  setStencilMask(e) {
    this._stencilState.stencilMask = e;
  }
  /**
   * Gets the current stencil function
   * @returns a number defining the stencil function to use
   */
  getStencilFunction() {
    return this._stencilState.stencilFunc;
  }
  /**
   * Gets the current stencil reference value
   * @returns a number defining the stencil reference value to use
   */
  getStencilFunctionReference() {
    return this._stencilState.stencilFuncRef;
  }
  /**
   * Gets the current stencil mask
   * @returns a number defining the stencil mask to use
   */
  getStencilFunctionMask() {
    return this._stencilState.stencilFuncMask;
  }
  /**
   * Sets the current stencil function
   * @param stencilFunc defines the new stencil function to use
   */
  setStencilFunction(e) {
    this._stencilState.stencilFunc = e;
  }
  /**
   * Sets the current stencil reference
   * @param reference defines the new stencil reference to use
   */
  setStencilFunctionReference(e) {
    this._stencilState.stencilFuncRef = e;
  }
  /**
   * Sets the current stencil mask
   * @param mask defines the new stencil mask to use
   */
  setStencilFunctionMask(e) {
    this._stencilState.stencilFuncMask = e;
  }
  /**
   * Gets the current stencil operation when stencil fails
   * @returns a number defining stencil operation to use when stencil fails
   */
  getStencilOperationFail() {
    return this._stencilState.stencilOpStencilFail;
  }
  /**
   * Gets the current stencil operation when depth fails
   * @returns a number defining stencil operation to use when depth fails
   */
  getStencilOperationDepthFail() {
    return this._stencilState.stencilOpDepthFail;
  }
  /**
   * Gets the current stencil operation when stencil passes
   * @returns a number defining stencil operation to use when stencil passes
   */
  getStencilOperationPass() {
    return this._stencilState.stencilOpStencilDepthPass;
  }
  /**
   * Sets the stencil operation to use when stencil fails
   * @param operation defines the stencil operation to use when stencil fails
   */
  setStencilOperationFail(e) {
    this._stencilState.stencilOpStencilFail = e;
  }
  /**
   * Sets the stencil operation to use when depth fails
   * @param operation defines the stencil operation to use when depth fails
   */
  setStencilOperationDepthFail(e) {
    this._stencilState.stencilOpDepthFail = e;
  }
  /**
   * Sets the stencil operation to use when stencil passes
   * @param operation defines the stencil operation to use when stencil passes
   */
  setStencilOperationPass(e) {
    this._stencilState.stencilOpStencilDepthPass = e;
  }
  /**
   * Sets a boolean indicating if the dithering state is enabled or disabled
   * @param value defines the dithering state
   */
  setDitheringState(e) {
    e ? this._gl.enable(this._gl.DITHER) : 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(e) {
    e ? this._gl.disable(this._gl.RASTERIZER_DISCARD) : this._gl.enable(this._gl.RASTERIZER_DISCARD);
  }
  /**
   * Gets the current depth function
   * @returns a number defining the depth function
   */
  getDepthFunction() {
    return this._depthCullingState.depthFunc;
  }
  /**
   * Sets the current depth function
   * @param depthFunc defines the function to use
   */
  setDepthFunction(e) {
    this._depthCullingState.depthFunc = e;
  }
  /**
   * Sets the current depth function to GREATER
   */
  setDepthFunctionToGreater() {
    this.setDepthFunction(516);
  }
  /**
   * Sets the current depth function to GEQUAL
   */
  setDepthFunctionToGreaterOrEqual() {
    this.setDepthFunction(518);
  }
  /**
   * Sets the current depth function to LESS
   */
  setDepthFunctionToLess() {
    this.setDepthFunction(513);
  }
  /**
   * Sets the current depth function to LEQUAL
   */
  setDepthFunctionToLessOrEqual() {
    this.setDepthFunction(515);
  }
  /**
   * Caches the the state of the stencil buffer
   */
  cacheStencilState() {
    this._cachedStencilBuffer = this.getStencilBuffer(), this._cachedStencilFunction = this.getStencilFunction(), this._cachedStencilMask = this.getStencilMask(), this._cachedStencilOperationPass = this.getStencilOperationPass(), this._cachedStencilOperationFail = this.getStencilOperationFail(), this._cachedStencilOperationDepthFail = this.getStencilOperationDepthFail(), this._cachedStencilReference = this.getStencilFunctionReference();
  }
  /**
   * Restores the state of the stencil buffer
   */
  restoreStencilState() {
    this.setStencilFunction(this._cachedStencilFunction), this.setStencilMask(this._cachedStencilMask), this.setStencilBuffer(this._cachedStencilBuffer), this.setStencilOperationPass(this._cachedStencilOperationPass), this.setStencilOperationFail(this._cachedStencilOperationFail), this.setStencilOperationDepthFail(this._cachedStencilOperationDepthFail), this.setStencilFunctionReference(this._cachedStencilReference);
  }
  /**
   * Directly set the WebGL Viewport
   * @param x defines the x coordinate of the viewport (in screen space)
   * @param y defines the y coordinate of the viewport (in screen space)
   * @param width defines the width of the viewport (in screen space)
   * @param height defines the height of the viewport (in screen space)
   * @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(e, t, i, s) {
    const r = this._cachedViewport;
    return this._cachedViewport = null, this._viewport(e, t, i, s), r;
  }
  /**
   * 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(e, t, i, s, r) {
    this.enableScissor(e, t, i, s), this.clear(r, !0, !0, !0), 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(e, t, i, s) {
    const r = this._gl;
    r.enable(r.SCISSOR_TEST), r.scissor(e, t, i, s);
  }
  /**
   * Disable previously set scissor test rectangle
   */
  disableScissor() {
    const e = this._gl;
    e.disable(e.SCISSOR_TEST);
  }
  /**
   * @internal
   */
  _reportDrawCall(e = 1) {
    this._drawCalls.addCount(e, !1);
  }
  /**
   * Initializes a webVR display and starts listening to display change events
   * The onVRDisplayChangedObservable will be notified upon these changes
   * @returns The onVRDisplayChangedObservable
   */
  initWebVR() {
    throw Y("WebVRCamera");
  }
  /** @internal */
  _prepareVRComponent() {
  }
  /**
   * @internal
   */
  // eslint-disable-next-line @typescript-eslint/no-unused-vars
  _connectVREvents(e, t) {
  }
  /** @internal */
  _submitVRFrame() {
  }
  /**
   * Call this function to leave webVR mode
   * Will do nothing if webVR is not supported or if there is no webVR device
   * @see https://doc.babylonjs.com/features/featuresDeepDive/cameras/webVRCamera
   */
  disableVR() {
  }
  /**
   * Gets a boolean indicating that the system is in VR mode and is presenting
   * @returns true if VR mode is engaged
   */
  isVRPresenting() {
    return !1;
  }
  /** @internal */
  _requestVRFrame() {
  }
  /**
   * @internal
   */
  _loadFileAsync(e, t, i) {
    return new Promise((s, r) => {
      this._loadFile(e, (n) => {
        s(n);
      }, void 0, t, i, (n, a) => {
        r(a);
      });
    });
  }
  /**
   * 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(e) {
    const t = this._gl.getAttachedShaders(e);
    return t ? this._gl.getShaderSource(t[0]) : null;
  }
  /**
   * 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(e) {
    const t = this._gl.getAttachedShaders(e);
    return t ? this._gl.getShaderSource(t[1]) : null;
  }
  /**
   * Sets a depth stencil texture from a render target to the according uniform.
   * @param channel The texture channel
   * @param uniform The uniform to set
   * @param texture The render target texture containing the depth stencil texture to apply
   * @param name The texture name
   */
  setDepthStencilTexture(e, t, i, s) {
    e !== void 0 && (t && (this._boundUniforms[e] = t), !i || !i.depthStencilTexture ? this._setTexture(e, null, void 0, void 0, s) : this._setTexture(e, i, !1, !0, s));
  }
  /**
   * Sets a texture to the webGL context from a postprocess
   * @param channel defines the channel to use
   * @param postProcess defines the source postprocess
   * @param name name of the channel
   */
  setTextureFromPostProcess(e, t, i) {
    var s;
    let r = null;
    t && (t._textures.data[t._currentRenderTextureInd] ? r = t._textures.data[t._currentRenderTextureInd] : t._forcedOutputTexture && (r = t._forcedOutputTexture)), this._bindTexture(e, (s = r == null ? void 0 : r.texture) !== null && s !== void 0 ? s : null, i);
  }
  /**
   * Binds the output of the passed in post process to the texture channel specified
   * @param channel The channel the texture should be bound to
   * @param postProcess The post process which's output should be bound
   * @param name name of the channel
   */
  setTextureFromPostProcessOutput(e, t, i) {
    var s, r;
    this._bindTexture(e, (r = (s = t == null ? void 0 : t._outputTexture) === null || s === void 0 ? void 0 : s.texture) !== null && r !== void 0 ? r : null, i);
  }
  _rebuildBuffers() {
    for (const e of this.scenes)
      e.resetCachedMaterial(), e._rebuildGeometries(), e._rebuildTextures();
    for (const e of this._virtualScenes)
      e.resetCachedMaterial(), e._rebuildGeometries(), e._rebuildTextures();
    super._rebuildBuffers();
  }
  /** @internal */
  _renderFrame() {
    for (let e = 0; e < this._activeRenderLoops.length; e++) {
      const t = this._activeRenderLoops[e];
      t();
    }
  }
  _renderLoop() {
    if (!this._contextWasLost) {
      let e = !0;
      (this.isDisposed || !this.renderEvenInBackground && this._windowIsBackground) && (e = !1), e && (this.beginFrame(), this._renderViews() || this._renderFrame(), this.endFrame());
    }
    this._activeRenderLoops.length > 0 ? this.customAnimationFrameRequester ? (this.customAnimationFrameRequester.requestID = this._queueNewFrame(this.customAnimationFrameRequester.renderFunction || this._boundRenderFunction, this.customAnimationFrameRequester), this._frameHandler = this.customAnimationFrameRequester.requestID) : this.isVRPresenting() ? this._requestVRFrame() : this._frameHandler = this._queueNewFrame(this._boundRenderFunction, this.getHostWindow()) : this._renderingQueueLaunched = !1;
  }
  /** @internal */
  _renderViews() {
    return !1;
  }
  /**
   * Toggle full screen mode
   * @param requestPointerLock defines if a pointer lock should be requested from the user
   */
  switchFullscreen(e) {
    this.isFullscreen ? this.exitFullscreen() : this.enterFullscreen(e);
  }
  /**
   * Enters full screen mode
   * @param requestPointerLock defines if a pointer lock should be requested from the user
   */
  enterFullscreen(e) {
    this.isFullscreen || (this._pointerLockRequested = e, this._renderingCanvas && P._RequestFullscreen(this._renderingCanvas));
  }
  /**
   * Exits full screen mode
   */
  exitFullscreen() {
    this.isFullscreen && P._ExitFullscreen();
  }
  /**
   * Enters Pointerlock mode
   */
  enterPointerlock() {
    this._renderingCanvas && P._RequestPointerlock(this._renderingCanvas);
  }
  /**
   * Exits Pointerlock mode
   */
  exitPointerlock() {
    P._ExitPointerlock();
  }
  /**
   * Begin a new frame
   */
  beginFrame() {
    this._measureFps(), this.onBeginFrameObservable.notifyObservers(this), super.beginFrame();
  }
  /**
   * End the current frame
   */
  endFrame() {
    super.endFrame(), this._submitVRFrame(), this.onEndFrameObservable.notifyObservers(this);
  }
  /**
   * Resize the view according to the canvas' size
   * @param forceSetSize true to force setting the sizes of the underlying canvas
   */
  resize(e = !1) {
    this.isVRPresenting() || super.resize(e);
  }
  /**
   * 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(e, t, i = !1) {
    if (!this._renderingCanvas || !super.setSize(e, t, i))
      return !1;
    if (this.scenes) {
      for (let s = 0; s < this.scenes.length; s++) {
        const r = this.scenes[s];
        for (let n = 0; n < r.cameras.length; n++) {
          const a = r.cameras[n];
          a._currentRenderId = 0;
        }
      }
      this.onResizeObservable.hasObservers() && this.onResizeObservable.notifyObservers(this);
    }
    return !0;
  }
  _deletePipelineContext(e) {
    const t = e;
    t && t.program && t.transformFeedback && (this.deleteTransformFeedback(t.transformFeedback), t.transformFeedback = null), super._deletePipelineContext(e);
  }
  createShaderProgram(e, t, i, s, r, n = null) {
    r = r || this._gl, this.onBeforeShaderCompilationObservable.notifyObservers(this);
    const a = super.createShaderProgram(e, t, i, s, r, n);
    return this.onAfterShaderCompilationObservable.notifyObservers(this), a;
  }
  _createShaderProgram(e, t, i, s, r = null) {
    const n = s.createProgram();
    if (e.program = n, !n)
      throw new Error("Unable to create program");
    if (s.attachShader(n, t), s.attachShader(n, i), this.webGLVersion > 1 && r) {
      const a = this.createTransformFeedback();
      this.bindTransformFeedback(a), this.setTranformFeedbackVaryings(n, r), e.transformFeedback = a;
    }
    return s.linkProgram(n), this.webGLVersion > 1 && r && this.bindTransformFeedback(null), e.context = s, e.vertexShader = t, e.fragmentShader = i, e.isParallelCompiled || this._finalizePipelineContext(e), n;
  }
  /**
   * @internal
   */
  _releaseTexture(e) {
    super._releaseTexture(e);
  }
  /**
   * @internal
   */
  _releaseRenderTargetWrapper(e) {
    super._releaseRenderTargetWrapper(e), this.scenes.forEach((t) => {
      t.postProcesses.forEach((i) => {
        i._outputTexture === e && (i._outputTexture = null);
      }), t.cameras.forEach((i) => {
        i._postProcesses.forEach((s) => {
          s && s._outputTexture === e && (s._outputTexture = null);
        });
      });
    });
  }
  /**
   * Gets the names of the render passes that are currently created
   * @returns list of the render pass names
   */
  getRenderPassNames() {
    return this._renderPassNames;
  }
  /**
   * Gets the name of the current render pass
   * @returns name of the current render pass
   */
  getCurrentRenderPassName() {
    return this._renderPassNames[this.currentRenderPassId];
  }
  /**
   * Creates a render pass id
   * @param name Name of the render pass (for debug purpose only)
   * @returns the id of the new render pass
   */
  createRenderPassId(e) {
    const t = ++P._RenderPassIdCounter;
    return this._renderPassNames[t] = e ?? "NONAME", t;
  }
  /**
   * Releases a render pass id
   * @param id id of the render pass to release
   */
  releaseRenderPassId(e) {
    this._renderPassNames[e] = void 0;
    for (let t = 0; t < this.scenes.length; ++t) {
      const i = this.scenes[t];
      for (let s = 0; s < i.meshes.length; ++s) {
        const r = i.meshes[s];
        if (r.subMeshes)
          for (let n = 0; n < r.subMeshes.length; ++n)
            r.subMeshes[n]._removeDrawWrapper(e);
      }
    }
  }
  /**
   * @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(e, t, i, s, r) {
    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 n = this.createRenderTargetTexture({
      width: t.width,
      height: t.height
    }, {
      generateMipMaps: !1,
      type: 0,
      samplingMode: 2,
      generateDepthBuffer: !1,
      generateStencilBuffer: !1
    });
    !this._rescalePostProcess && P._RescalePostProcessFactory && (this._rescalePostProcess = P._RescalePostProcessFactory(this)), this._rescalePostProcess && (this._rescalePostProcess.externalTextureSamplerBinding = !0, this._rescalePostProcess.getEffect().executeWhenCompiled(() => {
      this._rescalePostProcess.onApply = function(o) {
        o._bindTexture("textureSampler", e);
      };
      let a = i;
      a || (a = this.scenes[this.scenes.length - 1]), a.postProcessManager.directRender([this._rescalePostProcess], n, !0), this._bindTextureDirectly(this._gl.TEXTURE_2D, t, !0), this._gl.copyTexImage2D(this._gl.TEXTURE_2D, 0, s, 0, 0, t.width, t.height, 0), this.unBindFramebuffer(n), n.dispose(), r && r();
    }));
  }
  // FPS
  /**
   * 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;
  }
  _measureFps() {
    this._performanceMonitor.sampleFrame(), this._fps = this._performanceMonitor.averageFPS, this._deltaTime = this._performanceMonitor.instantaneousFrameTime || 0;
  }
  /**
   * 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)
   * @returns the babylon internal texture
   */
  wrapWebGLTexture(e, t = !1, i = 3) {
    const s = new rs(e, this._gl), r = new It(this, De.Unknown, !0);
    return r._hardwareTexture = s, r.isReady = !0, r.useMipMaps = t, this.updateTextureSamplingMode(i, r), r;
  }
  /**
   * @internal
   */
  _uploadImageToTexture(e, t, i = 0, s = 0) {
    const r = this._gl, n = this._getWebGLTextureType(e.type), a = this._getInternalFormat(e.format), o = this._getRGBABufferInternalSizedFormat(e.type, a), h = e.isCube ? r.TEXTURE_CUBE_MAP : r.TEXTURE_2D;
    this._bindTextureDirectly(h, e, !0), this._unpackFlipY(e.invertY);
    let c = r.TEXTURE_2D;
    e.isCube && (c = r.TEXTURE_CUBE_MAP_POSITIVE_X + i), r.texImage2D(c, s, o, a, n, t), this._bindTextureDirectly(h, null, !0);
  }
  /**
   * 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(e, t) {
    if (this.webGLVersion === 1) {
      S.Error("WebGL 1 does not support texture comparison.");
      return;
    }
    const i = this._gl;
    e.isCube ? (this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, e, !0), t === 0 ? (i.texParameteri(i.TEXTURE_CUBE_MAP, i.TEXTURE_COMPARE_FUNC, 515), i.texParameteri(i.TEXTURE_CUBE_MAP, i.TEXTURE_COMPARE_MODE, i.NONE)) : (i.texParameteri(i.TEXTURE_CUBE_MAP, i.TEXTURE_COMPARE_FUNC, t), i.texParameteri(i.TEXTURE_CUBE_MAP, i.TEXTURE_COMPARE_MODE, i.COMPARE_REF_TO_TEXTURE)), this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null)) : (this._bindTextureDirectly(this._gl.TEXTURE_2D, e, !0), t === 0 ? (i.texParameteri(i.TEXTURE_2D, i.TEXTURE_COMPARE_FUNC, 515), i.texParameteri(i.TEXTURE_2D, i.TEXTURE_COMPARE_MODE, i.NONE)) : (i.texParameteri(i.TEXTURE_2D, i.TEXTURE_COMPARE_FUNC, t), i.texParameteri(i.TEXTURE_2D, i.TEXTURE_COMPARE_MODE, i.COMPARE_REF_TO_TEXTURE)), this._bindTextureDirectly(this._gl.TEXTURE_2D, null)), e._comparisonFunction = t;
  }
  /**
   * Creates a webGL buffer to use with instantiation
   * @param capacity defines the size of the buffer
   * @returns the webGL buffer
   */
  createInstancesBuffer(e) {
    const t = this._gl.createBuffer();
    if (!t)
      throw new Error("Unable to create instance buffer");
    const i = new Gt(t);
    return i.capacity = e, this.bindArrayBuffer(i), this._gl.bufferData(this._gl.ARRAY_BUFFER, e, this._gl.DYNAMIC_DRAW), i.references = 1, i;
  }
  /**
   * Delete a webGL buffer used with instantiation
   * @param buffer defines the webGL buffer to delete
   */
  deleteInstancesBuffer(e) {
    this._gl.deleteBuffer(e);
  }
  _clientWaitAsync(e, t = 0, i = 10) {
    const s = this._gl;
    return new Promise((r, n) => {
      const a = () => {
        const o = s.clientWaitSync(e, t, 0);
        if (o == s.WAIT_FAILED) {
          n();
          return;
        }
        if (o == s.TIMEOUT_EXPIRED) {
          setTimeout(a, i);
          return;
        }
        r();
      };
      a();
    });
  }
  /**
   * @internal
   */
  _readPixelsAsync(e, t, i, s, r, n, a) {
    if (this._webGLVersion < 2)
      throw new Error("_readPixelsAsync only work on WebGL2+");
    const o = this._gl, h = o.createBuffer();
    o.bindBuffer(o.PIXEL_PACK_BUFFER, h), o.bufferData(o.PIXEL_PACK_BUFFER, a.byteLength, o.STREAM_READ), o.readPixels(e, t, i, s, r, n, 0), o.bindBuffer(o.PIXEL_PACK_BUFFER, null);
    const c = o.fenceSync(o.SYNC_GPU_COMMANDS_COMPLETE, 0);
    return c ? (o.flush(), this._clientWaitAsync(c, 0, 10).then(() => (o.deleteSync(c), o.bindBuffer(o.PIXEL_PACK_BUFFER, h), o.getBufferSubData(o.PIXEL_PACK_BUFFER, 0, a), o.bindBuffer(o.PIXEL_PACK_BUFFER, null), o.deleteBuffer(h), a))) : null;
  }
  dispose() {
    for (this.hideLoadingUI(), this.onNewSceneAddedObservable.clear(); this.postProcesses.length; )
      this.postProcesses[0].dispose();
    for (this._rescalePostProcess && this._rescalePostProcess.dispose(); this.scenes.length; )
      this.scenes[0].dispose();
    for (; this._virtualScenes.length; )
      this._virtualScenes[0].dispose();
    J.Instances.length === 1 && P.audioEngine && (P.audioEngine.dispose(), P.audioEngine = null), this.disableVR();
    const e = this.getHostWindow();
    e && typeof e.removeEventListener == "function" && (e.removeEventListener("blur", this._onBlur), e.removeEventListener("focus", this._onFocus)), this._renderingCanvas && (this._renderingCanvas.removeEventListener("focus", this._onCanvasFocus), this._renderingCanvas.removeEventListener("blur", this._onCanvasBlur), this._renderingCanvas.removeEventListener("pointerout", this._onCanvasPointerOut), this._renderingCanvas.removeEventListener("contextmenu", this._onCanvasContextMenu)), Wt() && (document.removeEventListener("fullscreenchange", this._onFullscreenChange), document.removeEventListener("mozfullscreenchange", this._onFullscreenChange), document.removeEventListener("webkitfullscreenchange", this._onFullscreenChange), document.removeEventListener("msfullscreenchange", this._onFullscreenChange), document.removeEventListener("pointerlockchange", this._onPointerLockChange), document.removeEventListener("mspointerlockchange", this._onPointerLockChange), document.removeEventListener("mozpointerlockchange", this._onPointerLockChange), document.removeEventListener("webkitpointerlockchange", this._onPointerLockChange)), super.dispose();
    const t = J.Instances.indexOf(this);
    t >= 0 && J.Instances.splice(t, 1), P.Instances.length || (J.OnEnginesDisposedObservable.notifyObservers(this), J.OnEnginesDisposedObservable.clear()), this.onResizeObservable.clear(), this.onCanvasBlurObservable.clear(), this.onCanvasFocusObservable.clear(), this.onCanvasPointerOutObservable.clear(), this.onBeginFrameObservable.clear(), this.onEndFrameObservable.clear();
  }
  _disableTouchAction() {
    !this._renderingCanvas || !this._renderingCanvas.setAttribute || (this._renderingCanvas.setAttribute("touch-action", "none"), this._renderingCanvas.style.touchAction = "none", this._renderingCanvas.style.webkitTapHighlightColor = "transparent");
  }
  // Loading screen
  /**
   * Display the loading screen
   * @see https://doc.babylonjs.com/features/featuresDeepDive/scene/customLoadingScreen
   */
  displayLoadingUI() {
    if (!Ie())
      return;
    const e = this.loadingScreen;
    e && e.displayLoadingUI();
  }
  /**
   * Hide the loading screen
   * @see https://doc.babylonjs.com/features/featuresDeepDive/scene/customLoadingScreen
   */
  hideLoadingUI() {
    if (!Ie())
      return;
    const e = this._loadingScreen;
    e && e.hideLoadingUI();
  }
  /**
   * Gets the current loading screen object
   * @see https://doc.babylonjs.com/features/featuresDeepDive/scene/customLoadingScreen
   */
  get loadingScreen() {
    return !this._loadingScreen && this._renderingCanvas && (this._loadingScreen = P.DefaultLoadingScreenFactory(this._renderingCanvas)), this._loadingScreen;
  }
  /**
   * Sets the current loading screen object
   * @see https://doc.babylonjs.com/features/featuresDeepDive/scene/customLoadingScreen
   */
  set loadingScreen(e) {
    this._loadingScreen = e;
  }
  /**
   * Sets the current loading screen text
   * @see https://doc.babylonjs.com/features/featuresDeepDive/scene/customLoadingScreen
   */
  set loadingUIText(e) {
    this.loadingScreen.loadingUIText = e;
  }
  /**
   * Sets the current loading screen background color
   * @see https://doc.babylonjs.com/features/featuresDeepDive/scene/customLoadingScreen
   */
  set loadingUIBackgroundColor(e) {
    this.loadingScreen.loadingUIBackgroundColor = e;
  }
  /**
   * creates and returns a new video element
   * @param constraints video constraints
   * @returns video element
   */
  // eslint-disable-next-line @typescript-eslint/no-unused-vars
  createVideoElement(e) {
    return document.createElement("video");
  }
  /** Pointerlock and fullscreen */
  /**
   * Ask the browser to promote the current element to pointerlock mode
   * @param element defines the DOM element to promote
   */
  static _RequestPointerlock(e) {
    if (e.requestPointerLock) {
      const t = e.requestPointerLock();
      t instanceof Promise ? t.then(() => {
        e.focus();
      }).catch(() => {
      }) : e.focus();
    }
  }
  /**
   * Asks the browser to exit pointerlock mode
   */
  static _ExitPointerlock() {
    document.exitPointerLock && document.exitPointerLock();
  }
  /**
   * Ask the browser to promote the current element to fullscreen rendering mode
   * @param element defines the DOM element to promote
   */
  static _RequestFullscreen(e) {
    const t = e.requestFullscreen || e.webkitRequestFullscreen;
    t && t.call(e);
  }
  /**
   * Asks the browser to exit fullscreen mode
   */
  static _ExitFullscreen() {
    const e = document;
    document.exitFullscreen ? document.exitFullscreen() : e.webkitCancelFullScreen && e.webkitCancelFullScreen();
  }
  /**
   * Get Font size information
   * @param font font name
   * @returns an object containing ascent, height and descent
   */
  getFontOffset(e) {
    const t = document.createElement("span");
    t.innerHTML = "Hg", t.setAttribute("style", `font: ${e} !important`);
    const i = document.createElement("div");
    i.style.display = "inline-block", i.style.width = "1px", i.style.height = "0px", i.style.verticalAlign = "bottom";
    const s = document.createElement("div");
    s.style.whiteSpace = "nowrap", s.appendChild(t), s.appendChild(i), document.body.appendChild(s);
    let r = 0, n = 0;
    try {
      n = i.getBoundingClientRect().top - t.getBoundingClientRect().top, i.style.verticalAlign = "baseline", r = i.getBoundingClientRect().top - t.getBoundingClientRect().top;
    } finally {
      document.body.removeChild(s);
    }
    return { ascent: r, height: n, descent: n - r };
  }
}
P.ALPHA_DISABLE = 0;
P.ALPHA_ADD = 1;
P.ALPHA_COMBINE = 2;
P.ALPHA_SUBTRACT = 3;
P.ALPHA_MULTIPLY = 4;
P.ALPHA_MAXIMIZED = 5;
P.ALPHA_ONEONE = 6;
P.ALPHA_PREMULTIPLIED = 7;
P.ALPHA_PREMULTIPLIED_PORTERDUFF = 8;
P.ALPHA_INTERPOLATE = 9;
P.ALPHA_SCREENMODE = 10;
P.DELAYLOADSTATE_NONE = 0;
P.DELAYLOADSTATE_LOADED = 1;
P.DELAYLOADSTATE_LOADING = 2;
P.DELAYLOADSTATE_NOTLOADED = 4;
P.NEVER = 512;
P.ALWAYS = 519;
P.LESS = 513;
P.EQUAL = 514;
P.LEQUAL = 515;
P.GREATER = 516;
P.GEQUAL = 518;
P.NOTEQUAL = 517;
P.KEEP = 7680;
P.REPLACE = 7681;
P.INCR = 7682;
P.DECR = 7683;
P.INVERT = 5386;
P.INCR_WRAP = 34055;
P.DECR_WRAP = 34056;
P.TEXTURE_CLAMP_ADDRESSMODE = 0;
P.TEXTURE_WRAP_ADDRESSMODE = 1;
P.TEXTURE_MIRROR_ADDRESSMODE = 2;
P.TEXTUREFORMAT_ALPHA = 0;
P.TEXTUREFORMAT_LUMINANCE = 1;
P.TEXTUREFORMAT_LUMINANCE_ALPHA = 2;
P.TEXTUREFORMAT_RGB = 4;
P.TEXTUREFORMAT_RGBA = 5;
P.TEXTUREFORMAT_RED = 6;
P.TEXTUREFORMAT_R = 6;
P.TEXTUREFORMAT_RG = 7;
P.TEXTUREFORMAT_RED_INTEGER = 8;
P.TEXTUREFORMAT_R_INTEGER = 8;
P.TEXTUREFORMAT_RG_INTEGER = 9;
P.TEXTUREFORMAT_RGB_INTEGER = 10;
P.TEXTUREFORMAT_RGBA_INTEGER = 11;
P.TEXTURETYPE_UNSIGNED_BYTE = 0;
P.TEXTURETYPE_UNSIGNED_INT = 0;
P.TEXTURETYPE_FLOAT = 1;
P.TEXTURETYPE_HALF_FLOAT = 2;
P.TEXTURETYPE_BYTE = 3;
P.TEXTURETYPE_SHORT = 4;
P.TEXTURETYPE_UNSIGNED_SHORT = 5;
P.TEXTURETYPE_INT = 6;
P.TEXTURETYPE_UNSIGNED_INTEGER = 7;
P.TEXTURETYPE_UNSIGNED_SHORT_4_4_4_4 = 8;
P.TEXTURETYPE_UNSIGNED_SHORT_5_5_5_1 = 9;
P.TEXTURETYPE_UNSIGNED_SHORT_5_6_5 = 10;
P.TEXTURETYPE_UNSIGNED_INT_2_10_10_10_REV = 11;
P.TEXTURETYPE_UNSIGNED_INT_24_8 = 12;
P.TEXTURETYPE_UNSIGNED_INT_10F_11F_11F_REV = 13;
P.TEXTURETYPE_UNSIGNED_INT_5_9_9_9_REV = 14;
P.TEXTURETYPE_FLOAT_32_UNSIGNED_INT_24_8_REV = 15;
P.TEXTURE_NEAREST_SAMPLINGMODE = 1;
P.TEXTURE_BILINEAR_SAMPLINGMODE = 2;
P.TEXTURE_TRILINEAR_SAMPLINGMODE = 3;
P.TEXTURE_NEAREST_NEAREST_MIPLINEAR = 8;
P.TEXTURE_LINEAR_LINEAR_MIPNEAREST = 11;
P.TEXTURE_LINEAR_LINEAR_MIPLINEAR = 3;
P.TEXTURE_NEAREST_NEAREST_MIPNEAREST = 4;
P.TEXTURE_NEAREST_LINEAR_MIPNEAREST = 5;
P.TEXTURE_NEAREST_LINEAR_MIPLINEAR = 6;
P.TEXTURE_NEAREST_LINEAR = 7;
P.TEXTURE_NEAREST_NEAREST = 1;
P.TEXTURE_LINEAR_NEAREST_MIPNEAREST = 9;
P.TEXTURE_LINEAR_NEAREST_MIPLINEAR = 10;
P.TEXTURE_LINEAR_LINEAR = 2;
P.TEXTURE_LINEAR_NEAREST = 12;
P.TEXTURE_EXPLICIT_MODE = 0;
P.TEXTURE_SPHERICAL_MODE = 1;
P.TEXTURE_PLANAR_MODE = 2;
P.TEXTURE_CUBIC_MODE = 3;
P.TEXTURE_PROJECTION_MODE = 4;
P.TEXTURE_SKYBOX_MODE = 5;
P.TEXTURE_INVCUBIC_MODE = 6;
P.TEXTURE_EQUIRECTANGULAR_MODE = 7;
P.TEXTURE_FIXED_EQUIRECTANGULAR_MODE = 8;
P.TEXTURE_FIXED_EQUIRECTANGULAR_MIRRORED_MODE = 9;
P.SCALEMODE_FLOOR = 1;
P.SCALEMODE_NEAREST = 2;
P.SCALEMODE_CEILING = 3;
P._RescalePostProcessFactory = null;
P._RenderPassIdCounter = 0;
class pe {
  /**
   * Gets or sets a boolean indicating if entire scene must be loaded even if scene contains incremental data
   */
  static get ForceFullSceneLoadingForIncremental() {
    return pe._ForceFullSceneLoadingForIncremental;
  }
  static set ForceFullSceneLoadingForIncremental(e) {
    pe._ForceFullSceneLoadingForIncremental = e;
  }
  /**
   * Gets or sets a boolean indicating if loading screen must be displayed while loading a scene
   */
  static get ShowLoadingScreen() {
    return pe._ShowLoadingScreen;
  }
  static set ShowLoadingScreen(e) {
    pe._ShowLoadingScreen = e;
  }
  /**
   * Defines the current logging level (while loading the scene)
   * @ignorenaming
   */
  // eslint-disable-next-line @typescript-eslint/naming-convention
  static get loggingLevel() {
    return pe._LoggingLevel;
  }
  // eslint-disable-next-line @typescript-eslint/naming-convention
  static set loggingLevel(e) {
    pe._LoggingLevel = e;
  }
  /**
   * Gets or set a boolean indicating if matrix weights must be cleaned upon loading
   */
  static get CleanBoneMatrixWeights() {
    return pe._CleanBoneMatrixWeights;
  }
  static set CleanBoneMatrixWeights(e) {
    pe._CleanBoneMatrixWeights = e;
  }
}
pe._ForceFullSceneLoadingForIncremental = !1;
pe._ShowLoadingScreen = !0;
pe._CleanBoneMatrixWeights = !1;
pe._LoggingLevel = 0;
var pt;
(function(l) {
  l[l.Clean = 0] = "Clean", l[l.Stop = 1] = "Stop", l[l.Sync = 2] = "Sync", l[l.NoSync = 3] = "NoSync";
})(pt || (pt = {}));
class j {
  /**
   * Gets or sets a boolean indicating if entire scene must be loaded even if scene contains incremental data
   */
  static get ForceFullSceneLoadingForIncremental() {
    return pe.ForceFullSceneLoadingForIncremental;
  }
  static set ForceFullSceneLoadingForIncremental(e) {
    pe.ForceFullSceneLoadingForIncremental = e;
  }
  /**
   * Gets or sets a boolean indicating if loading screen must be displayed while loading a scene
   */
  static get ShowLoadingScreen() {
    return pe.ShowLoadingScreen;
  }
  static set ShowLoadingScreen(e) {
    pe.ShowLoadingScreen = e;
  }
  /**
   * Defines the current logging level (while loading the scene)
   * @ignorenaming
   */
  // eslint-disable-next-line @typescript-eslint/naming-convention
  static get loggingLevel() {
    return pe.loggingLevel;
  }
  // eslint-disable-next-line @typescript-eslint/naming-convention
  static set loggingLevel(e) {
    pe.loggingLevel = e;
  }
  /**
   * Gets or set a boolean indicating if matrix weights must be cleaned upon loading
   */
  static get CleanBoneMatrixWeights() {
    return pe.CleanBoneMatrixWeights;
  }
  static set CleanBoneMatrixWeights(e) {
    pe.CleanBoneMatrixWeights = e;
  }
  /**
   * Gets the default plugin (used to load Babylon files)
   * @returns the .babylon plugin
   */
  static GetDefaultPlugin() {
    return j._RegisteredPlugins[".babylon"];
  }
  static _GetPluginForExtension(e) {
    const t = j._RegisteredPlugins[e];
    return t || (S.Warn("Unable to find a plugin to load " + e + " files. Trying to use .babylon default plugin. To load from a specific filetype (eg. gltf) see: https://doc.babylonjs.com/features/featuresDeepDive/importers/loadingFileTypes"), j.GetDefaultPlugin());
  }
  static _GetPluginForDirectLoad(e) {
    for (const t in j._RegisteredPlugins) {
      const i = j._RegisteredPlugins[t].plugin;
      if (i.canDirectLoad && i.canDirectLoad(e))
        return j._RegisteredPlugins[t];
    }
    return j.GetDefaultPlugin();
  }
  static _GetPluginForFilename(e) {
    const t = e.indexOf("?");
    t !== -1 && (e = e.substring(0, t));
    const i = e.lastIndexOf("."), s = e.substring(i, e.length).toLowerCase();
    return j._GetPluginForExtension(s);
  }
  static _GetDirectLoad(e) {
    return e.substr(0, 5) === "data:" ? e.substr(5) : null;
  }
  static _FormatErrorMessage(e, t, i) {
    let s = "Unable to load from " + e.url;
    return t ? s += `: ${t}` : i && (s += `: ${i}`), s;
  }
  static _LoadData(e, t, i, s, r, n, a) {
    const o = j._GetDirectLoad(e.url), h = a ? j._GetPluginForExtension(a) : o ? j._GetPluginForDirectLoad(e.url) : j._GetPluginForFilename(e.url);
    let c;
    if (h.plugin.createPlugin !== void 0 ? c = h.plugin.createPlugin() : c = h.plugin, !c)
      throw "The loader plugin corresponding to the file type you are trying to load has not been found. If using es6, please import the plugin you wish to use before.";
    if (j.OnPluginActivatedObservable.notifyObservers(c), o && (c.canDirectLoad && c.canDirectLoad(e.url) || !Oi(e.url))) {
      if (c.directLoad) {
        const v = c.directLoad(t, o);
        v.then ? v.then((A) => {
          i(c, A);
        }).catch((A) => {
          r("Error in directLoad of _loadData: " + A, A);
        }) : i(c, v);
      } else
        i(c, o);
      return c;
    }
    const u = h.isBinary, d = (v, A) => {
      if (t.isDisposed) {
        r("Scene has been disposed");
        return;
      }
      i(c, v, A);
    };
    let g = null, f = !1;
    const m = c.onDisposeObservable;
    m && m.add(() => {
      f = !0, g && (g.abort(), g = null), n();
    });
    const b = () => {
      if (f)
        return;
      const v = (E, y) => {
        r(E == null ? void 0 : E.statusText, y);
      }, A = e.file || e.url;
      g = c.loadFile ? c.loadFile(t, A, d, s, u, v) : t._loadFile(A, d, s, !0, u, v);
    }, T = t.getEngine();
    let M = T.enableOfflineSupport;
    if (M) {
      let v = !1;
      for (const A of t.disableOfflineSupportExceptionRules)
        if (A.test(e.url)) {
          v = !0;
          break;
        }
      M = !v;
    }
    return M && P.OfflineProviderFactory ? t.offlineProvider = P.OfflineProviderFactory(e.url, b, T.disableManifestCheck) : b(), c;
  }
  static _GetFileInfo(e, t) {
    let i, s, r = null;
    if (!t)
      i = e, s = k.GetFilename(e), e = k.GetFolderPath(e);
    else if (t.name) {
      const n = t;
      i = `file:${n.name}`, s = n.name, r = n;
    } else if (typeof t == "string" && t.startsWith("data:"))
      i = t, s = "";
    else {
      const n = t;
      if (n.substr(0, 1) === "/")
        return k.Error("Wrong sceneFilename parameter"), null;
      i = e + n, s = n;
    }
    return {
      url: i,
      rootUrl: e,
      name: s,
      file: r
    };
  }
  // 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(e) {
    return j._GetPluginForExtension(e).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(e) {
    return !!j._RegisteredPlugins[e];
  }
  /**
   * Adds a new plugin to the list of registered plugins
   * @param plugin defines the plugin to add
   */
  static RegisterPlugin(e) {
    if (typeof e.extensions == "string") {
      const t = e.extensions;
      j._RegisteredPlugins[t.toLowerCase()] = {
        plugin: e,
        isBinary: !1
      };
    } else {
      const t = e.extensions;
      Object.keys(t).forEach((i) => {
        j._RegisteredPlugins[i.toLowerCase()] = {
          plugin: e,
          isBinary: t[i].isBinary
        };
      });
    }
  }
  /**
   * Import meshes into a scene
   * @param meshNames an array of mesh names, a single mesh name, or empty string for all meshes that filter what meshes are imported
   * @param rootUrl a string that defines the root url for the scene and resources or the concatenation of rootURL and filename (e.g. http://example.com/test.glb)
   * @param sceneFilename a string that defines the name of the scene file or starts with "data:" following by the stringified version of the scene or a File object (default: empty string)
   * @param scene the instance of BABYLON.Scene to append to
   * @param onSuccess a callback with a list of imported meshes, particleSystems, 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
   * @returns The loaded plugin
   */
  static ImportMesh(e, t, i = "", s = J.LastCreatedScene, r = null, n = null, a = null, o = null) {
    if (!s)
      return S.Error("No scene available to import mesh to"), null;
    const h = j._GetFileInfo(t, i);
    if (!h)
      return null;
    const c = {};
    s.addPendingData(c);
    const u = () => {
      s.removePendingData(c);
    }, d = (m, b) => {
      const T = j._FormatErrorMessage(h, m, b);
      a ? a(s, T, new ct(T, vt.SceneLoaderError, b)) : S.Error(T), u();
    }, g = n ? (m) => {
      try {
        n(m);
      } catch (b) {
        d("Error in onProgress callback: " + b, b);
      }
    } : void 0, f = (m, b, T, M, v, A, E) => {
      if (s.importedMeshesFiles.push(h.url), r)
        try {
          r(m, b, T, M, v, A, E);
        } catch (y) {
          d("Error in onSuccess callback: " + y, y);
        }
      s.removePendingData(c);
    };
    return j._LoadData(h, s, (m, b, T) => {
      if (m.rewriteRootURL && (h.rootUrl = m.rewriteRootURL(h.rootUrl, T)), m.importMesh) {
        const M = m, v = new Array(), A = new Array(), E = new Array();
        if (!M.importMesh(e, s, b, h.rootUrl, v, A, E, d))
          return;
        s.loadingPluginName = m.name, f(v, A, E, [], [], [], []);
      } else
        m.importMeshAsync(e, s, b, h.rootUrl, g, h.name).then((v) => {
          s.loadingPluginName = m.name, f(v.meshes, v.particleSystems, v.skeletons, v.animationGroups, v.transformNodes, v.geometries, v.lights);
        }).catch((v) => {
          d(v.message, v);
        });
    }, g, d, u, o);
  }
  /**
   * Import meshes into a scene
   * @param meshNames an array of mesh names, a single mesh name, or empty string for all meshes that filter what meshes are imported
   * @param rootUrl a string that defines the root url for the scene and resources or the concatenation of rootURL and filename (e.g. http://example.com/test.glb)
   * @param sceneFilename a string that defines the name of the scene file or starts with "data:" following by the stringified version of the scene or a File object (default: empty string)
   * @param scene the instance of BABYLON.Scene to append to
   * @param onProgress a callback with a progress event for each file being loaded
   * @param pluginExtension the extension used to determine the plugin
   * @returns The loaded list of imported meshes, particle systems, skeletons, and animation groups
   */
  static ImportMeshAsync(e, t, i = "", s = J.LastCreatedScene, r = null, n = null) {
    return new Promise((a, o) => {
      j.ImportMesh(e, t, i, s, (h, c, u, d, g, f, m) => {
        a({
          meshes: h,
          particleSystems: c,
          skeletons: u,
          animationGroups: d,
          transformNodes: g,
          geometries: f,
          lights: m
        });
      }, r, (h, c, u) => {
        o(u || new Error(c));
      }, n);
    });
  }
  /**
   * Load a scene
   * @param rootUrl a string that defines the root url for the scene and resources or the concatenation of rootURL and filename (e.g. http://example.com/test.glb)
   * @param sceneFilename a string that defines the name of the scene file or starts with "data:" following by the stringified version of the scene or a File object (default: empty string)
   * @param engine is the instance of BABYLON.Engine to use to create the scene
   * @param onSuccess a callback with the scene when import succeeds
   * @param onProgress a callback with a progress event for each file being loaded
   * @param onError a callback with the scene, a message, and possibly an exception when import fails
   * @param pluginExtension the extension used to determine the plugin
   * @returns The loaded plugin
   */
  static Load(e, t = "", i = J.LastCreatedEngine, s = null, r = null, n = null, a = null) {
    return i ? j.Append(e, t, new Q(i), s, r, n, a) : (k.Error("No engine available"), null);
  }
  /**
   * Load a scene
   * @param rootUrl a string that defines the root url for the scene and resources or the concatenation of rootURL and filename (e.g. http://example.com/test.glb)
   * @param sceneFilename a string that defines the name of the scene file or starts with "data:" following by the stringified version of the scene or a File object (default: empty string)
   * @param engine is the instance of BABYLON.Engine to use to create the scene
   * @param onProgress a callback with a progress event for each file being loaded
   * @param pluginExtension the extension used to determine the plugin
   * @returns The loaded scene
   */
  static LoadAsync(e, t = "", i = J.LastCreatedEngine, s = null, r = null) {
    return new Promise((n, a) => {
      j.Load(e, t, i, (o) => {
        n(o);
      }, s, (o, h, c) => {
        a(c || new Error(h));
      }, r);
    });
  }
  /**
   * Append a scene
   * @param rootUrl a string that defines the root url for the scene and resources or the concatenation of rootURL and filename (e.g. http://example.com/test.glb)
   * @param sceneFilename a string that defines the name of the scene file or starts with "data:" following by the stringified version of the scene or a File object (default: empty string)
   * @param scene is the instance of BABYLON.Scene to append to
   * @param onSuccess a callback with the scene when import succeeds
   * @param onProgress a callback with a progress event for each file being loaded
   * @param onError a callback with the scene, a message, and possibly an exception when import fails
   * @param pluginExtension the extension used to determine the plugin
   * @returns The loaded plugin
   */
  static Append(e, t = "", i = J.LastCreatedScene, s = null, r = null, n = null, a = null) {
    if (!i)
      return S.Error("No scene available to append to"), null;
    const o = j._GetFileInfo(e, t);
    if (!o)
      return null;
    const h = {};
    i.addPendingData(h);
    const c = () => {
      i.removePendingData(h);
    };
    j.ShowLoadingScreen && !this._ShowingLoadingScreen && (this._ShowingLoadingScreen = !0, i.getEngine().displayLoadingUI(), i.executeWhenReady(() => {
      i.getEngine().hideLoadingUI(), this._ShowingLoadingScreen = !1;
    }));
    const u = (f, m) => {
      const b = j._FormatErrorMessage(o, f, m);
      n ? n(i, b, new ct(b, vt.SceneLoaderError, m)) : S.Error(b), c();
    }, d = r ? (f) => {
      try {
        r(f);
      } catch (m) {
        u("Error in onProgress callback", m);
      }
    } : void 0, g = () => {
      if (s)
        try {
          s(i);
        } catch (f) {
          u("Error in onSuccess callback", f);
        }
      i.removePendingData(h);
    };
    return j._LoadData(o, i, (f, m) => {
      if (f.load) {
        if (!f.load(i, m, o.rootUrl, u))
          return;
        i.loadingPluginName = f.name, g();
      } else
        f.loadAsync(i, m, o.rootUrl, d, o.name).then(() => {
          i.loadingPluginName = f.name, g();
        }).catch((T) => {
          u(T.message, T);
        });
    }, d, u, c, a);
  }
  /**
   * Append a scene
   * @param rootUrl a string that defines the root url for the scene and resources or the concatenation of rootURL and filename (e.g. http://example.com/test.glb)
   * @param sceneFilename a string that defines the name of the scene file or starts with "data:" following by the stringified version of the scene or a File object (default: empty string)
   * @param scene is the instance of BABYLON.Scene to append to
   * @param onProgress a callback with a progress event for each file being loaded
   * @param pluginExtension the extension used to determine the plugin
   * @returns The given scene
   */
  static AppendAsync(e, t = "", i = J.LastCreatedScene, s = null, r = null) {
    return new Promise((n, a) => {
      j.Append(e, t, i, (o) => {
        n(o);
      }, s, (o, h, c) => {
        a(c || new Error(h));
      }, r);
    });
  }
  /**
   * Load a scene into an asset container
   * @param rootUrl a string that defines the root url for the scene and resources or the concatenation of rootURL and filename (e.g. http://example.com/test.glb)
   * @param sceneFilename a string that defines the name of the scene file or starts with "data:" following by the stringified version of the scene or a File object (default: empty string)
   * @param scene is the instance of BABYLON.Scene to append to (default: last created scene)
   * @param onSuccess a callback with the scene when import succeeds
   * @param onProgress a callback with a progress event for each file being loaded
   * @param onError a callback with the scene, a message, and possibly an exception when import fails
   * @param pluginExtension the extension used to determine the plugin
   * @returns The loaded plugin
   */
  static LoadAssetContainer(e, t = "", i = J.LastCreatedScene, s = null, r = null, n = null, a = null) {
    if (!i)
      return S.Error("No scene available to load asset container to"), null;
    const o = j._GetFileInfo(e, t);
    if (!o)
      return null;
    const h = {};
    i.addPendingData(h);
    const c = () => {
      i.removePendingData(h);
    }, u = (f, m) => {
      const b = j._FormatErrorMessage(o, f, m);
      n ? n(i, b, new ct(b, vt.SceneLoaderError, m)) : S.Error(b), c();
    }, d = r ? (f) => {
      try {
        r(f);
      } catch (m) {
        u("Error in onProgress callback", m);
      }
    } : void 0, g = (f) => {
      if (s)
        try {
          s(f);
        } catch (m) {
          u("Error in onSuccess callback", m);
        }
      i.removePendingData(h);
    };
    return j._LoadData(o, i, (f, m) => {
      if (f.loadAssetContainer) {
        const T = f.loadAssetContainer(i, m, o.rootUrl, u);
        if (!T)
          return;
        i.loadingPluginName = f.name, g(T);
      } else
        f.loadAssetContainerAsync ? f.loadAssetContainerAsync(i, m, o.rootUrl, d, o.name).then((T) => {
          i.loadingPluginName = f.name, g(T);
        }).catch((T) => {
          u(T.message, T);
        }) : u("LoadAssetContainer is not supported by this plugin. Plugin did not provide a loadAssetContainer or loadAssetContainerAsync method.");
    }, d, u, c, a);
  }
  /**
   * Load a scene into an asset container
   * @param rootUrl a string that defines the root url for the scene and resources or the concatenation of rootURL and filename (e.g. http://example.com/test.glb)
   * @param sceneFilename a string that defines the name of the scene file or starts with "data:" following by the stringified version of the scene (default: empty string)
   * @param scene is the instance of Scene to append to
   * @param onProgress a callback with a progress event for each file being loaded
   * @param pluginExtension the extension used to determine the plugin
   * @returns The loaded asset container
   */
  static LoadAssetContainerAsync(e, t = "", i = J.LastCreatedScene, s = null, r = null) {
    return new Promise((n, a) => {
      j.LoadAssetContainer(e, t, i, (o) => {
        n(o);
      }, s, (o, h, c) => {
        a(c || new Error(h));
      }, r);
    });
  }
  /**
   * 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
   */
  static ImportAnimations(e, t = "", i = J.LastCreatedScene, s = !0, r = pt.Clean, n = null, a = null, o = null, h = null, c = null) {
    if (!i) {
      S.Error("No scene available to load animations to");
      return;
    }
    if (s) {
      for (const f of i.animatables)
        f.reset();
      i.stopAllAnimations(), i.animationGroups.slice().forEach((f) => {
        f.dispose();
      }), i.getNodes().forEach((f) => {
        f.animations && (f.animations = []);
      });
    } else
      switch (r) {
        case pt.Clean:
          i.animationGroups.slice().forEach((g) => {
            g.dispose();
          });
          break;
        case pt.Stop:
          i.animationGroups.forEach((g) => {
            g.stop();
          });
          break;
        case pt.Sync:
          i.animationGroups.forEach((g) => {
            g.reset(), g.restart();
          });
          break;
        case pt.NoSync:
          break;
        default:
          S.Error("Unknown animation group loading mode value '" + r + "'");
          return;
      }
    const u = i.animatables.length, d = (g) => {
      g.mergeAnimationsTo(i, i.animatables.slice(u), n), g.dispose(), i.onAnimationFileImportedObservable.notifyObservers(i), a && a(i);
    };
    this.LoadAssetContainer(e, t, i, d, o, h, c);
  }
  /**
   * Import animations from a file into a scene
   * @param rootUrl a string that defines the root url for the scene and resources or the concatenation of rootURL and filename (e.g. http://example.com/test.glb)
   * @param sceneFilename a string that defines the name of the scene file or starts with "data:" following by the stringified version of the scene or a File object (default: empty string)
   * @param scene is the instance of BABYLON.Scene to append to (default: last created scene)
   * @param overwriteAnimations when true, animations are cleaned before importing new ones. Animations are appended otherwise
   * @param animationGroupLoadingMode defines how to handle old animations groups before importing new ones
   * @param targetConverter defines a function used to convert animation targets from loaded scene to current scene (default: search node by name)
   * @param onSuccess a callback with the scene when import succeeds
   * @param onProgress a callback with a progress event for each file being loaded
   * @param onError a callback with the scene, a message, and possibly an exception when import fails
   * @param pluginExtension the extension used to determine the plugin
   * @returns the updated scene with imported animations
   */
  static ImportAnimationsAsync(e, t = "", i = J.LastCreatedScene, s = !0, r = pt.Clean, n = null, a = null, o = null, h = null, c = null) {
    return new Promise((u, d) => {
      j.ImportAnimations(e, t, i, s, r, n, (g) => {
        u(g);
      }, o, (g, f, m) => {
        d(m || new Error(f));
      }, c);
    });
  }
}
j.NO_LOGGING = 0;
j.MINIMAL_LOGGING = 1;
j.SUMMARY_LOGGING = 2;
j.DETAILED_LOGGING = 3;
j.OnPluginActivatedObservable = new w();
j._RegisteredPlugins = {};
j._ShowingLoadingScreen = !1;
class xi {
  constructor(e, t, i) {
    this.bu = e, this.bv = t, this.distance = i, this.faceId = 0, this.subMeshId = 0;
  }
}
class _r {
  constructor() {
    this._doNotSerialize = !1, this._isDisposed = !1, this._sceneRootNodesIndex = -1, this._isEnabled = !0, this._isParentEnabled = !0, this._isReady = !0, this._onEnabledStateChangedObservable = new w(), this._onClonedObservable = new w();
  }
}
class Ne {
  /**
   * Add a new node constructor
   * @param type defines the type name of the node to construct
   * @param constructorFunc defines the constructor function
   */
  static AddNodeConstructor(e, t) {
    this._NodeConstructors[e] = t;
  }
  /**
   * 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(e, t, i, s) {
    const r = this._NodeConstructors[e];
    return r ? r(t, i, s) : null;
  }
  /**
   * Gets or sets the accessibility tag to describe the node for accessibility purpose.
   */
  set accessibilityTag(e) {
    this._accessibilityTag = e, this.onAccessibilityTagChangedObservable.notifyObservers(e);
  }
  get accessibilityTag() {
    return this._accessibilityTag;
  }
  /**
   * Gets or sets a boolean used to define if the node must be serialized
   */
  get doNotSerialize() {
    return this._nodeDataStorage._doNotSerialize ? !0 : this._parentNode ? this._parentNode.doNotSerialize : !1;
  }
  set doNotSerialize(e) {
    this._nodeDataStorage._doNotSerialize = e;
  }
  /**
   * 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(e) {
    if (this._parentNode === e)
      return;
    const t = this._parentNode;
    if (this._parentNode && this._parentNode._children !== void 0 && this._parentNode._children !== null) {
      const i = this._parentNode._children.indexOf(this);
      i !== -1 && this._parentNode._children.splice(i, 1), !e && !this._nodeDataStorage._isDisposed && this._addToSceneRootNodes();
    }
    this._parentNode = e, this._parentNode && ((this._parentNode._children === void 0 || this._parentNode._children === null) && (this._parentNode._children = new Array()), this._parentNode._children.push(this), t || this._removeFromSceneRootNodes()), this._syncParentEnabledState();
  }
  get parent() {
    return this._parentNode;
  }
  /**
   * @internal
   */
  _serializeAsParent(e) {
    e.parentId = this.uniqueId;
  }
  /** @internal */
  _addToSceneRootNodes() {
    this._nodeDataStorage._sceneRootNodesIndex === -1 && (this._nodeDataStorage._sceneRootNodesIndex = this._scene.rootNodes.length, this._scene.rootNodes.push(this));
  }
  /** @internal */
  _removeFromSceneRootNodes() {
    if (this._nodeDataStorage._sceneRootNodesIndex !== -1) {
      const e = this._scene.rootNodes, t = e.length - 1;
      e[this._nodeDataStorage._sceneRootNodesIndex] = e[t], e[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() {
    return this._animationPropertiesOverride ? this._animationPropertiesOverride : this._scene.animationPropertiesOverride;
  }
  set animationPropertiesOverride(e) {
    this._animationPropertiesOverride = e;
  }
  /**
   * 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(e) {
    this._onDisposeObserver && this.onDisposeObservable.remove(this._onDisposeObserver), this._onDisposeObserver = this.onDisposeObservable.add(e);
  }
  /**
   * 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
   */
  constructor(e, t = null) {
    this._isDirty = !1, this._nodeDataStorage = new _r(), this.state = "", this.metadata = null, this.reservedDataStore = null, this._accessibilityTag = null, this.onAccessibilityTagChangedObservable = new w(), this._parentContainer = null, this.animations = new Array(), 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 = R.Identity(), this._worldMatrixDeterminant = 0, this._worldMatrixDeterminantIsDirty = !0, this._animationPropertiesOverride = null, this._isNode = !0, this.onDisposeObservable = new w(), this._onDisposeObserver = null, this._behaviors = new Array(), this.name = e, this.id = e, this._scene = t || J.LastCreatedScene, this.uniqueId = this._scene.getUniqueId(), this._initCache();
  }
  /**
   * 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(e, t = !1) {
    return this._behaviors.indexOf(e) !== -1 ? this : (e.init(), this._scene.isLoading && !t ? this._scene.onDataLoadedObservable.addOnce(() => {
      e.attach(this);
    }) : e.attach(this), this._behaviors.push(e), 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(e) {
    const t = this._behaviors.indexOf(e);
    return t === -1 ? this : (this._behaviors[t].detach(), this._behaviors.splice(t, 1), 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(e) {
    for (const t of this._behaviors)
      if (t.name === e)
        return t;
    return null;
  }
  /**
   * Returns the latest update of the World matrix
   * @returns a Matrix
   */
  getWorldMatrix() {
    return this._currentRenderId !== this._scene.getRenderId() && this.computeWorldMatrix(), this._worldMatrix;
  }
  /** @internal */
  _getWorldMatrixDeterminant() {
    return this._worldMatrixDeterminantIsDirty && (this._worldMatrixDeterminantIsDirty = !1, this._worldMatrixDeterminant = this._worldMatrix.determinant()), 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 = {}, this._cache.parent = void 0;
  }
  /**
   * @internal
   */
  updateCache(e) {
    !e && this.isSynchronized() || (this._cache.parent = this.parent, this._updateCache());
  }
  /**
   * @internal
   */
  _getActionManagerForTrigger(e, t = !0) {
    return this.parent ? this.parent._getActionManagerForTrigger(e, !1) : null;
  }
  // override it in derived class if you add new variables to the cache
  // and call the parent class method if !ignoreParentClass
  /**
   * @internal
   */
  _updateCache(e) {
  }
  // override it in derived class if you add new variables to the cache
  /** @internal */
  _isSynchronized() {
    return !0;
  }
  /** @internal */
  _markSyncedWithParent() {
    this._parentNode && (this._parentUpdateId = this._parentNode._childUpdateId);
  }
  /** @internal */
  isSynchronizedWithParent() {
    return this._parentNode ? this._parentNode._isDirty || this._parentUpdateId !== this._parentNode._childUpdateId ? !1 : this._parentNode.isSynchronized() : !0;
  }
  /** @internal */
  isSynchronized() {
    return this._cache.parent !== this._parentNode ? (this._cache.parent = this._parentNode, !1) : this._parentNode && !this.isSynchronizedWithParent() ? !1 : 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(e = !1) {
    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(e) {
    return this._currentRenderId = Number.MAX_VALUE, this._isDirty = !0, 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(e = !0) {
    return e === !1 ? this._nodeDataStorage._isEnabled : this._nodeDataStorage._isEnabled ? this._nodeDataStorage._isParentEnabled : !1;
  }
  /** @internal */
  _syncParentEnabledState() {
    this._nodeDataStorage._isParentEnabled = this._parentNode ? this._parentNode.isEnabled() : !0, this._children && this._children.forEach((e) => {
      e._syncParentEnabledState();
    });
  }
  /**
   * Set the enabled state of this node
   * @param value defines the new enabled state
   */
  setEnabled(e) {
    this._nodeDataStorage._isEnabled !== e && (this._nodeDataStorage._isEnabled = e, this._syncParentEnabledState(), this._nodeDataStorage._onEnabledStateChangedObservable.notifyObservers(e));
  }
  /**
   * 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(e) {
    return this.parent ? this.parent === e ? !0 : this.parent.isDescendantOf(e) : !1;
  }
  /**
   * @internal
   */
  _getDescendants(e, t = !1, i) {
    if (this._children)
      for (let s = 0; s < this._children.length; s++) {
        const r = this._children[s];
        (!i || i(r)) && e.push(r), t || r._getDescendants(e, !1, i);
      }
  }
  /**
   * 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(e, t) {
    const i = new Array();
    return this._getDescendants(i, e, t), i;
  }
  /**
   * 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(e, t) {
    const i = [];
    return this._getDescendants(i, e, (s) => (!t || t(s)) && s.cullingStrategy !== void 0), i;
  }
  /**
   * 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(e, t = !0) {
    return this.getDescendants(t, e);
  }
  /**
   * @internal
   */
  _setReady(e) {
    if (e !== this._nodeDataStorage._isReady) {
      if (!e) {
        this._nodeDataStorage._isReady = !1;
        return;
      }
      this.onReady && this.onReady(this), this._nodeDataStorage._isReady = !0;
    }
  }
  /**
   * 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(e) {
    for (let t = 0; t < this.animations.length; t++) {
      const i = this.animations[t];
      if (i.name === e)
        return i;
    }
    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(e, t, i) {
    if (!this._ranges[e]) {
      this._ranges[e] = Ne._AnimationRangeFactory(e, t, i);
      for (let s = 0, r = this.animations.length; s < r; s++)
        this.animations[s] && this.animations[s].createRange(e, t, i);
    }
  }
  /**
   * 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(e, t = !0) {
    for (let i = 0, s = this.animations.length; i < s; i++)
      this.animations[i] && this.animations[i].deleteRange(e, t);
    this._ranges[e] = 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(e) {
    return this._ranges[e] || null;
  }
  /**
   * Gets the list of all animation ranges defined on this node
   * @returns an array
   */
  getAnimationRanges() {
    const e = [];
    let t;
    for (t in this._ranges)
      e.push(this._ranges[t]);
    return e;
  }
  /**
   * 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(e, t, i, s) {
    const r = this.getAnimationRange(e);
    return r ? this._scene.beginAnimation(this, r.from, r.to, t, i, s) : null;
  }
  /**
   * Serialize animation ranges into a JSON compatible object
   * @returns serialization object
   */
  serializeAnimationRanges() {
    const e = [];
    for (const t in this._ranges) {
      const i = this._ranges[t];
      if (!i)
        continue;
      const s = {};
      s.name = t, s.from = i.from, s.to = i.to, e.push(s);
    }
    return e;
  }
  /**
   * 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(e) {
    return this._worldMatrix || (this._worldMatrix = R.Identity()), 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(e, t = !1) {
    if (this._nodeDataStorage._isDisposed = !0, !e) {
      const i = this.getDescendants(!0);
      for (const s of i)
        s.dispose(e, t);
    }
    this.parent ? this.parent = null : this._removeFromSceneRootNodes(), this.onDisposeObservable.notifyObservers(this), this.onDisposeObservable.clear(), this.onEnabledStateChangedObservable.clear(), this.onClonedObservable.clear();
    for (const i of this._behaviors)
      i.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(e, t, i) {
    if (t.ranges)
      for (let s = 0; s < t.ranges.length; s++) {
        const r = t.ranges[s];
        e.createAnimationRange(r.name, r.from, r.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(e = !0, t = null) {
    this.getScene().incrementRenderId(), this.computeWorldMatrix(!0);
    let i, s;
    const r = this;
    if (r.getBoundingInfo && r.subMeshes) {
      const n = r.getBoundingInfo();
      i = n.boundingBox.minimumWorld.clone(), s = n.boundingBox.maximumWorld.clone();
    } else
      i = new p(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE), s = new p(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
    if (e) {
      const n = this.getDescendants(!1);
      for (const a of n) {
        const o = a;
        if (o.computeWorldMatrix(!0), t && !t(o) || !o.getBoundingInfo || o.getTotalVertices() === 0)
          continue;
        const c = o.getBoundingInfo().boundingBox, u = c.minimumWorld, d = c.maximumWorld;
        p.CheckExtends(u, i, s), p.CheckExtends(d, i, s);
      }
    }
    return {
      min: i,
      max: s
    };
  }
}
Ne._AnimationRangeFactory = (l, e, t) => {
  throw Y("AnimationRange");
};
Ne._NodeConstructors = {};
F([
  B()
], Ne.prototype, "name", void 0);
F([
  B()
], Ne.prototype, "id", void 0);
F([
  B()
], Ne.prototype, "uniqueId", void 0);
F([
  B()
], Ne.prototype, "state", void 0);
F([
  B()
], Ne.prototype, "metadata", void 0);
class oi {
  /**
   * 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(e, t, i, s) {
    this.x = e, this.y = t, this.width = i, this.height = s;
  }
  /**
   * 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(e, t) {
    return new oi(this.x * e, this.y * t, this.width * e, this.height * t);
  }
  /**
   * 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(e, t, i) {
    return i.x = this.x * e, i.y = this.y * t, i.width = this.width * e, i.height = this.height * t, this;
  }
  /**
   * Returns a new Viewport copied from the current one
   * @returns a new Viewport
   */
  clone() {
    return new oi(this.x, this.y, this.width, this.height);
  }
}
class Z extends Ne {
  /**
   * Define the current local position of the camera in the scene
   */
  get position() {
    return this._position;
  }
  set position(e) {
    this._position = e;
  }
  /**
   * The vector the camera should consider as up.
   * (default is Vector3(0, 1, 0) aka Vector3.Up())
   */
  set upVector(e) {
    this._upVector = e;
  }
  get upVector() {
    return this._upVector;
  }
  /**
   * The screen area in scene units squared
   */
  get screenArea() {
    var e, t, i, s;
    let r = 0, n = 0;
    if (this.mode === Z.PERSPECTIVE_CAMERA)
      this.fovMode === Z.FOVMODE_VERTICAL_FIXED ? (n = this.minZ * 2 * Math.tan(this.fov / 2), r = this.getEngine().getAspectRatio(this) * n) : (r = this.minZ * 2 * Math.tan(this.fov / 2), n = r / this.getEngine().getAspectRatio(this));
    else {
      const a = this.getEngine().getRenderWidth() / 2, o = this.getEngine().getRenderHeight() / 2;
      r = ((e = this.orthoRight) !== null && e !== void 0 ? e : a) - ((t = this.orthoLeft) !== null && t !== void 0 ? t : -a), n = ((i = this.orthoTop) !== null && i !== void 0 ? i : o) - ((s = this.orthoBottom) !== null && s !== void 0 ? s : -o);
    }
    return r * n;
  }
  set orthoLeft(e) {
    this._orthoLeft = e;
    for (const t of this._rigCameras)
      t.orthoLeft = e;
  }
  get orthoLeft() {
    return this._orthoLeft;
  }
  set orthoRight(e) {
    this._orthoRight = e;
    for (const t of this._rigCameras)
      t.orthoRight = e;
  }
  get orthoRight() {
    return this._orthoRight;
  }
  set orthoBottom(e) {
    this._orthoBottom = e;
    for (const t of this._rigCameras)
      t.orthoBottom = e;
  }
  get orthoBottom() {
    return this._orthoBottom;
  }
  set orthoTop(e) {
    this._orthoTop = e;
    for (const t of this._rigCameras)
      t.orthoTop = e;
  }
  get orthoTop() {
    return this._orthoTop;
  }
  set mode(e) {
    this._mode = e;
    for (const t of this._rigCameras)
      t.mode = e;
  }
  get mode() {
    return this._mode;
  }
  /**
   * 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(e, t, i, s = !0) {
    super(e, i), this._position = p.Zero(), this._upVector = p.Up(), 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 = Z.PERSPECTIVE_CAMERA, this.isIntermediate = !1, this.viewport = new oi(0, 0, 1, 1), this.layerMask = 268435455, this.fovMode = Z.FOVMODE_VERTICAL_FIXED, this.cameraRigMode = Z.RIG_MODE_NONE, this.customRenderTargets = new Array(), this.outputRenderTarget = null, this.onViewMatrixChangedObservable = new w(), this.onProjectionMatrixChangedObservable = new w(), this.onAfterCheckInputsObservable = new w(), this.onRestoreStateObservable = new w(), this.isRigCamera = !1, this._rigCameras = new Array(), this._webvrViewMatrix = R.Identity(), this._skipRendering = !1, this._projectionMatrix = new R(), this._postProcesses = new Array(), this._activeMeshes = new We(256), this._globalPosition = p.Zero(), this._computedViewMatrix = R.Identity(), this._doNotComputeProjectionMatrix = !1, this._transformMatrix = R.Zero(), this._refreshFrustumPlanes = !0, this._absoluteRotation = X.Identity(), this._isCamera = !0, this._isLeftCamera = !1, this._isRightCamera = !1, this.getScene().addCamera(this), s && !this.getScene().activeCamera && (this.getScene().activeCamera = this), this.position = t, this.renderPassId = this.getScene().getEngine().createRenderPassId(`Camera ${e}`);
  }
  /**
   * Store current camera state (fov, position, etc..)
   * @returns the camera
   */
  storeState() {
    return this._stateStored = !0, this._storedFov = this.fov, this;
  }
  /**
   * Restores the camera state values if it has been stored. You must call storeState() first
   */
  _restoreStateValues() {
    return this._stateStored ? (this.fov = this._storedFov, !0) : !1;
  }
  /**
   * Restored camera state. You must call storeState() first.
   * @returns true if restored and false otherwise
   */
  restoreState() {
    return this._restoreStateValues() ? (this.onRestoreStateObservable.notifyObservers(this), !0) : !1;
  }
  /**
   * 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(e) {
    let t = "Name: " + this.name;
    if (t += ", type: " + this.getClassName(), this.animations)
      for (let i = 0; i < this.animations.length; i++)
        t += ", animation[0]: " + this.animations[i].toString(e);
    return t;
  }
  /**
   * Automatically tilts the projection plane, using `projectionPlaneTilt`, to correct the perspective effect on vertical lines.
   */
  applyVerticalCorrection() {
    const e = this.absoluteRotation.toEulerAngles();
    this.projectionPlaneTilt = this._scene.useRightHandedSystem ? -e.x : e.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(e) {
    return this._activeMeshes.indexOf(e) !== -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(e = !1) {
    if (e) {
      for (const t of this._postProcesses)
        if (t && !t.isReady())
          return !1;
    }
    return super.isReady(e);
  }
  /** @internal */
  _initCache() {
    super._initCache(), this._cache.position = new p(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE), this._cache.upVector = new p(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.renderWidth = void 0, this._cache.renderHeight = void 0;
  }
  /**
   * @internal
   */
  _updateCache(e) {
    e || super._updateCache(), this._cache.position.copyFrom(this.position), this._cache.upVector.copyFrom(this.upVector);
  }
  /** @internal */
  _isSynchronized() {
    return this._isSynchronizedViewMatrix() && this._isSynchronizedProjectionMatrix();
  }
  /** @internal */
  _isSynchronizedViewMatrix() {
    return super._isSynchronized() ? this._cache.position.equals(this.position) && this._cache.upVector.equals(this.upVector) && this.isSynchronizedWithParent() : !1;
  }
  /** @internal */
  _isSynchronizedProjectionMatrix() {
    let e = this._cache.mode === this.mode && this._cache.minZ === this.minZ && this._cache.maxZ === this.maxZ;
    if (!e)
      return !1;
    const t = this.getEngine();
    return this.mode === Z.PERSPECTIVE_CAMERA ? e = this._cache.fov === this.fov && this._cache.fovMode === this.fovMode && this._cache.aspectRatio === t.getAspectRatio(this) && this._cache.projectionPlaneTilt === this.projectionPlaneTilt : e = this._cache.orthoLeft === this.orthoLeft && this._cache.orthoRight === this.orthoRight && this._cache.orthoBottom === this.orthoBottom && this._cache.orthoTop === this.orthoTop && this._cache.renderWidth === t.getRenderWidth() && this._cache.renderHeight === t.getRenderHeight(), e;
  }
  /**
   * 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(e, t) {
  }
  /**
   * 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(e) {
  }
  /**
   * Update the camera state according to the different inputs gathered during the frame.
   */
  update() {
    this._checkInputs(), this.cameraRigMode !== Z.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 e = 0; e < this._postProcesses.length; e++)
      if (this._postProcesses[e] !== null)
        return this._postProcesses[e];
    return null;
  }
  _cascadePostProcessesToRigCams() {
    const e = this._getFirstPostProcess();
    e && e.markTextureDirty();
    for (let t = 0, i = this._rigCameras.length; t < i; t++) {
      const s = this._rigCameras[t], r = s._rigPostProcess;
      r ? (r.getEffectName() === "pass" && (s.isIntermediate = this._postProcesses.length === 0), s._postProcesses = this._postProcesses.slice(0).concat(r), r.markTextureDirty()) : s._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(e, t = null) {
    return !e.isReusable() && this._postProcesses.indexOf(e) > -1 ? (S.Error("You're trying to reuse a post process not defined as reusable."), 0) : (t == null || t < 0 ? this._postProcesses.push(e) : this._postProcesses[t] === null ? this._postProcesses[t] = e : this._postProcesses.splice(t, 0, e), this._cascadePostProcessesToRigCams(), this._scene.prePassRenderer && this._scene.prePassRenderer.markAsDirty(), this._postProcesses.indexOf(e));
  }
  /**
   * 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(e) {
    const t = this._postProcesses.indexOf(e);
    t !== -1 && (this._postProcesses[t] = null), this._scene.prePassRenderer && this._scene.prePassRenderer.markAsDirty(), this._cascadePostProcessesToRigCams();
  }
  /**
   * Gets the current world matrix of the camera
   */
  getWorldMatrix() {
    return this._isSynchronizedViewMatrix() ? this._worldMatrix : (this.getViewMatrix(), this._worldMatrix);
  }
  /** @internal */
  _getViewMatrix() {
    return R.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(e) {
    return !e && this._isSynchronizedViewMatrix() ? this._computedViewMatrix : (this.updateCache(), this._computedViewMatrix = this._getViewMatrix(), this._currentRenderId = this.getScene().getRenderId(), this._childUpdateId++, this._refreshFrustumPlanes = !0, this._cameraRigParams && this._cameraRigParams.vrPreViewMatrix && this._computedViewMatrix.multiplyToRef(this._cameraRigParams.vrPreViewMatrix, this._computedViewMatrix), this.parent && this.parent.onViewMatrixChangedObservable && this.parent.onViewMatrixChangedObservable.notifyObservers(this.parent), this.onViewMatrixChangedObservable.notifyObservers(this), this._computedViewMatrix.invertToRef(this._worldMatrix), 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(e) {
    this._doNotComputeProjectionMatrix = !0, e !== void 0 && (this._projectionMatrix = e);
  }
  /**
   * Unfreeze the projection matrix if it has previously been freezed by freezeProjectionMatrix.
   */
  unfreezeProjectionMatrix() {
    this._doNotComputeProjectionMatrix = !1;
  }
  /**
   * 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(e) {
    var t, i, s, r, n, a, o, h;
    if (this._doNotComputeProjectionMatrix || !e && this._isSynchronizedProjectionMatrix())
      return this._projectionMatrix;
    this._cache.mode = this.mode, this._cache.minZ = this.minZ, this._cache.maxZ = this.maxZ, this._refreshFrustumPlanes = !0;
    const c = this.getEngine(), u = this.getScene(), d = c.useReverseDepthBuffer;
    if (this.mode === Z.PERSPECTIVE_CAMERA) {
      this._cache.fov = this.fov, this._cache.fovMode = this.fovMode, this._cache.aspectRatio = c.getAspectRatio(this), this._cache.projectionPlaneTilt = this.projectionPlaneTilt, this.minZ <= 0 && (this.minZ = 0.1);
      let g;
      u.useRightHandedSystem ? g = R.PerspectiveFovRHToRef : g = R.PerspectiveFovLHToRef, g(this.fov, c.getAspectRatio(this), d ? this.maxZ : this.minZ, d ? this.minZ : this.maxZ, this._projectionMatrix, this.fovMode === Z.FOVMODE_VERTICAL_FIXED, c.isNDCHalfZRange, this.projectionPlaneTilt, d);
    } else {
      const g = c.getRenderWidth() / 2, f = c.getRenderHeight() / 2;
      u.useRightHandedSystem ? R.OrthoOffCenterRHToRef((t = this.orthoLeft) !== null && t !== void 0 ? t : -g, (i = this.orthoRight) !== null && i !== void 0 ? i : g, (s = this.orthoBottom) !== null && s !== void 0 ? s : -f, (r = this.orthoTop) !== null && r !== void 0 ? r : f, d ? this.maxZ : this.minZ, d ? this.minZ : this.maxZ, this._projectionMatrix, c.isNDCHalfZRange) : R.OrthoOffCenterLHToRef((n = this.orthoLeft) !== null && n !== void 0 ? n : -g, (a = this.orthoRight) !== null && a !== void 0 ? a : g, (o = this.orthoBottom) !== null && o !== void 0 ? o : -f, (h = this.orthoTop) !== null && h !== void 0 ? h : f, d ? this.maxZ : this.minZ, d ? this.minZ : this.maxZ, this._projectionMatrix, c.isNDCHalfZRange), this._cache.orthoLeft = this.orthoLeft, this._cache.orthoRight = this.orthoRight, this._cache.orthoBottom = this.orthoBottom, this._cache.orthoTop = this.orthoTop, this._cache.renderWidth = c.getRenderWidth(), this._cache.renderHeight = c.getRenderHeight();
    }
    return this.onProjectionMatrixChangedObservable.notifyObservers(this), this._projectionMatrix;
  }
  /**
   * Gets the transformation matrix (ie. the multiplication of view by projection matrices)
   * @returns a Matrix
   */
  getTransformationMatrix() {
    return this._computedViewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix), this._transformMatrix;
  }
  _updateFrustumPlanes() {
    this._refreshFrustumPlanes && (this.getTransformationMatrix(), this._frustumPlanes ? Xe.GetPlanesToRef(this._transformMatrix, this._frustumPlanes) : this._frustumPlanes = Xe.GetPlanes(this._transformMatrix), this._refreshFrustumPlanes = !1);
  }
  /**
   * Checks if a cullable object (mesh...) is in the camera frustum
   * This checks the bounding box center. See isCompletelyInFrustum for a full bounding check
   * @param target The object to check
   * @param checkRigCameras If the rig cameras should be checked (eg. with webVR camera both eyes should be checked) (Default: false)
   * @returns true if the object is in frustum otherwise false
   */
  isInFrustum(e, t = !1) {
    if (this._updateFrustumPlanes(), t && this.rigCameras.length > 0) {
      let i = !1;
      return this.rigCameras.forEach((s) => {
        s._updateFrustumPlanes(), i = i || e.isInFrustum(s._frustumPlanes);
      }), i;
    } else
      return e.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(e) {
    return this._updateFrustumPlanes(), e.isCompletelyInFrustum(this._frustumPlanes);
  }
  /**
   * Gets a ray in the forward direction from the camera.
   * @param length Defines the length of the ray to create
   * @param transform Defines the transform to apply to the ray, by default the world matrix is used to create a workd space ray
   * @param origin Defines the start point of the ray which defaults to the camera position
   * @returns the forward ray
   */
  // eslint-disable-next-line @typescript-eslint/no-unused-vars
  getForwardRay(e = 100, t, i) {
    throw Y("Ray");
  }
  /**
   * Gets a ray in the forward direction from the camera.
   * @param refRay the ray to (re)use when setting the values
   * @param length Defines the length of the ray to create
   * @param transform Defines the transform to apply to the ray, by default the world matrx is used to create a workd space ray
   * @param origin Defines the start point of the ray which defaults to the camera position
   * @returns the forward ray
   */
  // eslint-disable-next-line @typescript-eslint/no-unused-vars
  getForwardRayToRef(e, t = 100, i, s) {
    throw Y("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(e, t = !1) {
    for (this.onViewMatrixChangedObservable.clear(), this.onProjectionMatrixChangedObservable.clear(), this.onAfterCheckInputsObservable.clear(), this.onRestoreStateObservable.clear(), this.inputs && this.inputs.clear(), this.getScene().stopAnimation(this), this.getScene().removeCamera(this); this._rigCameras.length > 0; ) {
      const s = this._rigCameras.pop();
      s && s.dispose();
    }
    if (this._parentContainer) {
      const s = this._parentContainer.cameras.indexOf(this);
      s > -1 && this._parentContainer.cameras.splice(s, 1), this._parentContainer = null;
    }
    if (this._rigPostProcess)
      this._rigPostProcess.dispose(this), this._rigPostProcess = null, this._postProcesses.length = 0;
    else if (this.cameraRigMode !== Z.RIG_MODE_NONE)
      this._rigPostProcess = null, this._postProcesses.length = 0;
    else {
      let s = this._postProcesses.length;
      for (; --s >= 0; ) {
        const r = this._postProcesses[s];
        r && r.dispose(this);
      }
    }
    let i = this.customRenderTargets.length;
    for (; --i >= 0; )
      this.customRenderTargets[i].dispose();
    this.customRenderTargets.length = 0, this._activeMeshes.dispose(), this.getScene().getEngine().releaseRenderPassId(this.renderPassId), super.dispose(e, t);
  }
  /**
   * 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() {
    return this._rigCameras.length < 1 ? null : this._rigCameras[0];
  }
  /**
   * Gets the right camera of a rig setup in case of Rigged Camera
   */
  get rightCamera() {
    return this._rigCameras.length < 2 ? null : this._rigCameras[1];
  }
  /**
   * Gets the left camera target of a rig setup in case of Rigged Camera
   * @returns the target position
   */
  getLeftTarget() {
    return this._rigCameras.length < 1 ? null : this._rigCameras[0].getTarget();
  }
  /**
   * Gets the right camera target of a rig setup in case of Rigged Camera
   * @returns the target position
   */
  getRightTarget() {
    return this._rigCameras.length < 2 ? null : this._rigCameras[1].getTarget();
  }
  /**
   * @internal
   */
  setCameraRigMode(e, t) {
    if (this.cameraRigMode !== e) {
      for (; this._rigCameras.length > 0; ) {
        const i = this._rigCameras.pop();
        i && i.dispose();
      }
      if (this.cameraRigMode = e, this._cameraRigParams = {}, this._cameraRigParams.interaxialDistance = t.interaxialDistance || 0.0637, this._cameraRigParams.stereoHalfAngle = k.ToRadians(this._cameraRigParams.interaxialDistance / 0.0637), this.cameraRigMode !== Z.RIG_MODE_NONE) {
        const i = this.createRigCamera(this.name + "_L", 0);
        i && (i._isLeftCamera = !0);
        const s = this.createRigCamera(this.name + "_R", 1);
        s && (s._isRightCamera = !0), i && s && (this._rigCameras.push(i), this._rigCameras.push(s));
      }
      this._setRigMode(t), this._cascadePostProcessesToRigCams(), this.update();
    }
  }
  // eslint-disable-next-line @typescript-eslint/no-unused-vars
  _setRigMode(e) {
  }
  /** @internal */
  _getVRProjectionMatrix() {
    return R.PerspectiveFovLHToRef(this._cameraRigParams.vrMetrics.aspectRatioFov, this._cameraRigParams.vrMetrics.aspectRatio, this.minZ, this.maxZ, this._cameraRigParams.vrWorkMatrix, !0, this.getEngine().isNDCHalfZRange), this._cameraRigParams.vrWorkMatrix.multiplyToRef(this._cameraRigParams.vrHMatrix, this._projectionMatrix), this._projectionMatrix;
  }
  _updateCameraRotationMatrix() {
  }
  _updateWebVRCameraRotationMatrix() {
  }
  /**
   * This function MUST be overwritten by the different WebVR cameras available.
   * The context in which it is running is the RIG camera. So 'this' is the TargetCamera, left or right.
   * @internal
   */
  _getWebVRProjectionMatrix() {
    return R.Identity();
  }
  /**
   * This function MUST be overwritten by the different WebVR cameras available.
   * The context in which it is running is the RIG camera. So 'this' is the TargetCamera, left or right.
   * @internal
   */
  _getWebVRViewMatrix() {
    return R.Identity();
  }
  /**
   * @internal
   */
  setCameraRigParameter(e, t) {
    this._cameraRigParams || (this._cameraRigParams = {}), this._cameraRigParams[e] = t, e === "interaxialDistance" && (this._cameraRigParams.stereoHalfAngle = k.ToRadians(t / 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(e, t) {
    return null;
  }
  /**
   * May need to be overridden by children
   * @internal
   */
  _updateRigCameras() {
    for (let e = 0; e < this._rigCameras.length; e++)
      this._rigCameras[e].minZ = this.minZ, this._rigCameras[e].maxZ = this.maxZ, this._rigCameras[e].fov = this.fov, this._rigCameras[e].upVector.copyFrom(this.upVector);
    this.cameraRigMode === Z.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 e = he.Serialize(this);
    return e.uniqueId = this.uniqueId, e.type = this.getClassName(), this.parent && this.parent._serializeAsParent(e), this.inputs && this.inputs.serialize(e), he.AppendSerializedAnimations(this, e), e.ranges = this.serializeAnimationRanges(), e.isEnabled = this.isEnabled(), e;
  }
  /**
   * 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(e, t = null) {
    const i = he.Clone(Z.GetConstructorFromName(this.getClassName(), e, this.getScene(), this.interaxialDistance, this.isStereoscopicSideBySide), this);
    return i.name = e, i.parent = t, this.onClonedObservable.notifyObservers(i), i;
  }
  /**
   * 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(e) {
    const t = p.Zero();
    return this.getDirectionToRef(e, t), t;
  }
  /**
   * Returns the current camera absolute rotation
   */
  get absoluteRotation() {
    return this.getWorldMatrix().decompose(void 0, this._absoluteRotation), 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(e, t) {
    p.TransformNormalToRef(e, this.getWorldMatrix(), t);
  }
  /**
   * 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(e, t, i, s = 0, r = !0) {
    const n = Ne.Construct(e, t, i, {
      // eslint-disable-next-line @typescript-eslint/naming-convention
      interaxial_distance: s,
      isStereoscopicSideBySide: r
    });
    return n || (() => Z._CreateDefaultParsedCamera(t, i));
  }
  /**
   * 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(e, t) {
    const i = e.type, s = Z.GetConstructorFromName(i, e.name, t, e.interaxial_distance, e.isStereoscopicSideBySide), r = he.Parse(s, e, t);
    if (e.parentId !== void 0 && (r._waitingParentId = e.parentId), e.parentInstanceIndex !== void 0 && (r._waitingParentInstanceIndex = e.parentInstanceIndex), r.inputs && (r.inputs.parse(e), r._setupInputs()), e.upVector && (r.upVector = p.FromArray(e.upVector)), r.setPosition && (r.position.copyFromFloats(0, 0, 0), r.setPosition(p.FromArray(e.position))), e.target && r.setTarget && r.setTarget(p.FromArray(e.target)), e.cameraRigMode) {
      const n = e.interaxial_distance ? { interaxialDistance: e.interaxial_distance } : {};
      r.setCameraRigMode(e.cameraRigMode, n);
    }
    if (e.animations) {
      for (let n = 0; n < e.animations.length; n++) {
        const a = e.animations[n], o = ii("BABYLON.Animation");
        o && r.animations.push(o.Parse(a));
      }
      Ne.ParseAnimationRanges(r, e, t);
    }
    return e.autoAnimate && t.beginAnimation(r, e.autoAnimateFrom, e.autoAnimateTo, e.autoAnimateLoop, e.autoAnimateSpeed || 1), e.isEnabled !== void 0 && r.setEnabled(e.isEnabled), r;
  }
}
Z._CreateDefaultParsedCamera = (l, e) => {
  throw Y("UniversalCamera");
};
Z.PERSPECTIVE_CAMERA = 0;
Z.ORTHOGRAPHIC_CAMERA = 1;
Z.FOVMODE_VERTICAL_FIXED = 0;
Z.FOVMODE_HORIZONTAL_FIXED = 1;
Z.RIG_MODE_NONE = 0;
Z.RIG_MODE_STEREOSCOPIC_ANAGLYPH = 10;
Z.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL = 11;
Z.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED = 12;
Z.RIG_MODE_STEREOSCOPIC_OVERUNDER = 13;
Z.RIG_MODE_STEREOSCOPIC_INTERLACED = 14;
Z.RIG_MODE_VR = 20;
Z.RIG_MODE_WEBVR = 21;
Z.RIG_MODE_CUSTOM = 22;
Z.ForceAttachControlToAlwaysPreventDefault = !1;
F([
  Ht("position")
], Z.prototype, "_position", void 0);
F([
  Ht("upVector")
], Z.prototype, "_upVector", void 0);
F([
  B()
], Z.prototype, "orthoLeft", null);
F([
  B()
], Z.prototype, "orthoRight", null);
F([
  B()
], Z.prototype, "orthoBottom", null);
F([
  B()
], Z.prototype, "orthoTop", null);
F([
  B()
], Z.prototype, "fov", void 0);
F([
  B()
], Z.prototype, "projectionPlaneTilt", void 0);
F([
  B()
], Z.prototype, "minZ", void 0);
F([
  B()
], Z.prototype, "maxZ", void 0);
F([
  B()
], Z.prototype, "inertia", void 0);
F([
  B()
], Z.prototype, "mode", null);
F([
  B()
], Z.prototype, "layerMask", void 0);
F([
  B()
], Z.prototype, "fovMode", void 0);
F([
  B()
], Z.prototype, "cameraRigMode", void 0);
F([
  B()
], Z.prototype, "interaxialDistance", void 0);
F([
  B()
], Z.prototype, "isStereoscopicSideBySide", void 0);
class ie {
  /**
   * Creates a new ray
   * @param origin origin point
   * @param direction direction
   * @param length length of the ray
   */
  constructor(e, t, i = Number.MAX_VALUE) {
    this.origin = e, this.direction = t, this.length = i;
  }
  // Methods
  /**
   * Clone the current ray
   * @returns a new ray
   */
  clone() {
    return new ie(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(e, t, i = 0) {
    const s = ie._TmpVector3[0].copyFromFloats(e.x - i, e.y - i, e.z - i), r = ie._TmpVector3[1].copyFromFloats(t.x + i, t.y + i, t.z + i);
    let n = 0, a = Number.MAX_VALUE, o, h, c, u;
    if (Math.abs(this.direction.x) < 1e-7) {
      if (this.origin.x < s.x || this.origin.x > r.x)
        return !1;
    } else if (o = 1 / this.direction.x, h = (s.x - this.origin.x) * o, c = (r.x - this.origin.x) * o, c === -1 / 0 && (c = 1 / 0), h > c && (u = h, h = c, c = u), n = Math.max(h, n), a = Math.min(c, a), n > a)
      return !1;
    if (Math.abs(this.direction.y) < 1e-7) {
      if (this.origin.y < s.y || this.origin.y > r.y)
        return !1;
    } else if (o = 1 / this.direction.y, h = (s.y - this.origin.y) * o, c = (r.y - this.origin.y) * o, c === -1 / 0 && (c = 1 / 0), h > c && (u = h, h = c, c = u), n = Math.max(h, n), a = Math.min(c, a), n > a)
      return !1;
    if (Math.abs(this.direction.z) < 1e-7) {
      if (this.origin.z < s.z || this.origin.z > r.z)
        return !1;
    } else if (o = 1 / this.direction.z, h = (s.z - this.origin.z) * o, c = (r.z - this.origin.z) * o, c === -1 / 0 && (c = 1 / 0), h > c && (u = h, h = c, c = u), n = Math.max(h, n), a = Math.min(c, a), n > a)
      return !1;
    return !0;
  }
  /**
   * Checks if the ray intersects a box
   * This does not account for the ray lenght by design to improve perfs.
   * @param box the bounding box to check
   * @param intersectionTreshold extra extend to be added to the BoundingBox in all direction
   * @returns if the box was hit
   */
  intersectsBox(e, t = 0) {
    return this.intersectsBoxMinMax(e.minimum, e.maximum, t);
  }
  /**
   * 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(e, t = 0) {
    const i = e.center.x - this.origin.x, s = e.center.y - this.origin.y, r = e.center.z - this.origin.z, n = i * i + s * s + r * r, a = e.radius + t, o = a * a;
    if (n <= o)
      return !0;
    const h = i * this.direction.x + s * this.direction.y + r * this.direction.z;
    return h < 0 ? !1 : n - h * h <= o;
  }
  /**
   * If the ray hits a triange
   * @param vertex0 triangle vertex
   * @param vertex1 triangle vertex
   * @param vertex2 triangle vertex
   * @returns intersection information if hit
   */
  intersectsTriangle(e, t, i) {
    const s = ie._TmpVector3[0], r = ie._TmpVector3[1], n = ie._TmpVector3[2], a = ie._TmpVector3[3], o = ie._TmpVector3[4];
    t.subtractToRef(e, s), i.subtractToRef(e, r), p.CrossToRef(this.direction, r, n);
    const h = p.Dot(s, n);
    if (h === 0)
      return null;
    const c = 1 / h;
    this.origin.subtractToRef(e, a);
    const u = p.Dot(a, n) * c;
    if (u < 0 || u > 1)
      return null;
    p.CrossToRef(a, s, o);
    const d = p.Dot(this.direction, o) * c;
    if (d < 0 || u + d > 1)
      return null;
    const g = p.Dot(r, o) * c;
    return g > this.length ? null : new xi(1 - u - d, u, g);
  }
  /**
   * Checks if ray intersects a plane
   * @param plane the plane to check
   * @returns the distance away it was hit
   */
  intersectsPlane(e) {
    let t;
    const i = p.Dot(e.normal, this.direction);
    if (Math.abs(i) < 999999997475243e-21)
      return null;
    {
      const s = p.Dot(e.normal, this.origin);
      return t = (-e.d - s) / i, t < 0 ? t < -999999997475243e-21 ? null : 0 : t;
    }
  }
  /**
   * 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(e, t = 0) {
    switch (e) {
      case "y": {
        const i = (this.origin.y - t) / this.direction.y;
        return i > 0 ? null : new p(this.origin.x + this.direction.x * -i, t, this.origin.z + this.direction.z * -i);
      }
      case "x": {
        const i = (this.origin.x - t) / this.direction.x;
        return i > 0 ? null : new p(t, this.origin.y + this.direction.y * -i, this.origin.z + this.direction.z * -i);
      }
      case "z": {
        const i = (this.origin.z - t) / this.direction.z;
        return i > 0 ? null : new p(this.origin.x + this.direction.x * -i, this.origin.y + this.direction.y * -i, t);
      }
      default:
        return null;
    }
  }
  /**
   * Checks if ray intersects a mesh
   * @param mesh the mesh to check
   * @param fastCheck defines if the first intersection will be used (and not the closest)
   * @returns picking info of the intersection
   */
  intersectsMesh(e, t) {
    const i = C.Matrix[0];
    return e.getWorldMatrix().invertToRef(i), this._tmpRay ? ie.TransformToRef(this, i, this._tmpRay) : this._tmpRay = ie.Transform(this, i), e.intersects(this._tmpRay, t);
  }
  /**
   * 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(e, t, i) {
    i ? i.length = 0 : i = [];
    for (let s = 0; s < e.length; s++) {
      const r = this.intersectsMesh(e[s], t);
      r.hit && i.push(r);
    }
    return i.sort(this._comparePickingInfo), i;
  }
  _comparePickingInfo(e, t) {
    return e.distance < t.distance ? -1 : e.distance > t.distance ? 1 : 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(e, t, i) {
    const s = this.origin, r = C.Vector3[0], n = C.Vector3[1], a = C.Vector3[2], o = C.Vector3[3];
    t.subtractToRef(e, r), this.direction.scaleToRef(ie._Rayl, a), s.addToRef(a, n), e.subtractToRef(s, o);
    const h = p.Dot(r, r), c = p.Dot(r, a), u = p.Dot(a, a), d = p.Dot(r, o), g = p.Dot(a, o), f = h * u - c * c;
    let m, b = f, T, M = f;
    f < ie._Smallnum ? (m = 0, b = 1, T = g, M = u) : (m = c * g - u * d, T = h * g - c * d, m < 0 ? (m = 0, T = g, M = u) : m > b && (m = b, T = g + c, M = u)), T < 0 ? (T = 0, -d < 0 ? m = 0 : -d > h ? m = b : (m = -d, b = h)) : T > M && (T = M, -d + c < 0 ? m = 0 : -d + c > h ? m = b : (m = -d + c, b = h));
    const v = Math.abs(m) < ie._Smallnum ? 0 : m / b, A = Math.abs(T) < ie._Smallnum ? 0 : T / M, E = C.Vector3[4];
    a.scaleToRef(A, E);
    const y = C.Vector3[5];
    r.scaleToRef(v, y), y.addInPlace(o);
    const x = C.Vector3[6];
    return y.subtractToRef(E, x), A > 0 && A <= this.length && x.lengthSquared() < i * i ? y.length() : -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(e, t, i, s, r, n, a, o = !1) {
    if (o) {
      ie._RayDistant || (ie._RayDistant = ie.Zero()), ie._RayDistant.unprojectRayToRef(e, t, i, s, R.IdentityReadOnly, n, a);
      const h = C.Matrix[0];
      r.invertToRef(h), ie.TransformToRef(ie._RayDistant, h, this);
    } else
      this.unprojectRayToRef(e, t, i, s, r, n, a);
    return this;
  }
  // Statics
  /**
   * Creates a ray with origin and direction of 0,0,0
   * @returns the new ray
   */
  static Zero() {
    return new ie(p.Zero(), p.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(e, t, i, s, r, n, a) {
    return ie.Zero().update(e, t, i, s, r, n, a);
  }
  /**
   * 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(e, t, i = R.IdentityReadOnly) {
    const s = t.subtract(e), r = Math.sqrt(s.x * s.x + s.y * s.y + s.z * s.z);
    return s.normalize(), ie.Transform(new ie(e, s, r), i);
  }
  /**
   * Transforms a ray by a matrix
   * @param ray ray to transform
   * @param matrix matrix to apply
   * @returns the resulting new ray
   */
  static Transform(e, t) {
    const i = new ie(new p(0, 0, 0), new p(0, 0, 0));
    return ie.TransformToRef(e, t, i), i;
  }
  /**
   * Transforms a ray by a matrix
   * @param ray ray to transform
   * @param matrix matrix to apply
   * @param result ray to store result in
   */
  static TransformToRef(e, t, i) {
    p.TransformCoordinatesToRef(e.origin, t, i.origin), p.TransformNormalToRef(e.direction, t, i.direction), i.length = e.length;
    const s = i.direction, r = s.length();
    if (!(r === 0 || r === 1)) {
      const n = 1 / r;
      s.x *= n, s.y *= n, s.z *= n, i.length *= r;
    }
  }
  /**
   * 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(e, t, i, s, r, n, a) {
    var o;
    const h = C.Matrix[0];
    r.multiplyToRef(n, h), h.multiplyToRef(a, h), h.invert();
    const c = C.Vector3[0];
    c.x = e / i * 2 - 1, c.y = -(t / s * 2 - 1), c.z = !((o = J.LastCreatedEngine) === null || o === void 0) && o.isNDCHalfZRange ? 0 : -1;
    const u = C.Vector3[1].copyFromFloats(c.x, c.y, 1 - 1e-8), d = C.Vector3[2], g = C.Vector3[3];
    p._UnprojectFromInvertedMatrixToRef(c, h, d), p._UnprojectFromInvertedMatrixToRef(u, h, g), this.origin.copyFrom(d), g.subtractToRef(d, this.direction), this.direction.normalize();
  }
}
ie._TmpVector3 = Ee.BuildArray(6, p.Zero);
ie._RayDistant = ie.Zero();
ie._Smallnum = 1e-8;
ie._Rayl = 1e9;
Q.prototype.createPickingRay = function(l, e, t, i, s = !1) {
  const r = ie.Zero();
  return this.createPickingRayToRef(l, e, t, r, i, s), r;
};
Q.prototype.createPickingRayToRef = function(l, e, t, i, s, r = !1, n = !1) {
  const a = this.getEngine();
  if (!s) {
    if (!this.activeCamera)
      return this;
    s = this.activeCamera;
  }
  const h = s.viewport.toGlobal(a.getRenderWidth(), a.getRenderHeight());
  return l = l / a.getHardwareScalingLevel() - h.x, e = e / a.getHardwareScalingLevel() - (a.getRenderHeight() - h.y - h.height), i.update(l, e, h.width, h.height, t || R.IdentityReadOnly, r ? R.IdentityReadOnly : s.getViewMatrix(), s.getProjectionMatrix(), n), this;
};
Q.prototype.createPickingRayInCameraSpace = function(l, e, t) {
  const i = ie.Zero();
  return this.createPickingRayInCameraSpaceToRef(l, e, i, t), i;
};
Q.prototype.createPickingRayInCameraSpaceToRef = function(l, e, t, i) {
  if (!ut)
    return this;
  const s = this.getEngine();
  if (!i) {
    if (!this.activeCamera)
      throw new Error("Active camera not set");
    i = this.activeCamera;
  }
  const n = i.viewport.toGlobal(s.getRenderWidth(), s.getRenderHeight()), a = R.Identity();
  return l = l / s.getHardwareScalingLevel() - n.x, e = e / s.getHardwareScalingLevel() - (s.getRenderHeight() - n.y - n.height), t.update(l, e, n.width, n.height, a, a, i.getProjectionMatrix()), this;
};
Q.prototype._internalPickForMesh = function(l, e, t, i, s, r, n, a) {
  const o = e(i, t.enableDistantPicking), h = t.intersects(o, s, n, r, i, a);
  return !h || !h.hit || !s && l != null && h.distance >= l.distance ? null : h;
};
Q.prototype._internalPick = function(l, e, t, i, s) {
  let r = null;
  const n = !!(this.activeCameras && this.activeCameras.length > 1 && this.cameraToUseForPointers !== this.activeCamera), a = this.cameraToUseForPointers || this.activeCamera;
  for (let o = 0; o < this.meshes.length; o++) {
    const h = this.meshes[o];
    if (e) {
      if (!e(h))
        continue;
    } else if (!h.isEnabled() || !h.isVisible || !h.isPickable)
      continue;
    const c = n && h.isWorldMatrixCameraDependent(), u = h.computeWorldMatrix(c, a);
    if (h.hasThinInstances && h.thinInstanceEnablePicking) {
      const d = this._internalPickForMesh(r, l, h, u, !0, !0, s);
      if (d) {
        if (i)
          return d;
        const g = C.Matrix[1], f = h.thinInstanceGetWorldMatrices();
        for (let m = 0; m < f.length; m++) {
          f[m].multiplyToRef(u, g);
          const T = this._internalPickForMesh(r, l, h, g, t, i, s, !0);
          if (T && (r = T, r.thinInstanceIndex = m, t))
            return r;
        }
      }
    } else {
      const d = this._internalPickForMesh(r, l, h, u, t, i, s);
      if (d && (r = d, t))
        return r;
    }
  }
  return r || new ut();
};
Q.prototype._internalMultiPick = function(l, e, t) {
  if (!ut)
    return null;
  const i = new Array(), s = !!(this.activeCameras && this.activeCameras.length > 1 && this.cameraToUseForPointers !== this.activeCamera), r = this.cameraToUseForPointers || this.activeCamera;
  for (let n = 0; n < this.meshes.length; n++) {
    const a = this.meshes[n];
    if (e) {
      if (!e(a))
        continue;
    } else if (!a.isEnabled() || !a.isVisible || !a.isPickable)
      continue;
    const o = s && a.isWorldMatrixCameraDependent(), h = a.computeWorldMatrix(o, r);
    if (a.hasThinInstances && a.thinInstanceEnablePicking) {
      if (this._internalPickForMesh(null, l, a, h, !0, !0, t)) {
        const u = C.Matrix[1], d = a.thinInstanceGetWorldMatrices();
        for (let g = 0; g < d.length; g++) {
          d[g].multiplyToRef(h, u);
          const m = this._internalPickForMesh(null, l, a, u, !1, !1, t, !0);
          m && (m.thinInstanceIndex = g, i.push(m));
        }
      }
    } else {
      const c = this._internalPickForMesh(null, l, a, h, !1, !1, t);
      c && i.push(c);
    }
  }
  return i;
};
Q.prototype.pickWithBoundingInfo = function(l, e, t, i, s) {
  if (!ut)
    return null;
  const r = this._internalPick((n) => (this._tempPickingRay || (this._tempPickingRay = ie.Zero()), this.createPickingRayToRef(l, e, n, this._tempPickingRay, s || null), this._tempPickingRay), t, i, !0);
  return r && (r.ray = this.createPickingRay(l, e, R.Identity(), s || null)), r;
};
Object.defineProperty(Q.prototype, "_pickingAvailable", {
  get: () => !0,
  enumerable: !1,
  configurable: !1
});
Q.prototype.pick = function(l, e, t, i, s, r, n = !1) {
  const a = this._internalPick((o, h) => (this._tempPickingRay || (this._tempPickingRay = ie.Zero()), this.createPickingRayToRef(l, e, o, this._tempPickingRay, s || null, !1, h), this._tempPickingRay), t, i, !1, r);
  return a && (a.ray = this.createPickingRay(l, e, R.Identity(), s || null)), a;
};
Q.prototype.pickWithRay = function(l, e, t, i) {
  const s = this._internalPick((r) => (this._pickWithRayInverseMatrix || (this._pickWithRayInverseMatrix = R.Identity()), r.invertToRef(this._pickWithRayInverseMatrix), this._cachedRayForTransform || (this._cachedRayForTransform = ie.Zero()), ie.TransformToRef(l, this._pickWithRayInverseMatrix, this._cachedRayForTransform), this._cachedRayForTransform), e, t, !1, i);
  return s && (s.ray = l), s;
};
Q.prototype.multiPick = function(l, e, t, i, s) {
  return this._internalMultiPick((r) => this.createPickingRay(l, e, r, i || null), t, s);
};
Q.prototype.multiPickWithRay = function(l, e, t) {
  return this._internalMultiPick((i) => (this._pickWithRayInverseMatrix || (this._pickWithRayInverseMatrix = R.Identity()), i.invertToRef(this._pickWithRayInverseMatrix), this._cachedRayForTransform || (this._cachedRayForTransform = ie.Zero()), ie.TransformToRef(l, this._pickWithRayInverseMatrix, this._cachedRayForTransform), this._cachedRayForTransform), e, t);
};
Z.prototype.getForwardRay = function(l = 100, e, t) {
  return this.getForwardRayToRef(new ie(p.Zero(), p.Zero(), l), l, e, t);
};
Z.prototype.getForwardRayToRef = function(l, e = 100, t, i) {
  return t || (t = this.getWorldMatrix()), l.length = e, i ? l.origin.copyFrom(i) : l.origin.copyFrom(this.position), C.Vector3[2].set(0, 0, this._scene.useRightHandedSystem ? -1 : 1), p.TransformNormalToRef(C.Vector3[2], t, C.Vector3[3]), p.NormalizeToRef(C.Vector3[3], l.direction), l;
};
function Ei(l, e, t) {
  try {
    const i = l.next();
    i.done ? e(i) : i.value ? i.value.then(() => {
      i.value = void 0, e(i);
    }, t) : e(i);
  } catch (i) {
    t(i);
  }
}
function gr(l = 25) {
  let e;
  return (t, i, s) => {
    const r = performance.now();
    e === void 0 || r - e > l ? (e = r, setTimeout(() => {
      Ei(t, i, s);
    }, 0)) : Ei(t, i, s);
  };
}
function _s(l, e, t, i, s) {
  const r = () => {
    let n;
    const a = (o) => {
      o.done ? t(o.value) : n === void 0 ? n = !0 : r();
    };
    do
      n = void 0, !s || !s.aborted ? e(l, a, i) : i(new Error("Aborted")), n === void 0 && (n = !1);
    while (n);
  };
  r();
}
function Ui(l, e) {
  let t;
  return _s(l, Ei, (i) => t = i, (i) => {
    throw i;
  }, e), t;
}
function pr(l, e, t) {
  return new Promise((i, s) => {
    _s(l, e, i, s, t);
  });
}
function mr(l, e) {
  return (...t) => Ui(l(...t), e);
}
class q {
  constructor() {
    this._applyTo = mr(this._applyToCoroutine.bind(this));
  }
  /**
   * 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(e, t) {
    switch (e.length || S.Warn(`Setting vertex data kind '${t}' with an empty array`), t) {
      case _.PositionKind:
        this.positions = e;
        break;
      case _.NormalKind:
        this.normals = e;
        break;
      case _.TangentKind:
        this.tangents = e;
        break;
      case _.UVKind:
        this.uvs = e;
        break;
      case _.UV2Kind:
        this.uvs2 = e;
        break;
      case _.UV3Kind:
        this.uvs3 = e;
        break;
      case _.UV4Kind:
        this.uvs4 = e;
        break;
      case _.UV5Kind:
        this.uvs5 = e;
        break;
      case _.UV6Kind:
        this.uvs6 = e;
        break;
      case _.ColorKind:
        this.colors = e;
        break;
      case _.MatricesIndicesKind:
        this.matricesIndices = e;
        break;
      case _.MatricesWeightsKind:
        this.matricesWeights = e;
        break;
      case _.MatricesIndicesExtraKind:
        this.matricesIndicesExtra = e;
        break;
      case _.MatricesWeightsExtraKind:
        this.matricesWeightsExtra = e;
        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(e, t) {
    return this._applyTo(e, t, !1), 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(e, t) {
    return this._applyTo(e, t, !1), this;
  }
  /**
   * Updates the associated mesh
   * @param mesh the mesh to be updated
   * @returns VertexData
   */
  updateMesh(e) {
    return this._update(e), this;
  }
  /**
   * Updates the associated geometry
   * @param geometry the geometry to be updated
   * @returns VertexData.
   */
  updateGeometry(e) {
    return this._update(e), this;
  }
  /**
   * @internal
   */
  *_applyToCoroutine(e, t = !1, i) {
    return this.positions && (e.setVerticesData(_.PositionKind, this.positions, t), i && (yield)), this.normals && (e.setVerticesData(_.NormalKind, this.normals, t), i && (yield)), this.tangents && (e.setVerticesData(_.TangentKind, this.tangents, t), i && (yield)), this.uvs && (e.setVerticesData(_.UVKind, this.uvs, t), i && (yield)), this.uvs2 && (e.setVerticesData(_.UV2Kind, this.uvs2, t), i && (yield)), this.uvs3 && (e.setVerticesData(_.UV3Kind, this.uvs3, t), i && (yield)), this.uvs4 && (e.setVerticesData(_.UV4Kind, this.uvs4, t), i && (yield)), this.uvs5 && (e.setVerticesData(_.UV5Kind, this.uvs5, t), i && (yield)), this.uvs6 && (e.setVerticesData(_.UV6Kind, this.uvs6, t), i && (yield)), this.colors && (e.setVerticesData(_.ColorKind, this.colors, t), i && (yield)), this.matricesIndices && (e.setVerticesData(_.MatricesIndicesKind, this.matricesIndices, t), i && (yield)), this.matricesWeights && (e.setVerticesData(_.MatricesWeightsKind, this.matricesWeights, t), i && (yield)), this.matricesIndicesExtra && (e.setVerticesData(_.MatricesIndicesExtraKind, this.matricesIndicesExtra, t), i && (yield)), this.matricesWeightsExtra && (e.setVerticesData(_.MatricesWeightsExtraKind, this.matricesWeightsExtra, t), i && (yield)), this.indices ? (e.setIndices(this.indices, null, t), i && (yield)) : e.setIndices([], null), this;
  }
  _update(e, t, i) {
    return this.positions && e.updateVerticesData(_.PositionKind, this.positions, t, i), this.normals && e.updateVerticesData(_.NormalKind, this.normals, t, i), this.tangents && e.updateVerticesData(_.TangentKind, this.tangents, t, i), this.uvs && e.updateVerticesData(_.UVKind, this.uvs, t, i), this.uvs2 && e.updateVerticesData(_.UV2Kind, this.uvs2, t, i), this.uvs3 && e.updateVerticesData(_.UV3Kind, this.uvs3, t, i), this.uvs4 && e.updateVerticesData(_.UV4Kind, this.uvs4, t, i), this.uvs5 && e.updateVerticesData(_.UV5Kind, this.uvs5, t, i), this.uvs6 && e.updateVerticesData(_.UV6Kind, this.uvs6, t, i), this.colors && e.updateVerticesData(_.ColorKind, this.colors, t, i), this.matricesIndices && e.updateVerticesData(_.MatricesIndicesKind, this.matricesIndices, t, i), this.matricesWeights && e.updateVerticesData(_.MatricesWeightsKind, this.matricesWeights, t, i), this.matricesIndicesExtra && e.updateVerticesData(_.MatricesIndicesExtraKind, this.matricesIndicesExtra, t, i), this.matricesWeightsExtra && e.updateVerticesData(_.MatricesWeightsExtraKind, this.matricesWeightsExtra, t, i), this.indices && e.setIndices(this.indices, null), this;
  }
  static _TransformVector3Coordinates(e, t, i = 0, s = e.length) {
    const r = C.Vector3[0], n = C.Vector3[1];
    for (let a = i; a < i + s; a += 3)
      p.FromArrayToRef(e, a, r), p.TransformCoordinatesToRef(r, t, n), e[a] = n.x, e[a + 1] = n.y, e[a + 2] = n.z;
  }
  static _TransformVector3Normals(e, t, i = 0, s = e.length) {
    const r = C.Vector3[0], n = C.Vector3[1];
    for (let a = i; a < i + s; a += 3)
      p.FromArrayToRef(e, a, r), p.TransformNormalToRef(r, t, n), e[a] = n.x, e[a + 1] = n.y, e[a + 2] = n.z;
  }
  static _TransformVector4Normals(e, t, i = 0, s = e.length) {
    const r = C.Vector4[0], n = C.Vector4[1];
    for (let a = i; a < i + s; a += 4)
      de.FromArrayToRef(e, a, r), de.TransformNormalToRef(r, t, n), e[a] = n.x, e[a + 1] = n.y, e[a + 2] = n.z, e[a + 3] = n.w;
  }
  static _FlipFaces(e, t = 0, i = e.length) {
    for (let s = t; s < t + i; s += 3) {
      const r = e[s + 1];
      e[s + 1] = e[s + 2], e[s + 2] = r;
    }
  }
  /**
   * Transforms each position and each normal of the vertexData according to the passed Matrix
   * @param matrix the transforming matrix
   * @returns the VertexData
   */
  transform(e) {
    const t = e.determinant() < 0;
    return this.positions && q._TransformVector3Coordinates(this.positions, e), this.normals && q._TransformVector3Normals(this.normals, e), this.tangents && q._TransformVector4Normals(this.tangents, e), t && this.indices && q._FlipFaces(this.indices), this;
  }
  /**
   * 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
   * @returns the modified VertexData
   */
  merge(e, t = !1, i = !1) {
    const s = Array.isArray(e) ? e.map((r) => ({ vertexData: r })) : [{ vertexData: e }];
    return Ui(this._mergeCoroutine(void 0, s, t, !1, i));
  }
  /**
   * @internal
   */
  *_mergeCoroutine(e, t, i = !1, s, r) {
    var n, a, o, h;
    this._validate();
    const c = t.map((f) => f.vertexData);
    for (const f of c)
      if (f._validate(), !this.normals != !f.normals || !this.tangents != !f.tangents || !this.uvs != !f.uvs || !this.uvs2 != !f.uvs2 || !this.uvs3 != !f.uvs3 || !this.uvs4 != !f.uvs4 || !this.uvs5 != !f.uvs5 || !this.uvs6 != !f.uvs6 || !this.colors != !f.colors || !this.matricesIndices != !f.matricesIndices || !this.matricesWeights != !f.matricesWeights || !this.matricesIndicesExtra != !f.matricesIndicesExtra || !this.matricesWeightsExtra != !f.matricesWeightsExtra)
        throw new Error("Cannot merge vertex data that do not have the same set of attributes");
    const u = c.reduce((f, m) => {
      var b, T;
      return f + ((T = (b = m.indices) === null || b === void 0 ? void 0 : b.length) !== null && T !== void 0 ? T : 0);
    }, (a = (n = this.indices) === null || n === void 0 ? void 0 : n.length) !== null && a !== void 0 ? a : 0);
    let g = r || c.some((f) => f.indices === this.indices) ? (o = this.indices) === null || o === void 0 ? void 0 : o.slice() : this.indices;
    if (u > 0) {
      let f = (h = g == null ? void 0 : g.length) !== null && h !== void 0 ? h : 0;
      if (g || (g = new Array(u)), g.length !== u) {
        if (Array.isArray(g))
          g.length = u;
        else {
          const b = i || g instanceof Uint32Array ? new Uint32Array(u) : new Uint16Array(u);
          b.set(g), g = b;
        }
        e && e.determinant() < 0 && q._FlipFaces(g, 0, f);
      }
      let m = this.positions ? this.positions.length / 3 : 0;
      for (const { vertexData: b, transform: T } of t)
        if (b.indices) {
          for (let M = 0; M < b.indices.length; M++)
            g[f + M] = b.indices[M] + m;
          T && T.determinant() < 0 && q._FlipFaces(g, f, b.indices.length), m += b.positions.length / 3, f += b.indices.length, s && (yield);
        }
    }
    return this.indices = g, this.positions = q._MergeElement(_.PositionKind, this.positions, e, t.map((f) => [f.vertexData.positions, f.transform])), s && (yield), this.normals = q._MergeElement(_.NormalKind, this.normals, e, t.map((f) => [f.vertexData.normals, f.transform])), s && (yield), this.tangents = q._MergeElement(_.TangentKind, this.tangents, e, t.map((f) => [f.vertexData.tangents, f.transform])), s && (yield), this.uvs = q._MergeElement(_.UVKind, this.uvs, e, t.map((f) => [f.vertexData.uvs, f.transform])), s && (yield), this.uvs2 = q._MergeElement(_.UV2Kind, this.uvs2, e, t.map((f) => [f.vertexData.uvs2, f.transform])), s && (yield), this.uvs3 = q._MergeElement(_.UV3Kind, this.uvs3, e, t.map((f) => [f.vertexData.uvs3, f.transform])), s && (yield), this.uvs4 = q._MergeElement(_.UV4Kind, this.uvs4, e, t.map((f) => [f.vertexData.uvs4, f.transform])), s && (yield), this.uvs5 = q._MergeElement(_.UV5Kind, this.uvs5, e, t.map((f) => [f.vertexData.uvs5, f.transform])), s && (yield), this.uvs6 = q._MergeElement(_.UV6Kind, this.uvs6, e, t.map((f) => [f.vertexData.uvs6, f.transform])), s && (yield), this.colors = q._MergeElement(_.ColorKind, this.colors, e, t.map((f) => [f.vertexData.colors, f.transform])), s && (yield), this.matricesIndices = q._MergeElement(_.MatricesIndicesKind, this.matricesIndices, e, t.map((f) => [f.vertexData.matricesIndices, f.transform])), s && (yield), this.matricesWeights = q._MergeElement(_.MatricesWeightsKind, this.matricesWeights, e, t.map((f) => [f.vertexData.matricesWeights, f.transform])), s && (yield), this.matricesIndicesExtra = q._MergeElement(_.MatricesIndicesExtraKind, this.matricesIndicesExtra, e, t.map((f) => [f.vertexData.matricesIndicesExtra, f.transform])), s && (yield), this.matricesWeightsExtra = q._MergeElement(_.MatricesWeightsExtraKind, this.matricesWeightsExtra, e, t.map((f) => [f.vertexData.matricesWeightsExtra, f.transform])), this;
  }
  static _MergeElement(e, t, i, s) {
    const r = s.filter((o) => o[0] !== null && o[0] !== void 0);
    if (!t && r.length == 0)
      return t;
    if (!t)
      return this._MergeElement(e, r[0][0], r[0][1], r.slice(1));
    const n = r.reduce((o, h) => o + h[0].length, t.length), a = e === _.PositionKind ? q._TransformVector3Coordinates : e === _.NormalKind ? q._TransformVector3Normals : e === _.TangentKind ? q._TransformVector4Normals : () => {
    };
    if (t instanceof Float32Array) {
      const o = new Float32Array(n);
      o.set(t), i && a(o, i, 0, t.length);
      let h = t.length;
      for (const [c, u] of r)
        o.set(c, h), u && a(o, u, h, c.length), h += c.length;
      return o;
    } else {
      const o = new Array(n);
      for (let c = 0; c < t.length; c++)
        o[c] = t[c];
      i && a(o, i, 0, t.length);
      let h = t.length;
      for (const [c, u] of r) {
        for (let d = 0; d < c.length; d++)
          o[h + d] = c[d];
        u && a(o, u, h, c.length), h += c.length;
      }
      return o;
    }
  }
  _validate() {
    if (!this.positions)
      throw new ct("Positions are required", vt.MeshInvalidPositionsError);
    const e = (s, r) => {
      const n = _.DeduceStride(s);
      if (r.length % n !== 0)
        throw new Error("The " + s + "s array count must be a multiple of " + n);
      return r.length / n;
    }, t = e(_.PositionKind, this.positions), i = (s, r) => {
      const n = e(s, r);
      if (n !== t)
        throw new Error("The " + s + "s element count (" + n + ") does not match the positions count (" + t + ")");
    };
    this.normals && i(_.NormalKind, this.normals), this.tangents && i(_.TangentKind, this.tangents), this.uvs && i(_.UVKind, this.uvs), this.uvs2 && i(_.UV2Kind, this.uvs2), this.uvs3 && i(_.UV3Kind, this.uvs3), this.uvs4 && i(_.UV4Kind, this.uvs4), this.uvs5 && i(_.UV5Kind, this.uvs5), this.uvs6 && i(_.UV6Kind, this.uvs6), this.colors && i(_.ColorKind, this.colors), this.matricesIndices && i(_.MatricesIndicesKind, this.matricesIndices), this.matricesWeights && i(_.MatricesWeightsKind, this.matricesWeights), this.matricesIndicesExtra && i(_.MatricesIndicesExtraKind, this.matricesIndicesExtra), this.matricesWeightsExtra && i(_.MatricesWeightsExtraKind, this.matricesWeightsExtra);
  }
  /**
   * Serializes the VertexData
   * @returns a serialized object
   */
  serialize() {
    const e = {};
    return this.positions && (e.positions = this.positions), this.normals && (e.normals = this.normals), this.tangents && (e.tangents = this.tangents), this.uvs && (e.uvs = this.uvs), this.uvs2 && (e.uvs2 = this.uvs2), this.uvs3 && (e.uvs3 = this.uvs3), this.uvs4 && (e.uvs4 = this.uvs4), this.uvs5 && (e.uvs5 = this.uvs5), this.uvs6 && (e.uvs6 = this.uvs6), this.colors && (e.colors = this.colors), this.matricesIndices && (e.matricesIndices = this.matricesIndices, e.matricesIndices._isExpanded = !0), this.matricesWeights && (e.matricesWeights = this.matricesWeights), this.matricesIndicesExtra && (e.matricesIndicesExtra = this.matricesIndicesExtra, e.matricesIndicesExtra._isExpanded = !0), this.matricesWeightsExtra && (e.matricesWeightsExtra = this.matricesWeightsExtra), e.indices = this.indices, e;
  }
  // 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(e, t, i) {
    return q._ExtractFrom(e, t, i);
  }
  /**
   * 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(e, t, i) {
    return q._ExtractFrom(e, t, i);
  }
  static _ExtractFrom(e, t, i) {
    const s = new q();
    return e.isVerticesDataPresent(_.PositionKind) && (s.positions = e.getVerticesData(_.PositionKind, t, i)), e.isVerticesDataPresent(_.NormalKind) && (s.normals = e.getVerticesData(_.NormalKind, t, i)), e.isVerticesDataPresent(_.TangentKind) && (s.tangents = e.getVerticesData(_.TangentKind, t, i)), e.isVerticesDataPresent(_.UVKind) && (s.uvs = e.getVerticesData(_.UVKind, t, i)), e.isVerticesDataPresent(_.UV2Kind) && (s.uvs2 = e.getVerticesData(_.UV2Kind, t, i)), e.isVerticesDataPresent(_.UV3Kind) && (s.uvs3 = e.getVerticesData(_.UV3Kind, t, i)), e.isVerticesDataPresent(_.UV4Kind) && (s.uvs4 = e.getVerticesData(_.UV4Kind, t, i)), e.isVerticesDataPresent(_.UV5Kind) && (s.uvs5 = e.getVerticesData(_.UV5Kind, t, i)), e.isVerticesDataPresent(_.UV6Kind) && (s.uvs6 = e.getVerticesData(_.UV6Kind, t, i)), e.isVerticesDataPresent(_.ColorKind) && (s.colors = e.getVerticesData(_.ColorKind, t, i)), e.isVerticesDataPresent(_.MatricesIndicesKind) && (s.matricesIndices = e.getVerticesData(_.MatricesIndicesKind, t, i)), e.isVerticesDataPresent(_.MatricesWeightsKind) && (s.matricesWeights = e.getVerticesData(_.MatricesWeightsKind, t, i)), e.isVerticesDataPresent(_.MatricesIndicesExtraKind) && (s.matricesIndicesExtra = e.getVerticesData(_.MatricesIndicesExtraKind, t, i)), e.isVerticesDataPresent(_.MatricesWeightsExtraKind) && (s.matricesWeightsExtra = e.getVerticesData(_.MatricesWeightsExtraKind, t, i)), s.indices = e.getIndices(t, i), s;
  }
  /**
   * 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
   * @param options.pathArray
   * @param options.closeArray
   * @param options.closePath
   * @param options.offset
   * @param options.sideOrientation
   * @param options.frontUVs
   * @param options.backUVs
   * @param options.invertUV
   * @param options.uvs
   * @param options.colors
   * @returns the VertexData of the ribbon
   * @deprecated use CreateRibbonVertexData instead
   */
  static CreateRibbon(e) {
    throw Y("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)
   * @param options.size
   * @param options.width
   * @param options.height
   * @param options.depth
   * @param options.faceUV
   * @param options.faceColors
   * @param options.sideOrientation
   * @param options.frontUVs
   * @param options.backUVs
   * @returns the VertexData of the box
   * @deprecated Please use CreateBoxVertexData from the BoxBuilder file instead
   */
  static CreateBox(e) {
    throw Y("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(e) {
    throw Y("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)
   * @param options.pattern
   * @param options.tileSize
   * @param options.tileWidth
   * @param options.tileHeight
   * @param options.size
   * @param options.width
   * @param options.height
   * @param options.alignHorizontal
   * @param options.alignVertical
   * @param options.sideOrientation
   * @param options.frontUVs
   * @param options.backUVs
   * @returns the VertexData of the tiled plane
   * @deprecated use CreateTiledPlaneVertexData instead
   */
  static CreateTiledPlane(e) {
    throw Y("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)
   * @param options.segments
   * @param options.diameter
   * @param options.diameterX
   * @param options.diameterY
   * @param options.diameterZ
   * @param options.arc
   * @param options.slice
   * @param options.sideOrientation
   * @param options.frontUVs
   * @param options.backUVs
   * @returns the VertexData of the ellipsoid
   * @deprecated use CreateSphereVertexData instead
   */
  static CreateSphere(e) {
    throw Y("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)
   * @param options.height
   * @param options.diameterTop
   * @param options.diameterBottom
   * @param options.diameter
   * @param options.tessellation
   * @param options.subdivisions
   * @param options.arc
   * @param options.faceColors
   * @param options.faceUV
   * @param options.hasRings
   * @param options.enclose
   * @param options.sideOrientation
   * @param options.frontUVs
   * @param options.backUVs
   * @returns the VertexData of the cylinder, cone or prism
   * @deprecated please use CreateCylinderVertexData instead
   */
  static CreateCylinder(e) {
    throw Y("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)
   * @param options.diameter
   * @param options.thickness
   * @param options.tessellation
   * @param options.sideOrientation
   * @param options.frontUVs
   * @param options.backUVs
   * @returns the VertexData of the torus
   * @deprecated use CreateTorusVertexData instead
   */
  static CreateTorus(e) {
    throw Y("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
   * @param options.lines
   * @param options.colors
   * @returns the VertexData of the LineSystem
   * @deprecated use CreateLineSystemVertexData instead
   */
  static CreateLineSystem(e) {
    throw Y("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
   * @param options.points
   * @param options.dashSize
   * @param options.gapSize
   * @param options.dashNb
   * @returns the VertexData for the DashedLines
   * @deprecated use CreateDashedLinesVertexData instead
   */
  static CreateDashedLines(e) {
    throw Y("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
   * @param options.width
   * @param options.height
   * @param options.subdivisions
   * @param options.subdivisionsX
   * @param options.subdivisionsY
   * @returns the VertexData of the Ground
   * @deprecated Please use CreateGroundVertexData instead
   */
  static CreateGround(e) {
    throw Y("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}
   * @param options.xmin
   * @param options.zmin
   * @param options.xmax
   * @param options.zmax
   * @param options.subdivisions
   * @param options.subdivisions.w
   * @param options.subdivisions.h
   * @param options.precision
   * @param options.precision.w
   * @param options.precision.h
   * @returns the VertexData of the TiledGround
   * @deprecated use CreateTiledGroundVertexData instead
   */
  static CreateTiledGround(e) {
    throw Y("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)
   * @param options.width
   * @param options.height
   * @param options.subdivisions
   * @param options.minHeight
   * @param options.maxHeight
   * @param options.colorFilter
   * @param options.buffer
   * @param options.bufferWidth
   * @param options.bufferHeight
   * @param options.alphaFilter
   * @returns the VertexData of the Ground designed from a heightmap
   * @deprecated use CreateGroundFromHeightMapVertexData instead
   */
  static CreateGroundFromHeightMap(e) {
    throw Y("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)
   * @param options.size
   * @param options.width
   * @param options.height
   * @param options.sideOrientation
   * @param options.frontUVs
   * @param options.backUVs
   * @returns the VertexData of the box
   * @deprecated use CreatePlaneVertexData instead
   */
  static CreatePlane(e) {
    throw Y("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)
   * @param options.radius
   * @param options.tessellation
   * @param options.arc
   * @param options.sideOrientation
   * @param options.frontUVs
   * @param options.backUVs
   * @returns the VertexData of the box
   * @deprecated use CreateDiscVertexData instead
   */
  static CreateDisc(e) {
    throw Y("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(e, t, i, s, r, n, a) {
    throw Y("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)
   * @param options.radius
   * @param options.radiusX
   * @param options.radiusY
   * @param options.radiusZ
   * @param options.flat
   * @param options.subdivisions
   * @param options.sideOrientation
   * @param options.frontUVs
   * @param options.backUVs
   * @returns the VertexData of the IcoSphere
   * @deprecated use CreateIcoSphereVertexData instead
   */
  static CreateIcoSphere(e) {
    throw Y("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)
   * @param options.type
   * @param options.size
   * @param options.sizeX
   * @param options.sizeY
   * @param options.sizeZ
   * @param options.custom
   * @param options.faceUV
   * @param options.faceColors
   * @param options.flat
   * @param options.sideOrientation
   * @param options.frontUVs
   * @param options.backUVs
   * @returns the VertexData of the Polyhedron
   * @deprecated use CreatePolyhedronVertexData instead
   */
  static CreatePolyhedron(e) {
    throw Y("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(e = {
    orientation: p.Up(),
    subdivisions: 2,
    tessellation: 16,
    height: 1,
    radius: 0.25,
    capSubdivisions: 6
  }) {
    throw Y("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)
   * @param options.radius
   * @param options.tube
   * @param options.radialSegments
   * @param options.tubularSegments
   * @param options.p
   * @param options.q
   * @param options.sideOrientation
   * @param options.frontUVs
   * @param options.backUVs
   * @returns the VertexData of the Torus Knot
   * @deprecated use CreateTorusKnotVertexData instead
   */
  static CreateTorusKnot(e) {
    throw Y("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
   * @param options.facetNormals
   * @param options.facetPositions
   * @param options.facetPartitioning
   * @param options.ratio
   * @param options.bInfo
   * @param options.bbSize
   * @param options.subDiv
   * @param options.useRightHandedSystem
   * @param options.depthSort
   * @param options.distanceTo
   * @param options.depthSortedFacets
   */
  static ComputeNormals(e, t, i, s) {
    let r = 0, n = 0, a = 0, o = 0, h = 0, c = 0, u = 0, d = 0, g = 0, f = 0, m = 0, b = 0, T = 0, M = 0, v = 0, A = 0, E = 0, y = 0, x = 0, D = 0, V = !1, W = !1, ce = !1, ee = !1, oe = 1, $ = 0, Pe = null;
    s && (V = !!s.facetNormals, W = !!s.facetPositions, ce = !!s.facetPartitioning, oe = s.useRightHandedSystem === !0 ? -1 : 1, $ = s.ratio || 0, ee = !!s.depthSort, Pe = s.distanceTo, ee && Pe === void 0 && (Pe = p.Zero()));
    let Ae = 0, Fe = 0, Te = 0, Me = 0;
    for (ce && s && s.bbSize && (Ae = s.subDiv.X * $ / s.bbSize.x, Fe = s.subDiv.Y * $ / s.bbSize.y, Te = s.subDiv.Z * $ / s.bbSize.z, Me = s.subDiv.max * s.subDiv.max, s.facetPartitioning.length = 0), r = 0; r < e.length; r++)
      i[r] = 0;
    const ze = t.length / 3 | 0;
    for (r = 0; r < ze; r++) {
      if (b = t[r * 3] * 3, T = b + 1, M = b + 2, v = t[r * 3 + 1] * 3, A = v + 1, E = v + 2, y = t[r * 3 + 2] * 3, x = y + 1, D = y + 2, n = e[b] - e[v], a = e[T] - e[A], o = e[M] - e[E], h = e[y] - e[v], c = e[x] - e[A], u = e[D] - e[E], d = oe * (a * u - o * c), g = oe * (o * h - n * u), f = oe * (n * c - a * h), m = Math.sqrt(d * d + g * g + f * f), m = m === 0 ? 1 : m, d /= m, g /= m, f /= m, V && s && (s.facetNormals[r].x = d, s.facetNormals[r].y = g, s.facetNormals[r].z = f), W && s && (s.facetPositions[r].x = (e[b] + e[v] + e[y]) / 3, s.facetPositions[r].y = (e[T] + e[A] + e[x]) / 3, s.facetPositions[r].z = (e[M] + e[E] + e[D]) / 3), ce && s) {
        const ke = Math.floor((s.facetPositions[r].x - s.bInfo.minimum.x * $) * Ae), Qe = Math.floor((s.facetPositions[r].y - s.bInfo.minimum.y * $) * Fe), _t = Math.floor((s.facetPositions[r].z - s.bInfo.minimum.z * $) * Te), Xt = Math.floor((e[b] - s.bInfo.minimum.x * $) * Ae), Yt = Math.floor((e[T] - s.bInfo.minimum.y * $) * Fe), qt = Math.floor((e[M] - s.bInfo.minimum.z * $) * Te), ui = Math.floor((e[v] - s.bInfo.minimum.x * $) * Ae), di = Math.floor((e[A] - s.bInfo.minimum.y * $) * Fe), fi = Math.floor((e[E] - s.bInfo.minimum.z * $) * Te), _i = Math.floor((e[y] - s.bInfo.minimum.x * $) * Ae), gi = Math.floor((e[x] - s.bInfo.minimum.y * $) * Fe), pi = Math.floor((e[D] - s.bInfo.minimum.z * $) * Te), it = Xt + s.subDiv.max * Yt + Me * qt, st = ui + s.subDiv.max * di + Me * fi, rt = _i + s.subDiv.max * gi + Me * pi, nt = ke + s.subDiv.max * Qe + Me * _t;
        s.facetPartitioning[nt] = s.facetPartitioning[nt] ? s.facetPartitioning[nt] : new Array(), s.facetPartitioning[it] = s.facetPartitioning[it] ? s.facetPartitioning[it] : new Array(), s.facetPartitioning[st] = s.facetPartitioning[st] ? s.facetPartitioning[st] : new Array(), s.facetPartitioning[rt] = s.facetPartitioning[rt] ? s.facetPartitioning[rt] : new Array(), s.facetPartitioning[it].push(r), st != it && s.facetPartitioning[st].push(r), rt == st || rt == it || s.facetPartitioning[rt].push(r), nt == it || nt == st || nt == rt || s.facetPartitioning[nt].push(r);
      }
      if (ee && s && s.facetPositions) {
        const ke = s.depthSortedFacets[r];
        ke.ind = r * 3, ke.sqDistance = p.DistanceSquared(s.facetPositions[r], Pe);
      }
      i[b] += d, i[T] += g, i[M] += f, i[v] += d, i[A] += g, i[E] += f, i[y] += d, i[x] += g, i[D] += f;
    }
    for (r = 0; r < i.length / 3; r++)
      d = i[r * 3], g = i[r * 3 + 1], f = i[r * 3 + 2], m = Math.sqrt(d * d + g * g + f * f), m = m === 0 ? 1 : m, d /= m, g /= m, f /= m, i[r * 3] = d, i[r * 3 + 1] = g, i[r * 3 + 2] = f;
  }
  /**
   * @internal
   */
  static _ComputeSides(e, t, i, s, r, n, a) {
    const o = i.length, h = s.length;
    let c, u;
    switch (e = e || q.DEFAULTSIDE, e) {
      case q.FRONTSIDE:
        break;
      case q.BACKSIDE:
        for (c = 0; c < o; c += 3) {
          const d = i[c];
          i[c] = i[c + 2], i[c + 2] = d;
        }
        for (u = 0; u < h; u++)
          s[u] = -s[u];
        break;
      case q.DOUBLESIDE: {
        const d = t.length, g = d / 3;
        for (let b = 0; b < d; b++)
          t[d + b] = t[b];
        for (c = 0; c < o; c += 3)
          i[c + o] = i[c + 2] + g, i[c + 1 + o] = i[c + 1] + g, i[c + 2 + o] = i[c] + g;
        for (u = 0; u < h; u++)
          s[h + u] = -s[u];
        const f = r.length;
        let m = 0;
        for (m = 0; m < f; m++)
          r[m + f] = r[m];
        for (n = n || new de(0, 0, 1, 1), a = a || new de(0, 0, 1, 1), m = 0, c = 0; c < f / 2; c++)
          r[m] = n.x + (n.z - n.x) * r[m], r[m + 1] = n.y + (n.w - n.y) * r[m + 1], r[m + f] = a.x + (a.z - a.x) * r[m + f], r[m + f + 1] = a.y + (a.w - a.y) * r[m + f + 1], m += 2;
        break;
      }
    }
  }
  /**
   * 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(e, t) {
    const i = new q(), s = e.positions;
    s && i.set(s, _.PositionKind);
    const r = e.normals;
    r && i.set(r, _.NormalKind);
    const n = e.tangents;
    n && i.set(n, _.TangentKind);
    const a = e.uvs;
    a && i.set(a, _.UVKind);
    const o = e.uv2s;
    o && i.set(o, _.UV2Kind);
    const h = e.uv3s;
    h && i.set(h, _.UV3Kind);
    const c = e.uv4s;
    c && i.set(c, _.UV4Kind);
    const u = e.uv5s;
    u && i.set(u, _.UV5Kind);
    const d = e.uv6s;
    d && i.set(d, _.UV6Kind);
    const g = e.colors;
    g && i.set(Oe.CheckColors4(g, s.length / 3), _.ColorKind);
    const f = e.matricesIndices;
    f && i.set(f, _.MatricesIndicesKind);
    const m = e.matricesWeights;
    m && i.set(m, _.MatricesWeightsKind);
    const b = e.indices;
    b && (i.indices = b), t.setAllVerticesData(i, e.updatable);
  }
}
q.FRONTSIDE = 0;
q.BACKSIDE = 1;
q.DOUBLESIDE = 2;
q.DEFAULTSIDE = 0;
F([
  yt.filter((...[l]) => !Array.isArray(l))
], q, "_TransformVector3Coordinates", null);
F([
  yt.filter((...[l]) => !Array.isArray(l))
], q, "_TransformVector3Normals", null);
F([
  yt.filter((...[l]) => !Array.isArray(l))
], q, "_TransformVector4Normals", null);
F([
  yt.filter((...[l]) => !Array.isArray(l))
], q, "_FlipFaces", null);
class ht {
  /**
   * 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(e, t, i) {
    this.vectors = Ee.BuildArray(8, p.Zero), this.center = p.Zero(), this.centerWorld = p.Zero(), this.extendSize = p.Zero(), this.extendSizeWorld = p.Zero(), this.directions = Ee.BuildArray(3, p.Zero), this.vectorsWorld = Ee.BuildArray(8, p.Zero), this.minimumWorld = p.Zero(), this.maximumWorld = p.Zero(), this.minimum = p.Zero(), this.maximum = p.Zero(), this._drawWrapperFront = null, this._drawWrapperBack = null, this.reConstruct(e, t, i);
  }
  // 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(e, t, i) {
    const s = e.x, r = e.y, n = e.z, a = t.x, o = t.y, h = t.z, c = this.vectors;
    this.minimum.copyFromFloats(s, r, n), this.maximum.copyFromFloats(a, o, h), c[0].copyFromFloats(s, r, n), c[1].copyFromFloats(a, o, h), c[2].copyFromFloats(a, r, n), c[3].copyFromFloats(s, o, n), c[4].copyFromFloats(s, r, h), c[5].copyFromFloats(a, o, n), c[6].copyFromFloats(s, o, h), c[7].copyFromFloats(a, r, h), t.addToRef(e, this.center).scaleInPlace(0.5), t.subtractToRef(e, this.extendSize).scaleInPlace(0.5), this._worldMatrix = i || R.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(e) {
    const t = ht._TmpVector3, i = this.maximum.subtractToRef(this.minimum, t[0]), s = i.length();
    i.normalizeFromLength(s);
    const r = s * e, n = i.scaleInPlace(r * 0.5), a = this.center.subtractToRef(n, t[1]), o = this.center.addToRef(n, t[2]);
    return this.reConstruct(a, o, this._worldMatrix), this;
  }
  /**
   * Gets the world matrix of the bounding box
   * @returns a matrix
   */
  getWorldMatrix() {
    return this._worldMatrix;
  }
  /**
   * @internal
   */
  _update(e) {
    const t = this.minimumWorld, i = this.maximumWorld, s = this.directions, r = this.vectorsWorld, n = this.vectors;
    if (e.isIdentity()) {
      t.copyFrom(this.minimum), i.copyFrom(this.maximum);
      for (let a = 0; a < 8; ++a)
        r[a].copyFrom(n[a]);
      this.extendSizeWorld.copyFrom(this.extendSize), this.centerWorld.copyFrom(this.center);
    } else {
      t.setAll(Number.MAX_VALUE), i.setAll(-Number.MAX_VALUE);
      for (let a = 0; a < 8; ++a) {
        const o = r[a];
        p.TransformCoordinatesToRef(n[a], e, o), t.minimizeInPlace(o), i.maximizeInPlace(o);
      }
      i.subtractToRef(t, this.extendSizeWorld).scaleInPlace(0.5), i.addToRef(t, this.centerWorld).scaleInPlace(0.5);
    }
    p.FromArrayToRef(e.m, 0, s[0]), p.FromArrayToRef(e.m, 4, s[1]), p.FromArrayToRef(e.m, 8, s[2]), this._worldMatrix = e;
  }
  /**
   * 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(e) {
    return ht.IsInFrustum(this.vectorsWorld, e);
  }
  /**
   * 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(e) {
    return ht.IsCompletelyInFrustum(this.vectorsWorld, e);
  }
  /**
   * 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(e) {
    const t = this.minimumWorld, i = this.maximumWorld, s = t.x, r = t.y, n = t.z, a = i.x, o = i.y, h = i.z, c = e.x, u = e.y, d = e.z, g = -ye;
    return !(a - c < g || g > c - s || o - u < g || g > u - r || h - d < g || g > d - n);
  }
  /**
   * 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(e) {
    return ht.IntersectsSphere(this.minimumWorld, this.maximumWorld, e.centerWorld, e.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(e, t) {
    const i = this.minimumWorld, s = this.maximumWorld, r = i.x, n = i.y, a = i.z, o = s.x, h = s.y, c = s.z, u = e.x, d = e.y, g = e.z, f = t.x, m = t.y, b = t.z;
    return !(o < u || r > f || h < d || n > m || c < g || a > b);
  }
  /**
   * Disposes the resources of the class
   */
  dispose() {
    var e, t;
    (e = this._drawWrapperFront) === null || e === void 0 || e.dispose(), (t = this._drawWrapperBack) === null || t === void 0 || t.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(e, t) {
    return e.intersectsMinMax(t.minimumWorld, t.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(e, t, i, s) {
    const r = ht._TmpVector3[0];
    return p.ClampToRef(i, e, t, r), p.DistanceSquared(i, r) <= s * s;
  }
  /**
   * 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(e, t) {
    for (let i = 0; i < 6; ++i) {
      const s = t[i];
      for (let r = 0; r < 8; ++r)
        if (s.dotCoordinate(e[r]) < 0)
          return !1;
    }
    return !0;
  }
  /**
   * 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(e, t) {
    for (let i = 0; i < 6; ++i) {
      let s = !0;
      const r = t[i];
      for (let n = 0; n < 8; ++n)
        if (r.dotCoordinate(e[n]) >= 0) {
          s = !1;
          break;
        }
      if (s)
        return !1;
    }
    return !0;
  }
}
ht._TmpVector3 = Ee.BuildArray(3, p.Zero);
class Ct {
  /**
   * 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(e, t, i) {
    this.center = p.Zero(), this.centerWorld = p.Zero(), this.minimum = p.Zero(), this.maximum = p.Zero(), this.reConstruct(e, t, i);
  }
  /**
   * 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(e, t, i) {
    this.minimum.copyFrom(e), this.maximum.copyFrom(t);
    const s = p.Distance(e, t);
    t.addToRef(e, this.center).scaleInPlace(0.5), this.radius = s * 0.5, this._update(i || R.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(e) {
    const t = this.radius * e, i = Ct._TmpVector3, s = i[0].setAll(t), r = this.center.subtractToRef(s, i[1]), n = this.center.addToRef(s, i[2]);
    return this.reConstruct(r, n, this._worldMatrix), this;
  }
  /**
   * Gets the world matrix of the bounding box
   * @returns a matrix
   */
  getWorldMatrix() {
    return this._worldMatrix;
  }
  // Methods
  /**
   * @internal
   */
  _update(e) {
    if (e.isIdentity())
      this.centerWorld.copyFrom(this.center), this.radiusWorld = this.radius;
    else {
      p.TransformCoordinatesToRef(this.center, e, this.centerWorld);
      const t = Ct._TmpVector3[0];
      p.TransformNormalFromFloatsToRef(1, 1, 1, e, t), this.radiusWorld = Math.max(Math.abs(t.x), Math.abs(t.y), Math.abs(t.z)) * 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(e) {
    const t = this.centerWorld, i = this.radiusWorld;
    for (let s = 0; s < 6; s++)
      if (e[s].dotCoordinate(t) <= -i)
        return !1;
    return !0;
  }
  /**
   * 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(e) {
    const t = this.centerWorld;
    for (let i = 0; i < 6; i++)
      if (e[i].dotCoordinate(t) < 0)
        return !1;
    return !0;
  }
  /**
   * 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(e) {
    const t = p.DistanceSquared(this.centerWorld, e);
    return !(this.radiusWorld * this.radiusWorld < t);
  }
  // Statics
  /**
   * Checks if two sphere intersect
   * @param sphere0 sphere 0
   * @param sphere1 sphere 1
   * @returns true if the spheres intersect
   */
  static Intersects(e, t) {
    const i = p.DistanceSquared(e.centerWorld, t.centerWorld), s = e.radiusWorld + t.radiusWorld;
    return !(s * s < i);
  }
  /**
   * 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(e, t, i) {
    this._TmpVector3[0].copyFrom(e), this._TmpVector3[1].copyFromFloats(0, 0, t), this._TmpVector3[2].copyFrom(e), this._TmpVector3[0].addInPlace(this._TmpVector3[1]), this._TmpVector3[2].subtractInPlace(this._TmpVector3[1]);
    const s = new Ct(this._TmpVector3[0], this._TmpVector3[2]);
    return i ? s._worldMatrix = i : s._worldMatrix = R.Identity(), s;
  }
}
Ct._TmpVector3 = Ee.BuildArray(3, p.Zero);
const yi = { min: 0, max: 0 }, Ti = { min: 0, max: 0 }, Ji = (l, e, t) => {
  const i = p.Dot(e.centerWorld, l), s = Math.abs(p.Dot(e.directions[0], l)) * e.extendSize.x, r = Math.abs(p.Dot(e.directions[1], l)) * e.extendSize.y, n = Math.abs(p.Dot(e.directions[2], l)) * e.extendSize.z, a = s + r + n;
  t.min = i - a, t.max = i + a;
}, Le = (l, e, t) => (Ji(l, e, yi), Ji(l, t, Ti), !(yi.min > Ti.max || Ti.min > yi.max));
class qe {
  /**
   * 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(e, t, i) {
    this._isLocked = !1, this.boundingBox = new ht(e, t, i), this.boundingSphere = new Ct(e, t, i);
  }
  /**
   * 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(e, t, i) {
    this.boundingBox.reConstruct(e, t, i), this.boundingSphere.reConstruct(e, t, i);
  }
  /**
   * 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(e) {
    this._isLocked = e;
  }
  // Methods
  /**
   * Updates the bounding sphere and box
   * @param world world matrix to be used to update
   */
  update(e) {
    this._isLocked || (this.boundingBox._update(e), this.boundingSphere._update(e));
  }
  /**
   * 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(e, t) {
    const i = qe._TmpVector3[0].copyFrom(e).subtractInPlace(t), s = qe._TmpVector3[1].copyFrom(e).addInPlace(t);
    return this.boundingBox.reConstruct(i, s, this.boundingBox.getWorldMatrix()), this.boundingSphere.reConstruct(i, s, this.boundingBox.getWorldMatrix()), 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(e) {
    const t = p.Minimize(this.minimum, e), i = p.Maximize(this.maximum, e);
    return this.reConstruct(t, i, this.boundingBox.getWorldMatrix()), 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(e) {
    const t = C.Matrix[0];
    this.boundingBox.getWorldMatrix().invertToRef(t);
    const i = C.Vector3[0];
    return p.TransformCoordinatesToRef(e.boundingBox.minimumWorld, t, i), this.encapsulate(i), p.TransformCoordinatesToRef(e.boundingBox.maximumWorld, t, i), this.encapsulate(i), 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(e) {
    return this.boundingBox.scale(e), this.boundingSphere.scale(e), 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(e, t = 0) {
    return (t === 2 || t === 3) && this.boundingSphere.isCenterInFrustum(e) ? !0 : this.boundingSphere.isInFrustum(e) ? t === 1 || t === 3 ? !0 : this.boundingBox.isInFrustum(e) : !1;
  }
  /**
   * Gets the world distance between the min and max points of the bounding box
   */
  get diagonalLength() {
    const e = this.boundingBox;
    return e.maximumWorld.subtractToRef(e.minimumWorld, qe._TmpVector3[0]).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(e) {
    return this.boundingBox.isCompletelyInFrustum(e);
  }
  /**
   * @internal
   */
  _checkCollision(e) {
    return e._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(e) {
    return !(!this.boundingSphere.centerWorld || !this.boundingSphere.intersectsPoint(e) || !this.boundingBox.intersectsPoint(e));
  }
  /**
   * 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(e, t) {
    if (!Ct.Intersects(this.boundingSphere, e.boundingSphere) || !ht.Intersects(this.boundingBox, e.boundingBox))
      return !1;
    if (!t)
      return !0;
    const i = this.boundingBox, s = e.boundingBox;
    return !(!Le(i.directions[0], i, s) || !Le(i.directions[1], i, s) || !Le(i.directions[2], i, s) || !Le(s.directions[0], i, s) || !Le(s.directions[1], i, s) || !Le(s.directions[2], i, s) || !Le(p.Cross(i.directions[0], s.directions[0]), i, s) || !Le(p.Cross(i.directions[0], s.directions[1]), i, s) || !Le(p.Cross(i.directions[0], s.directions[2]), i, s) || !Le(p.Cross(i.directions[1], s.directions[0]), i, s) || !Le(p.Cross(i.directions[1], s.directions[1]), i, s) || !Le(p.Cross(i.directions[1], s.directions[2]), i, s) || !Le(p.Cross(i.directions[2], s.directions[0]), i, s) || !Le(p.Cross(i.directions[2], s.directions[1]), i, s) || !Le(p.Cross(i.directions[2], s.directions[2]), i, s));
  }
}
qe._TmpVector3 = Ee.BuildArray(2, p.Zero);
class li {
  static extractMinAndMaxIndexed(e, t, i, s, r, n) {
    for (let a = i; a < i + s; a++) {
      const o = t[a] * 3, h = e[o], c = e[o + 1], u = e[o + 2];
      r.minimizeInPlaceFromFloats(h, c, u), n.maximizeInPlaceFromFloats(h, c, u);
    }
  }
  static extractMinAndMax(e, t, i, s, r, n) {
    for (let a = t, o = t * s; a < t + i; a++, o += s) {
      const h = e[o], c = e[o + 1], u = e[o + 2];
      r.minimizeInPlaceFromFloats(h, c, u), n.maximizeInPlaceFromFloats(h, c, u);
    }
  }
}
F([
  yt.filter((...[l, e]) => !Array.isArray(l) && !Array.isArray(e))
  // eslint-disable-next-line @typescript-eslint/naming-convention
], li, "extractMinAndMaxIndexed", null);
F([
  yt.filter((...[l]) => !Array.isArray(l))
  // eslint-disable-next-line @typescript-eslint/naming-convention
], li, "extractMinAndMax", null);
function br(l, e, t, i, s = null) {
  const r = new p(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE), n = new p(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  return li.extractMinAndMaxIndexed(l, e, t, i, r, n), s && (r.x -= r.x * s.x + s.y, r.y -= r.y * s.x + s.y, r.z -= r.z * s.x + s.y, n.x += n.x * s.x + s.y, n.y += n.y * s.x + s.y, n.z += n.z * s.x + s.y), {
    minimum: r,
    maximum: n
  };
}
function gs(l, e, t, i = null, s) {
  const r = new p(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE), n = new p(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  return s || (s = 3), li.extractMinAndMax(l, e, t, s, r, n), i && (r.x -= r.x * i.x + i.y, r.y -= r.y * i.x + i.y, r.z -= r.z * i.x + i.y, n.x += n.x * i.x + i.y, n.y += n.y * i.x + i.y, n.z += n.z * i.x + i.y), {
    minimum: r,
    maximum: n
  };
}
class Ye {
  /**
   * Gets material defines used by the effect associated to the sub mesh
   */
  get materialDefines() {
    var e;
    return this._mainDrawWrapperOverride ? this._mainDrawWrapperOverride.defines : (e = this._getDrawWrapper()) === null || e === void 0 ? void 0 : e.defines;
  }
  /**
   * Sets material defines used by the effect associated to the sub mesh
   */
  set materialDefines(e) {
    var t;
    const i = (t = this._mainDrawWrapperOverride) !== null && t !== void 0 ? t : this._getDrawWrapper(void 0, !0);
    i.defines = e;
  }
  /**
   * @internal
   */
  _getDrawWrapper(e, t = !1) {
    e = e ?? this._engine.currentRenderPassId;
    let i = this._drawWrappers[e];
    return !i && t && (this._drawWrappers[e] = i = new Pi(this._mesh.getScene().getEngine())), i;
  }
  /**
   * @internal
   */
  _removeDrawWrapper(e, t = !0) {
    var i;
    t && ((i = this._drawWrappers[e]) === null || i === void 0 || i.dispose()), this._drawWrappers[e] = void 0;
  }
  /**
   * Gets associated (main) effect (possibly the effect override if defined)
   */
  get effect() {
    var e, t;
    return this._mainDrawWrapperOverride ? this._mainDrawWrapperOverride.effect : (t = (e = this._getDrawWrapper()) === null || e === void 0 ? void 0 : e.effect) !== null && t !== void 0 ? t : null;
  }
  /** @internal */
  get _drawWrapper() {
    var e;
    return (e = this._mainDrawWrapperOverride) !== null && e !== void 0 ? e : this._getDrawWrapper(void 0, !0);
  }
  /** @internal */
  get _drawWrapperOverride() {
    return this._mainDrawWrapperOverride;
  }
  /**
   * @internal
   */
  _setMainDrawWrapperOverride(e) {
    this._mainDrawWrapperOverride = e;
  }
  /**
   * 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(e, t = null, i, s = !0) {
    const r = this._drawWrapper;
    r.setEffect(e, t, s), i !== void 0 && (r.materialContext = i), e || (r.defines = null, r.materialContext = void 0);
  }
  /**
   * Resets the draw wrappers cache
   * @param passId If provided, releases only the draw wrapper corresponding to this render pass id
   */
  resetDrawCache(e) {
    if (this._drawWrappers)
      if (e !== void 0) {
        this._removeDrawWrapper(e);
        return;
      } else
        for (const t of this._drawWrappers)
          t == null || t.dispose();
    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(e, t, i, s, r, n, a, o = !0) {
    return new Ye(e, t, i, s, r, n, a, o);
  }
  /**
   * 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(e, t, i, s, r, n, a, o = !0, h = !0) {
    this.materialIndex = e, this.verticesStart = t, this.verticesCount = i, this.indexStart = s, this.indexCount = r, this._mainDrawWrapperOverride = null, this._linesIndexCount = 0, this._linesIndexBuffer = null, this._lastColliderWorldVertices = null, this._lastColliderTransformMatrix = null, this._wasDispatched = !1, this._renderId = 0, this._alphaIndex = 0, this._distanceToCamera = 0, this._currentMaterial = null, this._mesh = n, this._renderingMesh = a || n, h && n.subMeshes.push(this), this._engine = this._mesh.getScene().getEngine(), this.resetDrawCache(), this._trianglePlanes = [], this._id = n.subMeshes.length - 1, o && (this.refreshBoundingInfo(), n.computeWorldMatrix(!0));
  }
  /**
   * 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() {
    return this.IsGlobal ? this._mesh.getBoundingInfo() : this._boundingInfo;
  }
  /**
   * Sets the submesh BoundingInfo
   * @param boundingInfo defines the new bounding info to use
   * @returns the SubMesh
   */
  setBoundingInfo(e) {
    return this._boundingInfo = e, 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 e = this._mesh._internalAbstractMeshDataInfo._actAsRegularMesh ? this._mesh : null;
    return e || 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(e = !0) {
    var t;
    const i = (t = this._renderingMesh.getMaterialForRenderPass(this._engine.currentRenderPassId)) !== null && t !== void 0 ? t : this._renderingMesh.material;
    if (i) {
      if (this._isMultiMaterial(i)) {
        const s = i.getSubMaterial(this.materialIndex);
        return this._currentMaterial !== s && (this._currentMaterial = s, this.resetDrawCache()), s;
      }
    } else
      return e ? this._mesh.getScene().defaultMaterial : null;
    return i;
  }
  _isMultiMaterial(e) {
    return e.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(e = null) {
    if (this._lastColliderWorldVertices = null, this.IsGlobal || !this._renderingMesh || !this._renderingMesh.geometry)
      return this;
    if (e || (e = this._renderingMesh.getVerticesData(_.PositionKind)), !e)
      return this._boundingInfo = this._mesh.getBoundingInfo(), this;
    const t = this._renderingMesh.getIndices();
    let i;
    if (this.indexStart === 0 && this.indexCount === t.length) {
      const s = this._renderingMesh.getBoundingInfo();
      i = { minimum: s.minimum.clone(), maximum: s.maximum.clone() };
    } else
      i = br(e, t, this.indexStart, this.indexCount, this._renderingMesh.geometry.boundingBias);
    return this._boundingInfo ? this._boundingInfo.reConstruct(i.minimum, i.maximum) : this._boundingInfo = new qe(i.minimum, i.maximum), this;
  }
  /**
   * @internal
   */
  _checkCollision(e) {
    return this.getBoundingInfo()._checkCollision(e);
  }
  /**
   * Updates the submesh BoundingInfo
   * @param world defines the world matrix to use to update the bounding info
   * @returns the submesh
   */
  updateBoundingInfo(e) {
    let t = this.getBoundingInfo();
    return t || (this.refreshBoundingInfo(), t = this.getBoundingInfo()), t && t.update(e), 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(e) {
    const t = this.getBoundingInfo();
    return t ? t.isInFrustum(e, this._mesh.cullingStrategy) : !1;
  }
  /**
   * 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(e) {
    const t = this.getBoundingInfo();
    return t ? t.isCompletelyInFrustum(e) : !1;
  }
  /**
   * Renders the submesh
   * @param enableAlphaMode defines if alpha needs to be used
   * @returns the submesh
   */
  render(e) {
    return this._renderingMesh.render(this, e, this._mesh._internalAbstractMeshDataInfo._actAsRegularMesh ? this._mesh : void 0), this;
  }
  /**
   * @internal
   */
  _getLinesIndexBuffer(e, t) {
    if (!this._linesIndexBuffer) {
      const i = [];
      for (let s = this.indexStart; s < this.indexStart + this.indexCount; s += 3)
        i.push(e[s], e[s + 1], e[s + 1], e[s + 2], e[s + 2], e[s]);
      this._linesIndexBuffer = t.createIndexBuffer(i), this._linesIndexCount = i.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(e) {
    const t = this.getBoundingInfo();
    return t ? e.intersectsBox(t.boundingBox) : !1;
  }
  /**
   * 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(e, t, i, s, r) {
    const n = this.getMaterial();
    if (!n)
      return null;
    let a = 3, o = !1;
    switch (n.fillMode) {
      case 3:
      case 5:
      case 6:
      case 8:
        return null;
      case 7:
        a = 1, o = !0;
        break;
    }
    return n.fillMode === 4 ? i.length ? this._intersectLines(e, t, i, this._mesh.intersectionThreshold, s) : this._intersectUnIndexedLines(e, t, i, this._mesh.intersectionThreshold, s) : !i.length && this._mesh._unIndexed ? this._intersectUnIndexedTriangles(e, t, i, s, r) : this._intersectTriangles(e, t, i, a, o, s, r);
  }
  /**
   * @internal
   */
  _intersectLines(e, t, i, s, r) {
    let n = null;
    for (let a = this.indexStart; a < this.indexStart + this.indexCount; a += 2) {
      const o = t[i[a]], h = t[i[a + 1]], c = e.intersectionSegment(o, h, s);
      if (!(c < 0) && (r || !n || c < n.distance) && (n = new xi(null, null, c), n.faceId = a / 2, r))
        break;
    }
    return n;
  }
  /**
   * @internal
   */
  _intersectUnIndexedLines(e, t, i, s, r) {
    let n = null;
    for (let a = this.verticesStart; a < this.verticesStart + this.verticesCount; a += 2) {
      const o = t[a], h = t[a + 1], c = e.intersectionSegment(o, h, s);
      if (!(c < 0) && (r || !n || c < n.distance) && (n = new xi(null, null, c), n.faceId = a / 2, r))
        break;
    }
    return n;
  }
  /**
   * @internal
   */
  _intersectTriangles(e, t, i, s, r, n, a) {
    let o = null, h = -1;
    for (let c = this.indexStart; c < this.indexStart + this.indexCount - (3 - s); c += s) {
      h++;
      const u = i[c], d = i[c + 1], g = i[c + 2];
      if (r && g === 4294967295) {
        c += 2;
        continue;
      }
      const f = t[u], m = t[d], b = t[g];
      if (!f || !m || !b || a && !a(f, m, b, e, u, d, g))
        continue;
      const T = e.intersectsTriangle(f, m, b);
      if (T) {
        if (T.distance < 0)
          continue;
        if ((n || !o || T.distance < o.distance) && (o = T, o.faceId = h, n))
          break;
      }
    }
    return o;
  }
  /**
   * @internal
   */
  _intersectUnIndexedTriangles(e, t, i, s, r) {
    let n = null;
    for (let a = this.verticesStart; a < this.verticesStart + this.verticesCount; a += 3) {
      const o = t[a], h = t[a + 1], c = t[a + 2];
      if (r && !r(o, h, c, e, -1, -1, -1))
        continue;
      const u = e.intersectsTriangle(o, h, c);
      if (u) {
        if (u.distance < 0)
          continue;
        if ((s || !n || u.distance < n.distance) && (n = u, n.faceId = a / 3, s))
          break;
      }
    }
    return n;
  }
  /** @internal */
  _rebuild() {
    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(e, t) {
    const i = new Ye(this.materialIndex, this.verticesStart, this.verticesCount, this.indexStart, this.indexCount, e, t, !1);
    if (!this.IsGlobal) {
      const s = this.getBoundingInfo();
      if (!s)
        return i;
      i._boundingInfo = new qe(s.minimum, s.maximum);
    }
    return i;
  }
  // Dispose
  /**
   * Release associated resources
   */
  dispose() {
    this._linesIndexBuffer && (this._mesh.getScene().getEngine()._releaseBuffer(this._linesIndexBuffer), this._linesIndexBuffer = null);
    const e = this._mesh.subMeshes.indexOf(this);
    this._mesh.subMeshes.splice(e, 1), this.resetDrawCache();
  }
  /**
   * 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(e, t, i, s, r, n = !0) {
    let a = Number.MAX_VALUE, o = -Number.MAX_VALUE;
    const c = (r || s).getIndices();
    for (let u = t; u < t + i; u++) {
      const d = c[u];
      d < a && (a = d), d > o && (o = d);
    }
    return new Ye(e, a, o - a + 1, t, i, s, r, n);
  }
}
class Rt {
}
Rt.UseOpenGLOrientationForUV = !1;
class Ve {
  /**
   *  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(e) {
    this._boundingBias ? this._boundingBias.copyFrom(e) : this._boundingBias = e.clone(), this._updateBoundingInfo(!0, 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(e) {
    const t = new Ve(Ve.RandomId(), e.getScene());
    return t.applyToMesh(e), t;
  }
  /** 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(e, t, i, s = !1, r = null) {
    this.delayLoadState = 0, this._totalVertices = 0, this._isDisposed = !1, this._indexBufferIsUpdatable = !1, this._positionsCache = [], this._parentContainer = null, this.useBoundingInfoFromGeometry = !1, this._scene = t || J.LastCreatedScene, this._scene && (this.id = e, this.uniqueId = this._scene.getUniqueId(), this._engine = this._scene.getEngine(), this._meshes = [], this._vertexBuffers = {}, this._indices = [], this._updatable = s, i ? this.setAllVerticesData(i, s) : this._totalVertices = 0, this._engine.getCaps().vertexArrayObject && (this._vertexArrayObjects = {}), r && (this.applyToMesh(r), r.computeWorldMatrix(!0)));
  }
  /**
   * 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 e = 0; e < this._meshes.length; e++)
      if (!this._meshes[e].doNotSerialize)
        return !1;
    return !0;
  }
  /** @internal */
  _rebuild() {
    this._vertexArrayObjects && (this._vertexArrayObjects = {}), this._meshes.length !== 0 && this._indices && (this._indexBuffer = this._engine.createIndexBuffer(this._indices, this._updatable));
    for (const e in this._vertexBuffers)
      this._vertexBuffers[e]._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(e, t) {
    e.applyToGeometry(this, t), 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(e, t, i = !1, s) {
    i && Array.isArray(t) && (t = new Float32Array(t));
    const r = new _(this._engine, t, e, i, this._meshes.length === 0, s);
    this.setVerticesBuffer(r);
  }
  /**
   * Removes a specific vertex data
   * @param kind defines the data kind (Position, normal, etc...)
   */
  removeVerticesData(e) {
    this._vertexBuffers[e] && (this._vertexBuffers[e].dispose(), delete this._vertexBuffers[e]), 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(e, t = null, i = !0) {
    const s = e.getKind();
    this._vertexBuffers[s] && i && this._vertexBuffers[s].dispose(), e._buffer && e._buffer._increaseReferences(), this._vertexBuffers[s] = e;
    const r = this._meshes, n = r.length;
    if (s === _.PositionKind) {
      const a = e.getData();
      t != null ? this._totalVertices = t : a != null && (this._totalVertices = a.length / (e.type === _.BYTE ? e.byteStride : e.byteStride / 4)), this._updateExtend(a), this._resetPointsArrayCache();
      for (let o = 0; o < n; o++) {
        const h = r[o];
        h.buildBoundingInfo(this._extend.minimum, this._extend.maximum), h._createGlobalSubMesh(h.isUnIndexed), h.computeWorldMatrix(!0), h.synchronizeInstances();
      }
    }
    this._notifyUpdate(s);
  }
  /**
   * 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(e, t, i, s = !1) {
    const r = this.getVertexBuffer(e);
    r && (r.updateDirectly(t, i, s), this._notifyUpdate(e));
  }
  /**
   * 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(e, t, i = !1) {
    const s = this.getVertexBuffer(e);
    s && (s.update(t), e === _.PositionKind && this._updateBoundingInfo(i, t), this._notifyUpdate(e));
  }
  _updateBoundingInfo(e, t) {
    if (e && this._updateExtend(t), this._resetPointsArrayCache(), e) {
      const i = this._meshes;
      for (const s of i) {
        s.hasBoundingInfo ? s.getBoundingInfo().reConstruct(this._extend.minimum, this._extend.maximum) : s.buildBoundingInfo(this._extend.minimum, this._extend.maximum);
        const r = s.subMeshes;
        for (const n of r)
          n.refreshBoundingInfo();
      }
    }
  }
  /**
   * @internal
   */
  _bind(e, t, i, s) {
    if (!e)
      return;
    t === void 0 && (t = this._indexBuffer);
    const r = this.getVertexBuffers();
    if (!r)
      return;
    if (t != this._indexBuffer || !this._vertexArrayObjects && !s) {
      this._engine.bindBuffers(r, t, e, i);
      return;
    }
    const n = s || this._vertexArrayObjects;
    n[e.key] || (n[e.key] = this._engine.recordVertexArrayObject(r, t, e, i)), this._engine.bindVertexArrayObject(n[e.key], t);
  }
  /**
   * Gets total number of vertices
   * @returns the total number of vertices
   */
  getTotalVertices() {
    return this.isReady() ? this._totalVertices : 0;
  }
  /**
   * 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(e, t, i) {
    const s = this.getVertexBuffer(e);
    return s ? s.getFloatData(this._totalVertices, i || t && this._meshes.length !== 1) : null;
  }
  /**
   * 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(e) {
    const t = this._vertexBuffers[e];
    return t ? t.isUpdatable() : !1;
  }
  /**
   * Gets a specific vertex buffer
   * @param kind defines the data kind (Position, normal, etc...)
   * @returns a VertexBuffer
   */
  getVertexBuffer(e) {
    return this.isReady() ? this._vertexBuffers[e] : null;
  }
  /**
   * Returns all vertex buffers
   * @returns an object holding all vertex buffers indexed by kind
   */
  getVertexBuffers() {
    return this.isReady() ? this._vertexBuffers : null;
  }
  /**
   * 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(e) {
    return this._vertexBuffers ? this._vertexBuffers[e] !== void 0 : this._delayInfo ? this._delayInfo.indexOf(e) !== -1 : !1;
  }
  /**
   * Gets a list of all attached data kinds (Position, normal, etc...)
   * @returns a list of string containing all kinds
   */
  getVerticesDataKinds() {
    const e = [];
    let t;
    if (!this._vertexBuffers && this._delayInfo)
      for (t in this._delayInfo)
        e.push(t);
    else
      for (t in this._vertexBuffers)
        e.push(t);
    return e;
  }
  /**
   * 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(e, t, i = !1) {
    if (this._indexBuffer)
      if (!this._indexBufferIsUpdatable)
        this.setIndices(e, null, !0);
      else {
        const s = e.length !== this._indices.length;
        if (i || (this._indices = e.slice()), this._engine.updateDynamicIndexBuffer(this._indexBuffer, e, t), s)
          for (const r of this._meshes)
            r._createGlobalSubMesh(!0);
      }
  }
  /**
   * 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)
   */
  setIndices(e, t = null, i = !1) {
    this._indexBuffer && this._engine._releaseBuffer(this._indexBuffer), this._indices = e, this._indexBufferIsUpdatable = i, this._meshes.length !== 0 && this._indices && (this._indexBuffer = this._engine.createIndexBuffer(this._indices, i)), t != null && (this._totalVertices = t);
    for (const s of this._meshes)
      s._createGlobalSubMesh(!0), s.synchronizeInstances();
    this._notifyUpdate();
  }
  /**
   * Return the total number of indices
   * @returns the total number of indices
   */
  getTotalIndices() {
    return this.isReady() ? this._indices.length : 0;
  }
  /**
   * 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(e, t) {
    if (!this.isReady())
      return null;
    const i = this._indices;
    return !t && (!e || this._meshes.length === 1) ? i : i.slice();
  }
  /**
   * Gets the index buffer
   * @returns the index buffer
   */
  getIndexBuffer() {
    return this.isReady() ? this._indexBuffer : null;
  }
  /**
   * @internal
   */
  _releaseVertexArrayObject(e = null) {
    !e || !this._vertexArrayObjects || this._vertexArrayObjects[e.key] && (this._engine.releaseVertexArrayObject(this._vertexArrayObjects[e.key]), delete this._vertexArrayObjects[e.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(e, t) {
    const i = this._meshes, s = i.indexOf(e);
    s !== -1 && (i.splice(s, 1), this._vertexArrayObjects && e._invalidateInstanceVertexArrayObject(), e._geometry = null, i.length === 0 && t && this.dispose());
  }
  /**
   * Apply current geometry to a given mesh
   * @param mesh defines the mesh to apply geometry to
   */
  applyToMesh(e) {
    if (e._geometry === this)
      return;
    const t = e._geometry;
    t && t.releaseForMesh(e), this._vertexArrayObjects && e._invalidateInstanceVertexArrayObject();
    const i = this._meshes;
    e._geometry = this, e._internalAbstractMeshDataInfo._positions = null, this._scene.pushGeometry(this), i.push(e), this.isReady() ? this._applyToMesh(e) : this._boundingInfo && e.setBoundingInfo(this._boundingInfo);
  }
  _updateExtend(e = null) {
    if (this.useBoundingInfoFromGeometry && this._boundingInfo)
      this._extend = {
        minimum: this._boundingInfo.minimum.clone(),
        maximum: this._boundingInfo.maximum.clone()
      };
    else {
      if (!e && (e = this.getVerticesData(_.PositionKind), !e))
        return;
      this._extend = gs(e, 0, this._totalVertices, this.boundingBias, 3);
    }
  }
  _applyToMesh(e) {
    const t = this._meshes.length;
    for (const i in this._vertexBuffers)
      t === 1 && this._vertexBuffers[i].create(), i === _.PositionKind && (this._extend || this._updateExtend(), e.buildBoundingInfo(this._extend.minimum, this._extend.maximum), e._createGlobalSubMesh(e.isUnIndexed), e._updateBoundingInfo());
    t === 1 && this._indices && this._indices.length > 0 && (this._indexBuffer = this._engine.createIndexBuffer(this._indices, this._updatable)), e._syncGeometryWithMorphTargetManager(), e.synchronizeInstances();
  }
  _notifyUpdate(e) {
    this.onGeometryUpdated && this.onGeometryUpdated(this, e), this._vertexArrayObjects && this._disposeVertexArrayObjects();
    for (const t of this._meshes)
      t._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(e, t) {
    if (this.delayLoadState !== 2) {
      if (this.isReady()) {
        t && t();
        return;
      }
      this.delayLoadState = 2, this._queueLoad(e, t);
    }
  }
  _queueLoad(e, t) {
    this.delayLoadingFile && (e.addPendingData(this), e._loadFile(this.delayLoadingFile, (i) => {
      if (!this._delayLoadingFunction)
        return;
      this._delayLoadingFunction(JSON.parse(i), this), this.delayLoadState = 1, this._delayInfo = [], e.removePendingData(this);
      const s = this._meshes, r = s.length;
      for (let n = 0; n < r; n++)
        this._applyToMesh(s[n]);
      t && t();
    }, void 0, !0));
  }
  /**
   * Invert the geometry to move from a right handed system to a left handed one.
   */
  toLeftHanded() {
    const e = this.getIndices(!1);
    if (e != null && e.length > 0) {
      for (let s = 0; s < e.length; s += 3) {
        const r = e[s + 0];
        e[s + 0] = e[s + 2], e[s + 2] = r;
      }
      this.setIndices(e);
    }
    const t = this.getVerticesData(_.PositionKind, !1);
    if (t != null && t.length > 0) {
      for (let s = 0; s < t.length; s += 3)
        t[s + 2] = -t[s + 2];
      this.setVerticesData(_.PositionKind, t, !1);
    }
    const i = this.getVerticesData(_.NormalKind, !1);
    if (i != null && i.length > 0) {
      for (let s = 0; s < i.length; s += 3)
        i[s + 2] = -i[s + 2];
      this.setVerticesData(_.NormalKind, i, !1);
    }
  }
  // Cache
  /** @internal */
  _resetPointsArrayCache() {
    this._positions = null;
  }
  /** @internal */
  _generatePointsArray() {
    if (this._positions)
      return !0;
    const e = this.getVerticesData(_.PositionKind);
    if (!e || e.length === 0)
      return !1;
    for (let t = this._positionsCache.length * 3, i = this._positionsCache.length; t < e.length; t += 3, ++i)
      this._positionsCache[i] = p.FromArray(e, t);
    for (let t = 0, i = 0; t < e.length; t += 3, ++i)
      this._positionsCache[i].set(e[0 + t], e[1 + t], e[2 + t]);
    return this._positionsCache.length = e.length / 3, this._positions = this._positionsCache, !0;
  }
  /**
   * 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 i in this._vertexArrayObjects)
        this._engine.releaseVertexArrayObject(this._vertexArrayObjects[i]);
      this._vertexArrayObjects = {};
      const e = this._meshes, t = e.length;
      for (let i = 0; i < t; i++)
        e[i]._invalidateInstanceVertexArrayObject();
    }
  }
  /**
   * Free all associated resources
   */
  dispose() {
    const e = this._meshes, t = e.length;
    let i;
    for (i = 0; i < t; i++)
      this.releaseForMesh(e[i]);
    this._meshes.length = 0, this._disposeVertexArrayObjects();
    for (const s in this._vertexBuffers)
      this._vertexBuffers[s].dispose();
    if (this._vertexBuffers = {}, this._totalVertices = 0, 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), this._parentContainer) {
      const s = this._parentContainer.geometries.indexOf(this);
      s > -1 && this._parentContainer.geometries.splice(s, 1), this._parentContainer = null;
    }
    this._isDisposed = !0;
  }
  /**
   * Clone the current geometry into a new geometry
   * @param id defines the unique ID of the new geometry
   * @returns a new geometry object
   */
  copy(e) {
    const t = new q();
    t.indices = [];
    const i = this.getIndices();
    if (i)
      for (let o = 0; o < i.length; o++)
        t.indices.push(i[o]);
    let s = !1, r = !1, n;
    for (n in this._vertexBuffers) {
      const o = this.getVerticesData(n);
      if (o && (o instanceof Float32Array ? t.set(new Float32Array(o), n) : t.set(o.slice(0), n), !r)) {
        const h = this.getVertexBuffer(n);
        h && (s = h.isUpdatable(), r = !s);
      }
    }
    const a = new Ve(e, this._scene, t, s);
    a.delayLoadState = this.delayLoadState, a.delayLoadingFile = this.delayLoadingFile, a._delayLoadingFunction = this._delayLoadingFunction;
    for (n in this._delayInfo)
      a._delayInfo = a._delayInfo || [], a._delayInfo.push(n);
    return a._boundingInfo = new qe(this._extend.minimum, this._extend.maximum), a;
  }
  /**
   * 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 e = {};
    return e.id = this.id, e.uniqueId = this.uniqueId, e.updatable = this._updatable, re && re.HasTags(this) && (e.tags = re.GetTags(this)), e;
  }
  _toNumberArray(e) {
    return Array.isArray(e) ? e : Array.prototype.slice.call(e);
  }
  /**
   * 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 e in this._vertexBuffers)
      Object.prototype.hasOwnProperty.call(this._vertexBuffers, e) && (this._vertexBuffers[e]._buffer._data = null);
  }
  /**
   * Serialize all vertices data into a JSON object
   * @returns a JSON representation of the current geometry data
   */
  serializeVerticeData() {
    const e = this.serialize();
    return this.isVerticesDataPresent(_.PositionKind) && (e.positions = this._toNumberArray(this.getVerticesData(_.PositionKind)), this.isVertexBufferUpdatable(_.PositionKind) && (e.positions._updatable = !0)), this.isVerticesDataPresent(_.NormalKind) && (e.normals = this._toNumberArray(this.getVerticesData(_.NormalKind)), this.isVertexBufferUpdatable(_.NormalKind) && (e.normals._updatable = !0)), this.isVerticesDataPresent(_.TangentKind) && (e.tangents = this._toNumberArray(this.getVerticesData(_.TangentKind)), this.isVertexBufferUpdatable(_.TangentKind) && (e.tangents._updatable = !0)), this.isVerticesDataPresent(_.UVKind) && (e.uvs = this._toNumberArray(this.getVerticesData(_.UVKind)), this.isVertexBufferUpdatable(_.UVKind) && (e.uvs._updatable = !0)), this.isVerticesDataPresent(_.UV2Kind) && (e.uv2s = this._toNumberArray(this.getVerticesData(_.UV2Kind)), this.isVertexBufferUpdatable(_.UV2Kind) && (e.uv2s._updatable = !0)), this.isVerticesDataPresent(_.UV3Kind) && (e.uv3s = this._toNumberArray(this.getVerticesData(_.UV3Kind)), this.isVertexBufferUpdatable(_.UV3Kind) && (e.uv3s._updatable = !0)), this.isVerticesDataPresent(_.UV4Kind) && (e.uv4s = this._toNumberArray(this.getVerticesData(_.UV4Kind)), this.isVertexBufferUpdatable(_.UV4Kind) && (e.uv4s._updatable = !0)), this.isVerticesDataPresent(_.UV5Kind) && (e.uv5s = this._toNumberArray(this.getVerticesData(_.UV5Kind)), this.isVertexBufferUpdatable(_.UV5Kind) && (e.uv5s._updatable = !0)), this.isVerticesDataPresent(_.UV6Kind) && (e.uv6s = this._toNumberArray(this.getVerticesData(_.UV6Kind)), this.isVertexBufferUpdatable(_.UV6Kind) && (e.uv6s._updatable = !0)), this.isVerticesDataPresent(_.ColorKind) && (e.colors = this._toNumberArray(this.getVerticesData(_.ColorKind)), this.isVertexBufferUpdatable(_.ColorKind) && (e.colors._updatable = !0)), this.isVerticesDataPresent(_.MatricesIndicesKind) && (e.matricesIndices = this._toNumberArray(this.getVerticesData(_.MatricesIndicesKind)), e.matricesIndices._isExpanded = !0, this.isVertexBufferUpdatable(_.MatricesIndicesKind) && (e.matricesIndices._updatable = !0)), this.isVerticesDataPresent(_.MatricesWeightsKind) && (e.matricesWeights = this._toNumberArray(this.getVerticesData(_.MatricesWeightsKind)), this.isVertexBufferUpdatable(_.MatricesWeightsKind) && (e.matricesWeights._updatable = !0)), e.indices = this._toNumberArray(this.getIndices()), e;
  }
  // 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(e, t) {
    const i = e._geometry;
    return i ? i.copy(t) : null;
  }
  /**
   * 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 k.RandomId();
  }
  static _GetGeometryByLoadedUniqueId(e, t) {
    for (let i = 0; i < t.geometries.length; i++)
      if (t.geometries[i]._loadedUniqueId === e)
        return t.geometries[i];
    return null;
  }
  /**
   * @internal
   */
  static _ImportGeometry(e, t) {
    const i = t.getScene(), s = e.geometryUniqueId, r = e.geometryId;
    if (s || r) {
      const n = s ? this._GetGeometryByLoadedUniqueId(s, i) : i.getGeometryById(r);
      n && n.applyToMesh(t);
    } else if (e instanceof ArrayBuffer) {
      const n = t._binaryInfo;
      if (n.positionsAttrDesc && n.positionsAttrDesc.count > 0) {
        const a = new Float32Array(e, n.positionsAttrDesc.offset, n.positionsAttrDesc.count);
        t.setVerticesData(_.PositionKind, a, !1);
      }
      if (n.normalsAttrDesc && n.normalsAttrDesc.count > 0) {
        const a = new Float32Array(e, n.normalsAttrDesc.offset, n.normalsAttrDesc.count);
        t.setVerticesData(_.NormalKind, a, !1);
      }
      if (n.tangetsAttrDesc && n.tangetsAttrDesc.count > 0) {
        const a = new Float32Array(e, n.tangetsAttrDesc.offset, n.tangetsAttrDesc.count);
        t.setVerticesData(_.TangentKind, a, !1);
      }
      if (n.uvsAttrDesc && n.uvsAttrDesc.count > 0) {
        const a = new Float32Array(e, n.uvsAttrDesc.offset, n.uvsAttrDesc.count);
        if (Rt.UseOpenGLOrientationForUV)
          for (let o = 1; o < a.length; o += 2)
            a[o] = 1 - a[o];
        t.setVerticesData(_.UVKind, a, !1);
      }
      if (n.uvs2AttrDesc && n.uvs2AttrDesc.count > 0) {
        const a = new Float32Array(e, n.uvs2AttrDesc.offset, n.uvs2AttrDesc.count);
        if (Rt.UseOpenGLOrientationForUV)
          for (let o = 1; o < a.length; o += 2)
            a[o] = 1 - a[o];
        t.setVerticesData(_.UV2Kind, a, !1);
      }
      if (n.uvs3AttrDesc && n.uvs3AttrDesc.count > 0) {
        const a = new Float32Array(e, n.uvs3AttrDesc.offset, n.uvs3AttrDesc.count);
        if (Rt.UseOpenGLOrientationForUV)
          for (let o = 1; o < a.length; o += 2)
            a[o] = 1 - a[o];
        t.setVerticesData(_.UV3Kind, a, !1);
      }
      if (n.uvs4AttrDesc && n.uvs4AttrDesc.count > 0) {
        const a = new Float32Array(e, n.uvs4AttrDesc.offset, n.uvs4AttrDesc.count);
        if (Rt.UseOpenGLOrientationForUV)
          for (let o = 1; o < a.length; o += 2)
            a[o] = 1 - a[o];
        t.setVerticesData(_.UV4Kind, a, !1);
      }
      if (n.uvs5AttrDesc && n.uvs5AttrDesc.count > 0) {
        const a = new Float32Array(e, n.uvs5AttrDesc.offset, n.uvs5AttrDesc.count);
        if (Rt.UseOpenGLOrientationForUV)
          for (let o = 1; o < a.length; o += 2)
            a[o] = 1 - a[o];
        t.setVerticesData(_.UV5Kind, a, !1);
      }
      if (n.uvs6AttrDesc && n.uvs6AttrDesc.count > 0) {
        const a = new Float32Array(e, n.uvs6AttrDesc.offset, n.uvs6AttrDesc.count);
        if (Rt.UseOpenGLOrientationForUV)
          for (let o = 1; o < a.length; o += 2)
            a[o] = 1 - a[o];
        t.setVerticesData(_.UV6Kind, a, !1);
      }
      if (n.colorsAttrDesc && n.colorsAttrDesc.count > 0) {
        const a = new Float32Array(e, n.colorsAttrDesc.offset, n.colorsAttrDesc.count);
        t.setVerticesData(_.ColorKind, a, !1, n.colorsAttrDesc.stride);
      }
      if (n.matricesIndicesAttrDesc && n.matricesIndicesAttrDesc.count > 0) {
        const a = new Int32Array(e, n.matricesIndicesAttrDesc.offset, n.matricesIndicesAttrDesc.count), o = [];
        for (let h = 0; h < a.length; h++) {
          const c = a[h];
          o.push(c & 255), o.push((c & 65280) >> 8), o.push((c & 16711680) >> 16), o.push(c >> 24 & 255);
        }
        t.setVerticesData(_.MatricesIndicesKind, o, !1);
      }
      if (n.matricesIndicesExtraAttrDesc && n.matricesIndicesExtraAttrDesc.count > 0) {
        const a = new Int32Array(e, n.matricesIndicesExtraAttrDesc.offset, n.matricesIndicesExtraAttrDesc.count), o = [];
        for (let h = 0; h < a.length; h++) {
          const c = a[h];
          o.push(c & 255), o.push((c & 65280) >> 8), o.push((c & 16711680) >> 16), o.push(c >> 24 & 255);
        }
        t.setVerticesData(_.MatricesIndicesExtraKind, o, !1);
      }
      if (n.matricesWeightsAttrDesc && n.matricesWeightsAttrDesc.count > 0) {
        const a = new Float32Array(e, n.matricesWeightsAttrDesc.offset, n.matricesWeightsAttrDesc.count);
        t.setVerticesData(_.MatricesWeightsKind, a, !1);
      }
      if (n.indicesAttrDesc && n.indicesAttrDesc.count > 0) {
        const a = new Int32Array(e, n.indicesAttrDesc.offset, n.indicesAttrDesc.count);
        t.setIndices(a, null);
      }
      if (n.subMeshesAttrDesc && n.subMeshesAttrDesc.count > 0) {
        const a = new Int32Array(e, n.subMeshesAttrDesc.offset, n.subMeshesAttrDesc.count * 5);
        t.subMeshes = [];
        for (let o = 0; o < n.subMeshesAttrDesc.count; o++) {
          const h = a[o * 5 + 0], c = a[o * 5 + 1], u = a[o * 5 + 2], d = a[o * 5 + 3], g = a[o * 5 + 4];
          Ye.AddToMesh(h, c, u, d, g, t);
        }
      }
    } else if (e.positions && e.normals && e.indices) {
      if (t.setVerticesData(_.PositionKind, e.positions, e.positions._updatable), t.setVerticesData(_.NormalKind, e.normals, e.normals._updatable), e.tangents && t.setVerticesData(_.TangentKind, e.tangents, e.tangents._updatable), e.uvs && t.setVerticesData(_.UVKind, e.uvs, e.uvs._updatable), e.uvs2 && t.setVerticesData(_.UV2Kind, e.uvs2, e.uvs2._updatable), e.uvs3 && t.setVerticesData(_.UV3Kind, e.uvs3, e.uvs3._updatable), e.uvs4 && t.setVerticesData(_.UV4Kind, e.uvs4, e.uvs4._updatable), e.uvs5 && t.setVerticesData(_.UV5Kind, e.uvs5, e.uvs5._updatable), e.uvs6 && t.setVerticesData(_.UV6Kind, e.uvs6, e.uvs6._updatable), e.colors && t.setVerticesData(_.ColorKind, Oe.CheckColors4(e.colors, e.positions.length / 3), e.colors._updatable), e.matricesIndices)
        if (e.matricesIndices._isExpanded)
          delete e.matricesIndices._isExpanded, t.setVerticesData(_.MatricesIndicesKind, e.matricesIndices, e.matricesIndices._updatable);
        else {
          const n = [];
          for (let a = 0; a < e.matricesIndices.length; a++) {
            const o = e.matricesIndices[a];
            n.push(o & 255), n.push((o & 65280) >> 8), n.push((o & 16711680) >> 16), n.push(o >> 24 & 255);
          }
          t.setVerticesData(_.MatricesIndicesKind, n, e.matricesIndices._updatable);
        }
      if (e.matricesIndicesExtra)
        if (e.matricesIndicesExtra._isExpanded)
          delete e.matricesIndices._isExpanded, t.setVerticesData(_.MatricesIndicesExtraKind, e.matricesIndicesExtra, e.matricesIndicesExtra._updatable);
        else {
          const n = [];
          for (let a = 0; a < e.matricesIndicesExtra.length; a++) {
            const o = e.matricesIndicesExtra[a];
            n.push(o & 255), n.push((o & 65280) >> 8), n.push((o & 16711680) >> 16), n.push(o >> 24 & 255);
          }
          t.setVerticesData(_.MatricesIndicesExtraKind, n, e.matricesIndicesExtra._updatable);
        }
      e.matricesWeights && (Ve._CleanMatricesWeights(e, t), t.setVerticesData(_.MatricesWeightsKind, e.matricesWeights, e.matricesWeights._updatable)), e.matricesWeightsExtra && t.setVerticesData(_.MatricesWeightsExtraKind, e.matricesWeightsExtra, e.matricesWeights._updatable), t.setIndices(e.indices, null);
    }
    if (e.subMeshes) {
      t.subMeshes = [];
      for (let n = 0; n < e.subMeshes.length; n++) {
        const a = e.subMeshes[n];
        Ye.AddToMesh(a.materialIndex, a.verticesStart, a.verticesCount, a.indexStart, a.indexCount, t);
      }
    }
    t._shouldGenerateFlatShading && (t.convertToFlatShadedMesh(), t._shouldGenerateFlatShading = !1), t.computeWorldMatrix(!0), i.onMeshImportedObservable.notifyObservers(t);
  }
  static _CleanMatricesWeights(e, t) {
    if (!pe.CleanBoneMatrixWeights)
      return;
    let s = 0;
    if (e.skeletonId > -1) {
      const u = t.getScene().getLastSkeletonById(e.skeletonId);
      if (!u)
        return;
      s = u.bones.length;
    } else
      return;
    const r = t.getVerticesData(_.MatricesIndicesKind), n = t.getVerticesData(_.MatricesIndicesExtraKind), a = e.matricesWeights, o = e.matricesWeightsExtra, h = e.numBoneInfluencer, c = a.length;
    for (let u = 0; u < c; u += 4) {
      let d = 0, g = -1;
      for (let f = 0; f < 4; f++) {
        const m = a[u + f];
        d += m, m < 1e-3 && g < 0 && (g = f);
      }
      if (o)
        for (let f = 0; f < 4; f++) {
          const m = o[u + f];
          d += m, m < 1e-3 && g < 0 && (g = f + 4);
        }
      if ((g < 0 || g > h - 1) && (g = h - 1), d > 1e-3) {
        const f = 1 / d;
        for (let m = 0; m < 4; m++)
          a[u + m] *= f;
        if (o)
          for (let m = 0; m < 4; m++)
            o[u + m] *= f;
      } else
        g >= 4 ? (o[u + g - 4] = 1 - d, n[u + g - 4] = s) : (a[u + g] = 1 - d, r[u + g] = s);
    }
    t.setVerticesData(_.MatricesIndicesKind, r), e.matricesWeightsExtra && t.setVerticesData(_.MatricesIndicesExtraKind, n);
  }
  /**
   * 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(e, t, i) {
    const s = new Ve(e.id, t, void 0, e.updatable);
    return s._loadedUniqueId = e.uniqueId, re && re.AddTagsTo(s, e.tags), e.delayLoadingFile ? (s.delayLoadState = 4, s.delayLoadingFile = i + e.delayLoadingFile, s._boundingInfo = new qe(p.FromArray(e.boundingBoxMinimum), p.FromArray(e.boundingBoxMaximum)), s._delayInfo = [], e.hasUVs && s._delayInfo.push(_.UVKind), e.hasUVs2 && s._delayInfo.push(_.UV2Kind), e.hasUVs3 && s._delayInfo.push(_.UV3Kind), e.hasUVs4 && s._delayInfo.push(_.UV4Kind), e.hasUVs5 && s._delayInfo.push(_.UV5Kind), e.hasUVs6 && s._delayInfo.push(_.UV6Kind), e.hasColors && s._delayInfo.push(_.ColorKind), e.hasMatricesIndices && s._delayInfo.push(_.MatricesIndicesKind), e.hasMatricesWeights && s._delayInfo.push(_.MatricesWeightsKind), s._delayLoadingFunction = q.ImportVertexData) : q.ImportVertexData(e, s), t.pushGeometry(s, !0), s;
  }
}
var ot;
(function(l) {
  l[l.LOCAL = 0] = "LOCAL", l[l.WORLD = 1] = "WORLD", l[l.BONE = 2] = "BONE";
})(ot || (ot = {}));
class ci {
}
ci.X = new p(1, 0, 0);
ci.Y = new p(0, 1, 0);
ci.Z = new p(0, 0, 1);
var es;
(function(l) {
  l[l.X = 0] = "X", l[l.Y = 1] = "Y", l[l.Z = 2] = "Z";
})(es || (es = {}));
class z extends Ne {
  /**
   * 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(e) {
    this._billboardMode !== e && (this._billboardMode = e, this._cache.useBillboardPosition = (this._billboardMode & z.BILLBOARDMODE_USE_POSITION) !== 0, this._computeUseBillboardPath());
  }
  /**
   * Gets or sets a boolean indicating that parent rotation should be preserved when using billboards.
   * This could be useful for glTF objects where parent rotation helps converting from right handed to left handed
   */
  get preserveParentRotationForBillboard() {
    return this._preserveParentRotationForBillboard;
  }
  set preserveParentRotationForBillboard(e) {
    e !== this._preserveParentRotationForBillboard && (this._preserveParentRotationForBillboard = e, this._computeUseBillboardPath());
  }
  _computeUseBillboardPath() {
    this._cache.useBillboardPath = this._billboardMode !== z.BILLBOARDMODE_NONE && !this.preserveParentRotationForBillboard;
  }
  /**
   * Gets or sets the distance of the object to max, often used by skybox
   */
  get infiniteDistance() {
    return this._infiniteDistance;
  }
  set infiniteDistance(e) {
    this._infiniteDistance !== e && (this._infiniteDistance = e);
  }
  constructor(e, t = null, i = !0) {
    super(e, t), this._forward = new p(0, 0, 1), this._up = new p(0, 1, 0), this._right = new p(1, 0, 0), this._position = p.Zero(), this._rotation = p.Zero(), this._rotationQuaternion = null, this._scaling = p.One(), this._transformToBoneReferal = null, this._isAbsoluteSynced = !1, this._billboardMode = z.BILLBOARDMODE_NONE, this._preserveParentRotationForBillboard = !1, this.scalingDeterminant = 1, this._infiniteDistance = !1, this.ignoreNonUniformScaling = !1, this.reIntegrateRotationIntoRotationQuaternion = !1, this._poseMatrix = null, this._localMatrix = R.Zero(), this._usePivotMatrix = !1, this._absolutePosition = p.Zero(), this._absoluteScaling = p.Zero(), this._absoluteRotationQuaternion = X.Identity(), this._pivotMatrix = R.Identity(), this._postMultiplyPivotMatrix = !1, this._isWorldMatrixFrozen = !1, this._indexInSceneTransformNodesArray = -1, this.onAfterWorldMatrixUpdateObservable = new w(), this._nonUniformScaling = !1, i && 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(e) {
    this._position = e, this._isDirty = !0;
  }
  /**
   * return true if a pivot has been set
   * @returns true if a pivot matrix is used
   */
  isUsingPivotMatrix() {
    return this._usePivotMatrix;
  }
  /**
   * 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(e) {
    this._rotation = e, this._rotationQuaternion = null, this._isDirty = !0;
  }
  /**
   * 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(e) {
    this._scaling = e, this._isDirty = !0;
  }
  /**
   * 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(e) {
    this._rotationQuaternion = e, e && this._rotation.setAll(0), this._isDirty = !0;
  }
  /**
   * The forward direction of that transform in world space.
   */
  get forward() {
    return p.TransformNormalFromFloatsToRef(0, 0, this.getScene().useRightHandedSystem ? -1 : 1, this.getWorldMatrix(), this._forward), this._forward.normalize();
  }
  /**
   * The up direction of that transform in world space.
   */
  get up() {
    return p.TransformNormalFromFloatsToRef(0, 1, 0, this.getWorldMatrix(), this._up), this._up.normalize();
  }
  /**
   * The right direction of that transform in world space.
   */
  get right() {
    return p.TransformNormalFromFloatsToRef(this.getScene().useRightHandedSystem ? -1 : 1, 0, 0, this.getWorldMatrix(), this._right), 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(e) {
    return this._poseMatrix ? (this._poseMatrix.copyFrom(e), this) : (this._poseMatrix = e.clone(), this);
  }
  /**
   * Returns the mesh Pose matrix.
   * @returns the pose matrix
   */
  getPoseMatrix() {
    return this._poseMatrix || (this._poseMatrix = R.Identity()), this._poseMatrix;
  }
  /** @internal */
  _isSynchronized() {
    const e = this._cache;
    return !(this._billboardMode !== e.billboardMode || this._billboardMode !== z.BILLBOARDMODE_NONE || e.pivotMatrixUpdated || this._infiniteDistance || this._position._isDirty || this._scaling._isDirty || this._rotationQuaternion && this._rotationQuaternion._isDirty || this._rotation._isDirty);
  }
  /** @internal */
  _initCache() {
    super._initCache();
    const e = this._cache;
    e.localMatrixUpdated = !1, e.billboardMode = -1, e.infiniteDistance = !1, e.useBillboardPosition = !1, e.useBillboardPath = !1;
  }
  /**
   * 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() {
    return this._syncAbsoluteScalingAndRotation(), this._absoluteScaling;
  }
  /**
   * Returns the current mesh absolute rotation.
   * Returns a Quaternion.
   */
  get absoluteRotationQuaternion() {
    return this._syncAbsoluteScalingAndRotation(), this._absoluteRotationQuaternion;
  }
  /**
   * Sets a new matrix to apply before all other transformation
   * @param matrix defines the transform matrix
   * @returns the current TransformNode
   */
  setPreTransformMatrix(e) {
    return this.setPivotMatrix(e, !1);
  }
  /**
   * 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(e, t = !0) {
    return this._pivotMatrix.copyFrom(e), this._usePivotMatrix = !this._pivotMatrix.isIdentity(), this._cache.pivotMatrixUpdated = !0, this._postMultiplyPivotMatrix = t, this._postMultiplyPivotMatrix && (this._pivotMatrixInverse ? this._pivotMatrix.invertToRef(this._pivotMatrixInverse) : this._pivotMatrixInverse = R.Invert(this._pivotMatrix)), 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(e = null, t, i) {
    const s = this.clone("Clone of " + (this.name || this.id), e || this.parent, !0);
    s && i && i(this, s);
    for (const r of this.getChildTransformNodes(!0))
      r.instantiateHierarchy(s, t, i);
    return s;
  }
  /**
   * Prevents the World matrix to be computed any longer
   * @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(e = null, t = !1) {
    return e ? t ? (this._rotation.setAll(0), this._rotationQuaternion = this._rotationQuaternion || X.Identity(), e.decompose(this._scaling, this._rotationQuaternion, this._position), this.computeWorldMatrix(!0)) : (this._worldMatrix = e, this._absolutePosition.copyFromFloats(this._worldMatrix.m[12], this._worldMatrix.m[13], this._worldMatrix.m[14]), this._afterComputeWorldMatrix()) : (this._isWorldMatrixFrozen = !1, this.computeWorldMatrix(!0)), this._isDirty = !1, this._isWorldMatrixFrozen = !0, this;
  }
  /**
   * Allows back the World matrix computation.
   * @returns the TransformNode.
   */
  unfreezeWorldMatrix() {
    return this._isWorldMatrixFrozen = !1, this.computeWorldMatrix(!0), 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() {
    return this.computeWorldMatrix(), 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(e) {
    if (!e)
      return this;
    let t, i, s;
    if (e.x === void 0) {
      if (arguments.length < 3)
        return this;
      t = arguments[0], i = arguments[1], s = arguments[2];
    } else
      t = e.x, i = e.y, s = e.z;
    if (this.parent) {
      const r = C.Matrix[0];
      this.parent.getWorldMatrix().invertToRef(r), p.TransformCoordinatesFromFloatsToRef(t, i, s, r, this.position);
    } else
      this.position.x = t, this.position.y = i, this.position.z = s;
    return this._absolutePosition.copyFrom(e), this;
  }
  /**
   * Sets the mesh position in its local space.
   * @param vector3 the position to set in localspace
   * @returns the TransformNode.
   */
  setPositionWithLocalVector(e) {
    return this.computeWorldMatrix(), this.position = p.TransformNormal(e, this._localMatrix), this;
  }
  /**
   * Returns the mesh position in the local space from the current World matrix values.
   * @returns a new Vector3.
   */
  getPositionExpressedInLocalSpace() {
    this.computeWorldMatrix();
    const e = C.Matrix[0];
    return this._localMatrix.invertToRef(e), p.TransformNormal(this.position, e);
  }
  /**
   * Translates the mesh along the passed Vector3 in its local space.
   * @param vector3 the distance to translate in localspace
   * @returns the TransformNode.
   */
  locallyTranslate(e) {
    return this.computeWorldMatrix(!0), this.position = p.TransformCoordinates(e, this._localMatrix), 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(e, t = 0, i = 0, s = 0, r = ot.LOCAL) {
    const n = z._LookAtVectorCache, a = r === ot.LOCAL ? this.position : this.getAbsolutePosition();
    if (e.subtractToRef(a, n), this.setDirection(n, t, i, s), r === ot.WORLD && this.parent)
      if (this.rotationQuaternion) {
        const o = C.Matrix[0];
        this.rotationQuaternion.toRotationMatrix(o);
        const h = C.Matrix[1];
        this.parent.getWorldMatrix().getRotationMatrixToRef(h), h.invert(), o.multiplyToRef(h, o), this.rotationQuaternion.fromRotationMatrix(o);
      } else {
        const o = C.Quaternion[0];
        X.FromEulerVectorToRef(this.rotation, o);
        const h = C.Matrix[0];
        o.toRotationMatrix(h);
        const c = C.Matrix[1];
        this.parent.getWorldMatrix().getRotationMatrixToRef(c), c.invert(), h.multiplyToRef(c, h), o.fromRotationMatrix(h), o.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(e) {
    const t = p.Zero();
    return this.getDirectionToRef(e, t), t;
  }
  /**
   * 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(e, t) {
    return p.TransformNormalToRef(e, this.getWorldMatrix(), t), 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(e, t = 0, i = 0, s = 0) {
    const r = -Math.atan2(e.z, e.x) + Math.PI / 2, n = Math.sqrt(e.x * e.x + e.z * e.z), a = -Math.atan2(e.y, n);
    return this.rotationQuaternion ? X.RotationYawPitchRollToRef(r + t, a + i, s, this.rotationQuaternion) : (this.rotation.x = a + i, this.rotation.y = r + t, this.rotation.z = s), 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(e, t = ot.LOCAL) {
    this.getScene().getRenderId() == 0 && this.computeWorldMatrix(!0);
    const i = this.getWorldMatrix();
    if (t == ot.WORLD) {
      const s = C.Matrix[0];
      i.invertToRef(s), e = p.TransformCoordinates(e, s);
    }
    return this.setPivotMatrix(R.Translation(-e.x, -e.y, -e.z), !0);
  }
  /**
   * Returns a new Vector3 set with the mesh pivot point coordinates in the local space.
   * @returns the pivot point
   */
  getPivotPoint() {
    const e = p.Zero();
    return this.getPivotPointToRef(e), e;
  }
  /**
   * 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(e) {
    return e.x = -this._pivotMatrix.m[12], e.y = -this._pivotMatrix.m[13], e.z = -this._pivotMatrix.m[14], 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 e = p.Zero();
    return this.getAbsolutePivotPointToRef(e), e;
  }
  /**
   * Sets the Vector3 "result" coordinates with the mesh pivot point World coordinates.
   * @param result vector3 to store the result
   * @returns this TransformNode.
   */
  getAbsolutePivotPointToRef(e) {
    return this.getPivotPointToRef(e), p.TransformCoordinatesToRef(e, this.getWorldMatrix(), e), 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(e) {
    if (this._isDirty)
      return this;
    if (this._children)
      for (const t of this._children)
        t.markAsDirty(e);
    return super.markAsDirty(e);
  }
  /**
   * 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.
   * 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(e, t = !1, i = !1) {
    if (!e && !this.parent)
      return this;
    const s = C.Quaternion[0], r = C.Vector3[0], n = C.Vector3[1], a = C.Matrix[1];
    R.IdentityToRef(a);
    const o = C.Matrix[0];
    this.computeWorldMatrix(!0);
    let h = this.rotationQuaternion;
    return h || (h = z._TmpRotation, X.RotationYawPitchRollToRef(this._rotation.y, this._rotation.x, this._rotation.z, h)), R.ComposeToRef(this.scaling, h, this.position, o), this.parent && o.multiplyToRef(this.parent.computeWorldMatrix(!0), o), e && (e.computeWorldMatrix(!0).invertToRef(a), o.multiplyToRef(a, o)), o.decompose(n, s, r, t ? this : void 0), this.rotationQuaternion ? this.rotationQuaternion.copyFrom(s) : s.toEulerAnglesToRef(this.rotation), this.scaling.copyFrom(n), this.position.copyFrom(r), this.parent = e, i && this.setPivotMatrix(R.Identity()), this;
  }
  /**
   * True if the scaling property of this object is non uniform eg. (1,2,1)
   */
  get nonUniformScaling() {
    return this._nonUniformScaling;
  }
  /**
   * @internal
   */
  _updateNonUniformScalingState(e) {
    return this._nonUniformScaling === e ? !1 : (this._nonUniformScaling = e, !0);
  }
  /**
   * 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(e, t) {
    return this._currentParentWhenAttachingToBone = this.parent, this._transformToBoneReferal = t, this.parent = e, e.getSkeleton().prepare(), e.getWorldMatrix().determinant() < 0 && (this.scalingDeterminant *= -1), 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(e = !1) {
    return this.parent ? (this.parent.getWorldMatrix().determinant() < 0 && (this.scalingDeterminant *= -1), this._transformToBoneReferal = null, e ? this.parent = this._currentParentWhenAttachingToBone : this.parent = null, this) : (e && (this.parent = this._currentParentWhenAttachingToBone), 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(e, t, i) {
    e.normalize(), this.rotationQuaternion || (this.rotationQuaternion = this.rotation.toQuaternion(), this.rotation.setAll(0));
    let s;
    if (!i || i === ot.LOCAL)
      s = X.RotationAxisToRef(e, t, z._RotationAxisCache), this.rotationQuaternion.multiplyToRef(s, this.rotationQuaternion);
    else {
      if (this.parent) {
        const r = C.Matrix[0];
        this.parent.getWorldMatrix().invertToRef(r), e = p.TransformNormal(e, r);
      }
      s = X.RotationAxisToRef(e, t, z._RotationAxisCache), s.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(e, t, i) {
    t.normalize(), this.rotationQuaternion || (this.rotationQuaternion = X.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z), this.rotation.setAll(0));
    const s = C.Vector3[0], r = C.Vector3[1], n = C.Vector3[2], a = C.Quaternion[0], o = C.Matrix[0], h = C.Matrix[1], c = C.Matrix[2], u = C.Matrix[3];
    return e.subtractToRef(this.position, s), R.TranslationToRef(s.x, s.y, s.z, o), R.TranslationToRef(-s.x, -s.y, -s.z, h), R.RotationAxisToRef(t, i, c), h.multiplyToRef(c, u), u.multiplyToRef(o, u), u.decompose(r, a, n), this.position.addInPlace(n), a.multiplyToRef(this.rotationQuaternion, this.rotationQuaternion), 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(e, t, i) {
    const s = e.scale(t);
    if (!i || i === ot.LOCAL) {
      const r = this.getPositionExpressedInLocalSpace().add(s);
      this.setPositionWithLocalVector(r);
    } else
      this.setAbsolutePosition(this.getAbsolutePosition().add(s));
    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(e, t, i) {
    let s;
    this.rotationQuaternion ? s = this.rotationQuaternion : (s = C.Quaternion[1], X.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, s));
    const r = C.Quaternion[0];
    return X.RotationYawPitchRollToRef(t, e, i, r), s.multiplyInPlace(r), this.rotationQuaternion || s.toEulerAnglesToRef(this.rotation), 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 !== z.BILLBOARDMODE_NONE && !this.preserveParentRotationForBillboard;
  }
  /**
   * 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(e = !1, t = null) {
    if (this._isWorldMatrixFrozen && !this._isDirty)
      return this._worldMatrix;
    const i = this.getScene().getRenderId();
    if (!this._isDirty && !e && (this._currentRenderId === i || this.isSynchronized()))
      return this._currentRenderId = i, this._worldMatrix;
    t = t || this.getScene().activeCamera, this._updateCache();
    const s = this._cache;
    s.pivotMatrixUpdated = !1, s.billboardMode = this.billboardMode, s.infiniteDistance = this.infiniteDistance, s.parent = this._parentNode, this._currentRenderId = i, this._childUpdateId += 1, this._isDirty = !1, this._position._isDirty = !1, this._rotation._isDirty = !1, this._scaling._isDirty = !1;
    const r = this._getEffectiveParent(), n = z._TmpScaling;
    let a = this._position;
    if (this._infiniteDistance && !this.parent && t) {
      const h = t.getWorldMatrix(), c = new p(h.m[12], h.m[13], h.m[14]);
      a = z._TmpTranslation, a.copyFromFloats(this._position.x + c.x, this._position.y + c.y, this._position.z + c.z);
    }
    n.copyFromFloats(this._scaling.x * this.scalingDeterminant, this._scaling.y * this.scalingDeterminant, this._scaling.z * this.scalingDeterminant);
    let o;
    if (this._rotationQuaternion ? (this._rotationQuaternion._isDirty = !1, o = this._rotationQuaternion, this.reIntegrateRotationIntoRotationQuaternion && this.rotation.lengthSquared() && (this._rotationQuaternion.multiplyInPlace(X.RotationYawPitchRoll(this._rotation.y, this._rotation.x, this._rotation.z)), this._rotation.copyFromFloats(0, 0, 0))) : (o = z._TmpRotation, X.RotationYawPitchRollToRef(this._rotation.y, this._rotation.x, this._rotation.z, o)), this._usePivotMatrix) {
      const h = C.Matrix[1];
      R.ScalingToRef(n.x, n.y, n.z, h);
      const c = C.Matrix[0];
      o.toRotationMatrix(c), this._pivotMatrix.multiplyToRef(h, C.Matrix[4]), C.Matrix[4].multiplyToRef(c, this._localMatrix), this._postMultiplyPivotMatrix && this._localMatrix.multiplyToRef(this._pivotMatrixInverse, this._localMatrix), this._localMatrix.addTranslationFromFloats(a.x, a.y, a.z);
    } else
      R.ComposeToRef(n, o, a, this._localMatrix);
    if (r && r.getWorldMatrix) {
      if (e && r.computeWorldMatrix(e), s.useBillboardPath) {
        this._transformToBoneReferal ? r.getWorldMatrix().multiplyToRef(this._transformToBoneReferal.getWorldMatrix(), C.Matrix[7]) : C.Matrix[7].copyFrom(r.getWorldMatrix());
        const h = C.Vector3[5], c = C.Vector3[6], u = C.Quaternion[0];
        C.Matrix[7].decompose(c, u, h), R.ScalingToRef(c.x, c.y, c.z, C.Matrix[7]), C.Matrix[7].setTranslation(h), z.BillboardUseParentOrientation && (this._position.applyRotationQuaternionToRef(u, h), this._localMatrix.setTranslation(h)), this._localMatrix.multiplyToRef(C.Matrix[7], this._worldMatrix);
      } else
        this._transformToBoneReferal ? (this._localMatrix.multiplyToRef(r.getWorldMatrix(), C.Matrix[6]), C.Matrix[6].multiplyToRef(this._transformToBoneReferal.getWorldMatrix(), this._worldMatrix)) : this._localMatrix.multiplyToRef(r.getWorldMatrix(), this._worldMatrix);
      this._markSyncedWithParent();
    } else
      this._worldMatrix.copyFrom(this._localMatrix);
    if (s.useBillboardPath && t && this.billboardMode && !s.useBillboardPosition) {
      const h = C.Vector3[0];
      if (this._worldMatrix.getTranslationToRef(h), C.Matrix[1].copyFrom(t.getViewMatrix()), C.Matrix[1].setTranslationFromFloats(0, 0, 0), C.Matrix[1].invertToRef(C.Matrix[0]), (this.billboardMode & z.BILLBOARDMODE_ALL) !== z.BILLBOARDMODE_ALL) {
        C.Matrix[0].decompose(void 0, C.Quaternion[0], void 0);
        const c = C.Vector3[1];
        C.Quaternion[0].toEulerAnglesToRef(c), (this.billboardMode & z.BILLBOARDMODE_X) !== z.BILLBOARDMODE_X && (c.x = 0), (this.billboardMode & z.BILLBOARDMODE_Y) !== z.BILLBOARDMODE_Y && (c.y = 0), (this.billboardMode & z.BILLBOARDMODE_Z) !== z.BILLBOARDMODE_Z && (c.z = 0), R.RotationYawPitchRollToRef(c.y, c.x, c.z, C.Matrix[0]);
      }
      this._worldMatrix.setTranslationFromFloats(0, 0, 0), this._worldMatrix.multiplyToRef(C.Matrix[0], this._worldMatrix), this._worldMatrix.setTranslation(C.Vector3[0]);
    } else if (s.useBillboardPath && t && s.useBillboardPosition) {
      const h = C.Vector3[0];
      this._worldMatrix.getTranslationToRef(h);
      const c = t.globalPosition;
      this._worldMatrix.invertToRef(C.Matrix[1]);
      const u = C.Vector3[1];
      p.TransformCoordinatesToRef(c, C.Matrix[1], u), u.normalize();
      const d = -Math.atan2(u.z, u.x) + Math.PI / 2, g = Math.sqrt(u.x * u.x + u.z * u.z), f = -Math.atan2(u.y, g);
      if (X.RotationYawPitchRollToRef(d, f, 0, C.Quaternion[0]), (this.billboardMode & z.BILLBOARDMODE_ALL) !== z.BILLBOARDMODE_ALL) {
        const m = C.Vector3[1];
        C.Quaternion[0].toEulerAnglesToRef(m), (this.billboardMode & z.BILLBOARDMODE_X) !== z.BILLBOARDMODE_X && (m.x = 0), (this.billboardMode & z.BILLBOARDMODE_Y) !== z.BILLBOARDMODE_Y && (m.y = 0), (this.billboardMode & z.BILLBOARDMODE_Z) !== z.BILLBOARDMODE_Z && (m.z = 0), R.RotationYawPitchRollToRef(m.y, m.x, m.z, C.Matrix[0]);
      } else
        R.FromQuaternionToRef(C.Quaternion[0], C.Matrix[0]);
      this._worldMatrix.setTranslationFromFloats(0, 0, 0), this._worldMatrix.multiplyToRef(C.Matrix[0], this._worldMatrix), this._worldMatrix.setTranslation(C.Vector3[0]);
    }
    return this.ignoreNonUniformScaling ? this._updateNonUniformScalingState(!1) : this._scaling.isNonUniformWithinEpsilon(1e-6) ? this._updateNonUniformScalingState(!0) : r && r._nonUniformScaling ? this._updateNonUniformScalingState(r._nonUniformScaling) : this._updateNonUniformScalingState(!1), this._afterComputeWorldMatrix(), this._absolutePosition.copyFromFloats(this._worldMatrix.m[12], this._worldMatrix.m[13], this._worldMatrix.m[14]), this._isAbsoluteSynced = !1, this.onAfterWorldMatrixUpdateObservable.notifyObservers(this), this._poseMatrix || (this._poseMatrix = R.Invert(this._worldMatrix)), this._worldMatrixDeterminantIsDirty = !0, 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(e = !0) {
    if (this.computeWorldMatrix(), e) {
      const t = this.getChildren();
      for (let i = 0; i < t.length; ++i) {
        const s = t[i];
        if (s) {
          s.computeWorldMatrix();
          const r = C.Matrix[0];
          s._localMatrix.multiplyToRef(this._localMatrix, r);
          const n = C.Quaternion[0];
          r.decompose(s.scaling, n, s.position), s.rotationQuaternion ? s.rotationQuaternion.copyFrom(n) : n.toEulerAnglesToRef(s.rotation);
        }
      }
    }
    this.scaling.copyFromFloats(1, 1, 1), this.position.copyFromFloats(0, 0, 0), this.rotation.copyFromFloats(0, 0, 0), this.rotationQuaternion && (this.rotationQuaternion = X.Identity()), this._worldMatrix = R.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(e) {
    return this.onAfterWorldMatrixUpdateObservable.add(e), this;
  }
  /**
   * Removes a registered callback function.
   * @param func callback function to remove
   * @returns the TransformNode.
   */
  unregisterAfterWorldMatrixUpdate(e) {
    return this.onAfterWorldMatrixUpdateObservable.removeCallback(e), this;
  }
  /**
   * Gets the position of the current mesh in camera space
   * @param camera defines the camera to use
   * @returns a position
   */
  getPositionInCameraSpace(e = null) {
    return e || (e = this.getScene().activeCamera), p.TransformCoordinates(this.getAbsolutePosition(), e.getViewMatrix());
  }
  /**
   * Returns the distance from the mesh to the active camera
   * @param camera defines the camera to use
   * @returns the distance
   */
  getDistanceToCamera(e = null) {
    return e || (e = this.getScene().activeCamera), this.getAbsolutePosition().subtract(e.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(e, t, i) {
    const s = he.Clone(() => new z(e, this.getScene()), this);
    if (s.name = e, s.id = e, t && (s.parent = t), !i) {
      const r = this.getDescendants(!0);
      for (let n = 0; n < r.length; n++) {
        const a = r[n];
        a.clone && a.clone(e + "." + a.name, s);
      }
    }
    return s;
  }
  /**
   * Serializes the objects information.
   * @param currentSerializationObject defines the object to serialize in
   * @returns the serialized object
   */
  serialize(e) {
    const t = he.Serialize(this, e);
    return t.type = this.getClassName(), t.uniqueId = this.uniqueId, this.parent && this.parent._serializeAsParent(t), t.localMatrix = this.getPivotMatrix().asArray(), t.isEnabled = this.isEnabled(), t;
  }
  // 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(e, t, i) {
    const s = he.Parse(() => new z(e.name, t), e, t, i);
    return e.localMatrix ? s.setPreTransformMatrix(R.FromArray(e.localMatrix)) : e.pivotMatrix && s.setPivotMatrix(R.FromArray(e.pivotMatrix)), s.setEnabled(e.isEnabled), s._waitingParsedUniqueId = e.uniqueId, e.parentId !== void 0 && (s._waitingParentId = e.parentId), e.parentInstanceIndex !== void 0 && (s._waitingParentInstanceIndex = e.parentInstanceIndex), s;
  }
  /**
   * 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(e, t) {
    const i = [];
    return this._getDescendants(i, e, (s) => (!t || t(s)) && s instanceof z), i;
  }
  /**
   * 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(e, t = !1) {
    if (this.getScene().stopAnimation(this), this.getScene().removeTransformNode(this), this._parentContainer) {
      const i = this._parentContainer.transformNodes.indexOf(this);
      i > -1 && this._parentContainer.transformNodes.splice(i, 1), this._parentContainer = null;
    }
    if (this.onAfterWorldMatrixUpdateObservable.clear(), e) {
      const i = this.getChildTransformNodes(!0);
      for (const s of i)
        s.parent = null, s.computeWorldMatrix(!0);
    }
    super.dispose(e, t);
  }
  /**
   * 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(e = !0, t = !1, i) {
    let s = null, r = null;
    t && (this.rotationQuaternion ? (r = this.rotationQuaternion.clone(), this.rotationQuaternion.copyFromFloats(0, 0, 0, 1)) : this.rotation && (s = this.rotation.clone(), this.rotation.copyFromFloats(0, 0, 0)));
    const n = this.getHierarchyBoundingVectors(e, i), a = n.max.subtract(n.min), o = Math.max(a.x, a.y, a.z);
    if (o === 0)
      return this;
    const h = 1 / o;
    return this.scaling.scaleInPlace(h), t && (this.rotationQuaternion && r ? this.rotationQuaternion.copyFrom(r) : this.rotation && s && this.rotation.copyFrom(s)), this;
  }
  _syncAbsoluteScalingAndRotation() {
    this._isAbsoluteSynced || (this._worldMatrix.decompose(this._absoluteScaling, this._absoluteRotationQuaternion), this._isAbsoluteSynced = !0);
  }
}
z.BILLBOARDMODE_NONE = 0;
z.BILLBOARDMODE_X = 1;
z.BILLBOARDMODE_Y = 2;
z.BILLBOARDMODE_Z = 4;
z.BILLBOARDMODE_ALL = 7;
z.BILLBOARDMODE_USE_POSITION = 128;
z.BillboardUseParentOrientation = !1;
z._TmpRotation = X.Zero();
z._TmpScaling = p.Zero();
z._TmpTranslation = p.Zero();
z._LookAtVectorCache = new p(0, 0, 0);
z._RotationAxisCache = new X();
F([
  Ht("position")
], z.prototype, "_position", void 0);
F([
  Ht("rotation")
], z.prototype, "_rotation", void 0);
F([
  rr("rotationQuaternion")
], z.prototype, "_rotationQuaternion", void 0);
F([
  Ht("scaling")
], z.prototype, "_scaling", void 0);
F([
  B("billboardMode")
], z.prototype, "_billboardMode", void 0);
F([
  B()
], z.prototype, "scalingDeterminant", void 0);
F([
  B("infiniteDistance")
], z.prototype, "_infiniteDistance", void 0);
F([
  B()
], z.prototype, "ignoreNonUniformScaling", void 0);
F([
  B()
], z.prototype, "reIntegrateRotationIntoRotationQuaternion", void 0);
class yr {
  constructor() {
    this._checkCollisions = !1, this._collisionMask = -1, this._collisionGroup = -1, this._surroundingMeshes = null, this._collider = null, this._oldPositionForCollisions = new p(0, 0, 0), this._diffPositionForCollisions = new p(0, 0, 0), this._collisionResponse = !0;
  }
}
class Tr {
  constructor() {
    this.facetNb = 0, this.partitioningSubdivisions = 10, this.partitioningBBoxRatio = 1.01, this.facetDataEnabled = !1, this.facetParameters = {}, this.bbSize = p.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 = !1, this.facetDepthSortEnabled = !1;
  }
}
class Mr {
  constructor() {
    this._hasVertexAlpha = !1, this._useVertexColors = !0, this._numBoneInfluencers = 4, this._applyFog = !0, this._receiveShadows = !1, this._facetData = new Tr(), this._visibility = 1, this._skeleton = null, this._layerMask = 268435455, this._computeBonesUsingShaders = !0, this._isActive = !1, this._onlyForInstances = !1, this._isActiveIntermediate = !1, this._onlyForInstancesIntermediate = !1, this._actAsRegularMesh = !1, this._currentLOD = null, this._currentLODIsUpToDate = !1, this._collisionRetryCount = 3, this._morphTargetManager = null, this._renderingGroupId = 0, this._bakedVertexAnimationManager = null, this._material = null, this._positions = null, this._pointerOverDisableMeshTesting = !1, this._meshCollisionData = new yr(), this._enableDistantPicking = !1, this._rawBoundingInfo = null;
  }
}
class Ge extends z {
  /**
   * No billboard
   */
  static get BILLBOARDMODE_NONE() {
    return z.BILLBOARDMODE_NONE;
  }
  /** Billboard on X axis */
  static get BILLBOARDMODE_X() {
    return z.BILLBOARDMODE_X;
  }
  /** Billboard on Y axis */
  static get BILLBOARDMODE_Y() {
    return z.BILLBOARDMODE_Y;
  }
  /** Billboard on Z axis */
  static get BILLBOARDMODE_Z() {
    return z.BILLBOARDMODE_Z;
  }
  /** Billboard on all axes */
  static get BILLBOARDMODE_ALL() {
    return z.BILLBOARDMODE_ALL;
  }
  /** Billboard on using position instead of orientation */
  static get BILLBOARDMODE_USE_POSITION() {
    return z.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(e) {
    this._internalAbstractMeshDataInfo._facetData.partitioningSubdivisions = e;
  }
  /**
   * 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
   */
  get partitioningBBoxRatio() {
    return this._internalAbstractMeshDataInfo._facetData.partitioningBBoxRatio;
  }
  set partitioningBBoxRatio(e) {
    this._internalAbstractMeshDataInfo._facetData.partitioningBBoxRatio = e;
  }
  /**
   * 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(e) {
    this._internalAbstractMeshDataInfo._facetData.facetDepthSort = e;
  }
  /**
   * 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(e) {
    this._internalAbstractMeshDataInfo._facetData.facetDepthSortFrom = e;
  }
  /** 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(e) {
    this._internalAbstractMeshDataInfo._collisionRetryCount = e;
  }
  /**
   * 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(e) {
    this._internalAbstractMeshDataInfo._morphTargetManager !== e && (this._internalAbstractMeshDataInfo._morphTargetManager = e, 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(e) {
    this._internalAbstractMeshDataInfo._bakedVertexAnimationManager !== e && (this._internalAbstractMeshDataInfo._bakedVertexAnimationManager = e, this._markSubMeshesAsAttributesDirty());
  }
  /** @internal */
  _syncGeometryWithMorphTargetManager() {
  }
  /**
   * @internal
   */
  _updateNonUniformScalingState(e) {
    return super._updateNonUniformScalingState(e) ? (this._markSubMeshesAsMiscDirty(), !0) : !1;
  }
  /** @internal */
  get rawBoundingInfo() {
    return this._internalAbstractMeshDataInfo._rawBoundingInfo;
  }
  set rawBoundingInfo(e) {
    this._internalAbstractMeshDataInfo._rawBoundingInfo = e;
  }
  /** Set a function to call when this mesh collides with another one */
  set onCollide(e) {
    this._internalAbstractMeshDataInfo._meshCollisionData._onCollideObserver && this.onCollideObservable.remove(this._internalAbstractMeshDataInfo._meshCollisionData._onCollideObserver), this._internalAbstractMeshDataInfo._meshCollisionData._onCollideObserver = this.onCollideObservable.add(e);
  }
  /** Set a function to call when the collision's position changes */
  set onCollisionPositionChange(e) {
    this._internalAbstractMeshDataInfo._meshCollisionData._onCollisionPositionChangeObserver && this.onCollisionPositionChangeObservable.remove(this._internalAbstractMeshDataInfo._meshCollisionData._onCollisionPositionChangeObserver), this._internalAbstractMeshDataInfo._meshCollisionData._onCollisionPositionChangeObserver = this.onCollisionPositionChangeObservable.add(e);
  }
  /**
   * 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(e) {
    if (this._internalAbstractMeshDataInfo._visibility === e)
      return;
    const t = this._internalAbstractMeshDataInfo._visibility;
    this._internalAbstractMeshDataInfo._visibility = e, (t === 1 && e !== 1 || t !== 1 && e === 1) && this._markSubMeshesAsMiscDirty();
  }
  /**
   * 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(e) {
    this._internalAbstractMeshDataInfo._pointerOverDisableMeshTesting = e;
  }
  /**
   * 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(e) {
    this._internalAbstractMeshDataInfo._renderingGroupId = e;
  }
  /** Gets or sets current material */
  get material() {
    return this._internalAbstractMeshDataInfo._material;
  }
  set material(e) {
    this._internalAbstractMeshDataInfo._material !== e && (this._internalAbstractMeshDataInfo._material && this._internalAbstractMeshDataInfo._material.meshMap && (this._internalAbstractMeshDataInfo._material.meshMap[this.uniqueId] = void 0), this._internalAbstractMeshDataInfo._material = e, e && e.meshMap && (e.meshMap[this.uniqueId] = this), this.onMaterialChangedObservable.hasObservers() && this.onMaterialChangedObservable.notifyObservers(this), this.subMeshes && (this.resetDrawCache(), 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(e) {
    var t;
    return (t = this._internalAbstractMeshDataInfo._materialForRenderPass) === null || t === void 0 ? void 0 : t[e];
  }
  /**
   * 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(e, t) {
    this.resetDrawCache(e), this._internalAbstractMeshDataInfo._materialForRenderPass || (this._internalAbstractMeshDataInfo._materialForRenderPass = []), this._internalAbstractMeshDataInfo._materialForRenderPass[e] = t;
  }
  /**
   * 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(e) {
    this._internalAbstractMeshDataInfo._receiveShadows !== e && (this._internalAbstractMeshDataInfo._receiveShadows = e, this._markSubMeshesAsLightDirty());
  }
  /** Gets or sets a boolean indicating that this mesh contains vertex color data with alpha values */
  get hasVertexAlpha() {
    return this._internalAbstractMeshDataInfo._hasVertexAlpha;
  }
  set hasVertexAlpha(e) {
    this._internalAbstractMeshDataInfo._hasVertexAlpha !== e && (this._internalAbstractMeshDataInfo._hasVertexAlpha = e, 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(e) {
    this._internalAbstractMeshDataInfo._useVertexColors !== e && (this._internalAbstractMeshDataInfo._useVertexColors = e, this._markSubMeshesAsAttributesDirty());
  }
  /**
   * Gets or sets a boolean indicating that bone animations must be computed by the CPU (false by default)
   */
  get computeBonesUsingShaders() {
    return this._internalAbstractMeshDataInfo._computeBonesUsingShaders;
  }
  set computeBonesUsingShaders(e) {
    this._internalAbstractMeshDataInfo._computeBonesUsingShaders !== e && (this._internalAbstractMeshDataInfo._computeBonesUsingShaders = e, this._markSubMeshesAsAttributesDirty());
  }
  /** Gets or sets the number of allowed bone influences per vertex (4 by default) */
  get numBoneInfluencers() {
    return this._internalAbstractMeshDataInfo._numBoneInfluencers;
  }
  set numBoneInfluencers(e) {
    this._internalAbstractMeshDataInfo._numBoneInfluencers !== e && (this._internalAbstractMeshDataInfo._numBoneInfluencers = e, 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(e) {
    this._internalAbstractMeshDataInfo._applyFog !== e && (this._internalAbstractMeshDataInfo._applyFog = e, 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(e) {
    this._internalAbstractMeshDataInfo._enableDistantPicking = e;
  }
  /**
   * 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(e) {
    e !== this._internalAbstractMeshDataInfo._layerMask && (this._internalAbstractMeshDataInfo._layerMask = e, 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(e) {
    this._internalAbstractMeshDataInfo._meshCollisionData._collisionMask = isNaN(e) ? -1 : e;
  }
  /**
   * 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(e) {
    this._internalAbstractMeshDataInfo._meshCollisionData._collisionResponse = e;
  }
  /**
   * 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(e) {
    this._internalAbstractMeshDataInfo._meshCollisionData._collisionGroup = isNaN(e) ? -1 : e;
  }
  /**
   * 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(e) {
    this._internalAbstractMeshDataInfo._meshCollisionData._surroundingMeshes = e;
  }
  /** Gets the list of lights affecting that mesh */
  get lightSources() {
    return this._lightSources;
  }
  /** @internal */
  get _positions() {
    return null;
  }
  /**
   * Gets or sets a skeleton to apply skinning transformations
   * @see https://doc.babylonjs.com/features/featuresDeepDive/mesh/bonesSkeletons
   */
  set skeleton(e) {
    const t = this._internalAbstractMeshDataInfo._skeleton;
    t && t.needInitialSkinMatrix && t._unregisterMeshWithPoseMatrix(this), e && e.needInitialSkinMatrix && e._registerMeshWithPoseMatrix(this), this._internalAbstractMeshDataInfo._skeleton = e, 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(e, t = null) {
    switch (super(e, t, !1), this._internalAbstractMeshDataInfo = new Mr(), this._waitingMaterialId = null, this.cullingStrategy = Ge.CULLINGSTRATEGY_BOUNDINGSPHERE_ONLY, this.onCollideObservable = new w(), this.onCollisionPositionChangeObservable = new w(), this.onMaterialChangedObservable = new w(), this.definedFacingForward = !0, this._occlusionQuery = null, this._renderingGroup = null, this.alphaIndex = Number.MAX_VALUE, this.isVisible = !0, this.isPickable = !0, this.isNearPickable = !1, this.isNearGrabbable = !1, this.showSubMeshesBoundingBox = !1, this.isBlocker = !1, this.enablePointerMoveEvents = !1, this.outlineColor = te.Red(), this.outlineWidth = 0.02, this.overlayColor = te.Red(), this.overlayAlpha = 0.5, this.useOctreeForRenderingSelection = !0, this.useOctreeForPicking = !0, this.useOctreeForCollisions = !0, this.alwaysSelectAsActiveMesh = !1, this.doNotSyncBoundingInfo = !1, this.actionManager = null, this.ellipsoid = new p(0.5, 1, 0.5), this.ellipsoidOffset = new p(0, 0, 0), this.edgesWidth = 1, this.edgesColor = new Oe(1, 0, 0, 1), this._edgesRenderer = null, this._masterMesh = null, this._boundingInfo = null, this._boundingInfoIsDirty = !0, this._renderId = 0, this._intersectionsInProgress = new Array(), this._unIndexed = !1, this._lightSources = new Array(), this._waitingData = {
      lods: null,
      actions: null,
      freezeWorldMatrix: null
    }, this._bonesTransformMatrices = null, this._transformMatrixTexture = null, this.onRebuildObservable = new w(), this._onCollisionPositionChange = (i, s, r = null) => {
      s.subtractToRef(this._internalAbstractMeshDataInfo._meshCollisionData._oldPositionForCollisions, this._internalAbstractMeshDataInfo._meshCollisionData._diffPositionForCollisions), this._internalAbstractMeshDataInfo._meshCollisionData._diffPositionForCollisions.length() > P.CollisionsEpsilon && this.position.addInPlace(this._internalAbstractMeshDataInfo._meshCollisionData._diffPositionForCollisions), r && this.onCollideObservable.notifyObservers(r), this.onCollisionPositionChangeObservable.notifyObservers(this.position);
    }, t = this.getScene(), t.addMesh(this), this._resyncLightSources(), this._uniformBuffer = new O(this.getScene().getEngine(), void 0, void 0, e, !this.getScene().getEngine().isWebGPU), this._buildUniformLayout(), t.performancePriority) {
      case et.Aggressive:
        this.doNotSyncBoundingInfo = !0;
      case et.Intermediate:
        this.alwaysSelectAsActiveMesh = !0, this.isPickable = !1;
        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(e) {
    const t = this._uniformBuffer;
    t.updateMatrix("world", e), t.updateFloat("visibility", this._internalAbstractMeshDataInfo._visibility), t.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(e) {
    let t = "Name: " + this.name + ", isInstance: " + (this.getClassName() !== "InstancedMesh" ? "YES" : "NO");
    t += ", # of submeshes: " + (this.subMeshes ? this.subMeshes.length : 0);
    const i = this._internalAbstractMeshDataInfo._skeleton;
    return i && (t += ", skeleton: " + i.name), e && (t += ", billboard mode: " + ["NONE", "X", "Y", null, "Z", null, null, "ALL"][this.billboardMode], t += ", freeze wrld mat: " + (this._isWorldMatrixFrozen || this._waitingData.freezeWorldMatrix ? "YES" : "NO")), t;
  }
  /**
   * @internal
   */
  _getEffectiveParent() {
    return this._masterMesh && this.billboardMode !== z.BILLBOARDMODE_NONE ? this._masterMesh : super._getEffectiveParent();
  }
  /**
   * @internal
   */
  _getActionManagerForTrigger(e, t = !0) {
    if (this.actionManager && (t || this.actionManager.isRecursive))
      if (e) {
        if (this.actionManager.hasSpecificTrigger(e))
          return this.actionManager;
      } else
        return this.actionManager;
    return this.parent ? this.parent._getActionManagerForTrigger(e, !1) : null;
  }
  /**
   * @internal
   */
  // eslint-disable-next-line @typescript-eslint/no-unused-vars
  _rebuild(e = !1) {
    if (this.onRebuildObservable.notifyObservers(this), this._occlusionQuery !== null && (this._occlusionQuery = null), !!this.subMeshes)
      for (const t of this.subMeshes)
        t._rebuild();
  }
  /** @internal */
  _resyncLightSources() {
    this._lightSources.length = 0;
    for (const e of this.getScene().lights)
      e.isEnabled() && e.canAffectMesh(this) && this._lightSources.push(e);
    this._markSubMeshesAsLightDirty();
  }
  /**
   * @internal
   */
  _resyncLightSource(e) {
    const t = e.isEnabled() && e.canAffectMesh(this), i = this._lightSources.indexOf(e);
    let s = !1;
    if (i === -1) {
      if (!t)
        return;
      this._lightSources.push(e);
    } else {
      if (t)
        return;
      s = !0, this._lightSources.splice(i, 1);
    }
    this._markSubMeshesAsLightDirty(s);
  }
  /** @internal */
  _unBindEffect() {
    for (const e of this.subMeshes)
      e.setEffect(null);
  }
  /**
   * @internal
   */
  _removeLightSource(e, t) {
    const i = this._lightSources.indexOf(e);
    i !== -1 && (this._lightSources.splice(i, 1), this._markSubMeshesAsLightDirty(t));
  }
  _markSubMeshesAsDirty(e) {
    if (this.subMeshes)
      for (const t of this.subMeshes)
        for (let i = 0; i < t._drawWrappers.length; ++i) {
          const s = t._drawWrappers[i];
          !s || !s.defines || !s.defines.markAllAsDirty || e(s.defines);
        }
  }
  /**
   * @internal
   */
  _markSubMeshesAsLightDirty(e = !1) {
    this._markSubMeshesAsDirty((t) => t.markAsLightDirty(e));
  }
  /** @internal */
  _markSubMeshesAsAttributesDirty() {
    this._markSubMeshesAsDirty((e) => e.markAsAttributesDirty());
  }
  /** @internal */
  _markSubMeshesAsMiscDirty() {
    this._markSubMeshesAsDirty((e) => e.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(e) {
    return this._currentRenderId = Number.MAX_VALUE, this._isDirty = !0, 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
   */
  resetDrawCache(e) {
    if (this.subMeshes)
      for (const t of this.subMeshes)
        t.resetDrawCache(e);
  }
  // Methods
  /**
   * Returns true if the mesh is blocked. Implemented by child classes
   */
  get isBlocked() {
    return !1;
  }
  /**
   * 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(e) {
    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(e) {
    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(e, t, i, s) {
    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(e, t, i, s) {
    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(e, t) {
    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(e) {
    return !1;
  }
  /**
   * 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() {
    return this._masterMesh ? this._masterMesh.getBoundingInfo() : (this._boundingInfoIsDirty && (this._boundingInfoIsDirty = !1, this._updateBoundingInfo()), this._boundingInfo);
  }
  /**
   * Returns the bounding info unnafected by instance data.
   * @returns the bounding info of the mesh unaffected by instance data.
   */
  getRawBoundingInfo() {
    var e;
    return (e = this.rawBoundingInfo) !== null && e !== void 0 ? e : this.getBoundingInfo();
  }
  /**
   * Overwrite the current bounding info
   * @param boundingInfo defines the new bounding info
   * @returns the current mesh
   */
  setBoundingInfo(e) {
    return this._boundingInfo = e, 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(e, t, i) {
    return this._boundingInfo = new qe(e, t, i), 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(e = !0, t = !1, i) {
    return super.normalizeToUnitCube(e, t, i);
  }
  /** Gets a boolean indicating if this mesh has skinning data and an attached skeleton */
  get useBones() {
    return this.skeleton && this.getScene().skeletonsEnabled && this.isVerticesDataPresent(_.MatricesIndicesKind) && this.isVerticesDataPresent(_.MatricesWeightsKind);
  }
  /** @internal */
  _preActivate() {
  }
  /**
   * @internal
   */
  // eslint-disable-next-line @typescript-eslint/no-unused-vars
  _preActivateForIntermediateRendering(e) {
  }
  /**
   * @internal
   */
  // eslint-disable-next-line @typescript-eslint/no-unused-vars
  _activate(e, t) {
    return this._renderId = e, !0;
  }
  /** @internal */
  _postActivate() {
  }
  /** @internal */
  _freeze() {
  }
  /** @internal */
  _unFreeze() {
  }
  /**
   * Gets the current world matrix
   * @returns a Matrix
   */
  getWorldMatrix() {
    return this._masterMesh && this.billboardMode === z.BILLBOARDMODE_NONE ? this._masterMesh.getWorldMatrix() : super.getWorldMatrix();
  }
  /** @internal */
  _getWorldMatrixDeterminant() {
    return this._masterMesh ? this._masterMesh._getWorldMatrixDeterminant() : super._getWorldMatrixDeterminant();
  }
  /**
   * Gets a boolean indicating if this mesh is an instance or a regular mesh
   */
  get isAnInstance() {
    return !1;
  }
  /**
   * Gets a boolean indicating if this mesh has instances
   */
  get hasInstances() {
    return !1;
  }
  /**
   * Gets a boolean indicating if this mesh has thin instances
   */
  get hasThinInstances() {
    return !1;
  }
  // ================================== 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(e, t, i) {
    return this.position.addInPlace(this.calcMovePOV(e, t, i)), 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(e, t, i) {
    const s = new R();
    (this.rotationQuaternion ? this.rotationQuaternion : X.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z)).toRotationMatrix(s);
    const n = p.Zero(), a = this.definedFacingForward ? -1 : 1;
    return p.TransformCoordinatesFromFloatsToRef(e * a, t, i * a, s, n), n;
  }
  // ================================== 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(e, t, i) {
    return this.rotation.addInPlace(this.calcRotatePOV(e, t, i)), 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(e, t, i) {
    const s = this.definedFacingForward ? 1 : -1;
    return new p(e * s, t, i * s);
  }
  /**
   * 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 applySkeleton defines whether to apply the skeleton before computing the bounding info
   * @param applyMorph  defines whether to apply the morph target before computing the bounding info
   * @returns the current mesh
   */
  refreshBoundingInfo(e = !1, t = !1) {
    return this._boundingInfo && this._boundingInfo.isLocked ? this : (this._refreshBoundingInfo(this._getPositionData(e, t), null), this);
  }
  /**
   * @internal
   */
  _refreshBoundingInfo(e, t) {
    if (e) {
      const i = gs(e, 0, this.getTotalVertices(), t);
      this._boundingInfo ? this._boundingInfo.reConstruct(i.minimum, i.maximum) : this._boundingInfo = new qe(i.minimum, i.maximum);
    }
    if (this.subMeshes)
      for (let i = 0; i < this.subMeshes.length; i++)
        this.subMeshes[i].refreshBoundingInfo(e);
    this._updateBoundingInfo();
  }
  /**
   * Internal function to get buffer data and possibly apply morphs and normals
   * @param applySkeleton
   * @param applyMorph
   * @param data
   * @param kind the kind of data you want. Can be Normal or Position
   */
  _getData(e = !1, t = !1, i, s = _.PositionKind) {
    if (i = i ?? this.getVerticesData(s).slice(), i && t && this.morphTargetManager) {
      let r = 0, n = 0;
      for (let a = 0; a < i.length; a++) {
        for (let o = 0; o < this.morphTargetManager.numTargets; o++) {
          const h = this.morphTargetManager.getTarget(o), c = h.influence;
          if (c > 0) {
            const u = h.getPositions();
            u && (i[a] += (u[a] - i[a]) * c);
          }
        }
        if (r++, s === _.PositionKind && this._positions && r === 3) {
          r = 0;
          const o = n * 3;
          this._positions[n++].copyFromFloats(i[o], i[o + 1], i[o + 2]);
        }
      }
    }
    if (i && e && this.skeleton) {
      const r = this.getVerticesData(_.MatricesIndicesKind), n = this.getVerticesData(_.MatricesWeightsKind);
      if (n && r) {
        const a = this.numBoneInfluencers > 4, o = a ? this.getVerticesData(_.MatricesIndicesExtraKind) : null, h = a ? this.getVerticesData(_.MatricesWeightsExtraKind) : null, c = this.skeleton.getTransformMatrices(this), u = C.Vector3[0], d = C.Matrix[0], g = C.Matrix[1];
        let f = 0;
        for (let m = 0; m < i.length; m += 3, f += 4) {
          d.reset();
          let b, T;
          for (b = 0; b < 4; b++)
            T = n[f + b], T > 0 && (R.FromFloat32ArrayToRefScaled(c, Math.floor(r[f + b] * 16), T, g), d.addToSelf(g));
          if (a)
            for (b = 0; b < 4; b++)
              T = h[f + b], T > 0 && (R.FromFloat32ArrayToRefScaled(c, Math.floor(o[f + b] * 16), T, g), d.addToSelf(g));
          s === _.NormalKind ? p.TransformNormalFromFloatsToRef(i[m], i[m + 1], i[m + 2], d, u) : p.TransformCoordinatesFromFloatsToRef(i[m], i[m + 1], i[m + 2], d, u), u.toArray(i, m), s === _.PositionKind && this._positions && this._positions[m / 3].copyFrom(u);
        }
      }
    }
    return i;
  }
  /**
   * 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(e = !1, t = !1) {
    return this._getData(e, t, null, _.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(e = !1, t = !1, i) {
    return this._getData(e, t, i, _.PositionKind);
  }
  /**
   * @internal
   */
  _getPositionData(e, t) {
    var i;
    let s = this.getVerticesData(_.PositionKind);
    if (this._internalAbstractMeshDataInfo._positions && (this._internalAbstractMeshDataInfo._positions = null), s && (e && this.skeleton || t && this.morphTargetManager)) {
      if (s = s.slice(), this._generatePointsArray(), this._positions) {
        const r = this._positions;
        this._internalAbstractMeshDataInfo._positions = new Array(r.length);
        for (let n = 0; n < r.length; n++)
          this._internalAbstractMeshDataInfo._positions[n] = ((i = r[n]) === null || i === void 0 ? void 0 : i.clone()) || new p();
      }
      return this.getPositionData(e, t, s);
    }
    return s;
  }
  /** @internal */
  _updateBoundingInfo() {
    return this._boundingInfo ? this._boundingInfo.update(this.worldMatrixFromCache) : this._boundingInfo = new qe(p.Zero(), p.Zero(), this.worldMatrixFromCache), this._updateSubMeshesBoundingInfo(this.worldMatrixFromCache), this;
  }
  /**
   * @internal
   */
  _updateSubMeshesBoundingInfo(e) {
    if (!this.subMeshes)
      return this;
    const t = this.subMeshes.length;
    for (let i = 0; i < t; i++) {
      const s = this.subMeshes[i];
      (t > 1 || !s.IsGlobal) && s.updateBoundingInfo(e);
    }
    return this;
  }
  /** @internal */
  _afterComputeWorldMatrix() {
    this.doNotSyncBoundingInfo || (this._boundingInfoIsDirty = !0);
  }
  /**
   * 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(e) {
    return this.getBoundingInfo().isInFrustum(e, 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(e) {
    return this.getBoundingInfo().isCompletelyInFrustum(e);
  }
  /**
   * 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(e, t = !1, i) {
    const s = this.getBoundingInfo(), r = e.getBoundingInfo();
    if (s.intersects(r, t))
      return !0;
    if (i) {
      for (const n of this.getChildMeshes())
        if (n.intersectsMesh(e, t, !0))
          return !0;
    }
    return !1;
  }
  /**
   * 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(e) {
    return this.getBoundingInfo().intersectsPoint(e);
  }
  // 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(e) {
    this._internalAbstractMeshDataInfo._meshCollisionData._checkCollisions = e;
  }
  /**
   * 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
   * @returns the current mesh
   */
  moveWithCollisions(e) {
    this.getAbsolutePosition().addToRef(this.ellipsoidOffset, this._internalAbstractMeshDataInfo._meshCollisionData._oldPositionForCollisions);
    const i = this.getScene().collisionCoordinator;
    return this._internalAbstractMeshDataInfo._meshCollisionData._collider || (this._internalAbstractMeshDataInfo._meshCollisionData._collider = i.createCollider()), this._internalAbstractMeshDataInfo._meshCollisionData._collider._radius = this.ellipsoid, i.getNewPosition(this._internalAbstractMeshDataInfo._meshCollisionData._oldPositionForCollisions, e, this._internalAbstractMeshDataInfo._meshCollisionData._collider, this.collisionRetryCount, this, this._onCollisionPositionChange, this.uniqueId), this;
  }
  // Collisions
  /**
   * @internal
   */
  _collideForSubMesh(e, t, i) {
    var s;
    if (this._generatePointsArray(), !this._positions)
      return this;
    if (!e._lastColliderWorldVertices || !e._lastColliderTransformMatrix.equals(t)) {
      e._lastColliderTransformMatrix = t.clone(), e._lastColliderWorldVertices = [], e._trianglePlanes = [];
      const r = e.verticesStart, n = e.verticesStart + e.verticesCount;
      for (let a = r; a < n; a++)
        e._lastColliderWorldVertices.push(p.TransformCoordinates(this._positions[a], t));
    }
    return i._collide(e._trianglePlanes, e._lastColliderWorldVertices, this.getIndices(), e.indexStart, e.indexStart + e.indexCount, e.verticesStart, !!e.getMaterial(), this, this._shouldConvertRHS(), ((s = e.getMaterial()) === null || s === void 0 ? void 0 : s.fillMode) === 7), this;
  }
  /**
   * @internal
   */
  _processCollisionsForSubMeshes(e, t) {
    const i = this._scene.getCollidingSubMeshCandidates(this, e), s = i.length;
    for (let r = 0; r < s; r++) {
      const n = i.data[r];
      s > 1 && !n._checkCollision(e) || this._collideForSubMesh(n, t, e);
    }
    return this;
  }
  /** @internal */
  _shouldConvertRHS() {
    return !1;
  }
  /**
   * @internal
   */
  _checkCollision(e) {
    if (!this.getBoundingInfo()._checkCollision(e))
      return this;
    const t = C.Matrix[0], i = C.Matrix[1];
    return R.ScalingToRef(1 / e._radius.x, 1 / e._radius.y, 1 / e._radius.z, t), this.worldMatrixFromCache.multiplyToRef(t, i), this._processCollisionsForSubMeshes(e, i), this;
  }
  // Picking
  /** @internal */
  _generatePointsArray() {
    return !1;
  }
  /**
   * Checks if the passed Ray intersects with the mesh
   * @param ray defines the ray to use
   * @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(e, t, i, s = !1, r, n = !1) {
    const a = new ut(), o = this.getClassName() === "InstancedLinesMesh" || this.getClassName() === "LinesMesh" ? this.intersectionThreshold : 0, h = this.getBoundingInfo();
    if (!this.subMeshes || !n && (!e.intersectsSphere(h.boundingSphere, o) || !e.intersectsBox(h.boundingBox, o)))
      return a;
    if (s)
      return a.hit = !n, a.pickedMesh = n ? null : this, a.distance = n ? 0 : p.Distance(e.origin, h.boundingSphere.center), a.subMeshId = 0, a;
    if (!this._generatePointsArray())
      return a;
    let c = null;
    const u = this._scene.getIntersectingSubMeshCandidates(this, e), d = u.length;
    let g = !1;
    for (let f = 0; f < d; f++) {
      const b = u.data[f].getMaterial();
      if (b && (b.fillMode == 7 || b.fillMode == 0 || b.fillMode == 1 || b.fillMode == 2 || b.fillMode == 4)) {
        g = !0;
        break;
      }
    }
    if (!g)
      return a.hit = !0, a.pickedMesh = this, a.distance = p.Distance(e.origin, h.boundingSphere.center), a.subMeshId = -1, a;
    for (let f = 0; f < d; f++) {
      const m = u.data[f];
      if (d > 1 && !m.canIntersects(e))
        continue;
      const b = m.intersects(e, this._positions, this.getIndices(), t, i);
      if (b && (t || !c || b.distance < c.distance) && (c = b, c.subMeshId = f, t))
        break;
    }
    if (c) {
      const f = r ?? this.getWorldMatrix(), m = C.Vector3[0], b = C.Vector3[1];
      p.TransformCoordinatesToRef(e.origin, f, m), e.direction.scaleToRef(c.distance, b);
      const M = p.TransformNormal(b, f).addInPlace(m);
      return a.hit = !0, a.distance = p.Distance(m, M), a.pickedPoint = M, a.pickedMesh = this, a.bu = c.bu || 0, a.bv = c.bv || 0, a.subMeshFaceId = c.faceId, a.faceId = c.faceId + u.data[c.subMeshId].indexStart / (this.getClassName().indexOf("LinesMesh") !== -1 ? 2 : 3), a.subMeshId = c.subMeshId, a;
    }
    return a;
  }
  /**
   * 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(e, t, i) {
    return null;
  }
  /**
   * Disposes all the submeshes of the current meshnp
   * @returns the current mesh
   */
  releaseSubMeshes() {
    if (this.subMeshes)
      for (; this.subMeshes.length; )
        this.subMeshes[0].dispose();
    else
      this.subMeshes = new Array();
    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(e, t = !1) {
    let i;
    for (this._scene.useMaterialMeshMap && this._internalAbstractMeshDataInfo._material && this._internalAbstractMeshDataInfo._material.meshMap && (this._internalAbstractMeshDataInfo._material.meshMap[this.uniqueId] = void 0), this.getScene().freeActiveMeshes(), this.getScene().freeRenderingGroups(), this.actionManager !== void 0 && this.actionManager !== null && (this.actionManager.dispose(), this.actionManager = null), this._internalAbstractMeshDataInfo._skeleton = null, this._transformMatrixTexture && (this._transformMatrixTexture.dispose(), this._transformMatrixTexture = null), i = 0; i < this._intersectionsInProgress.length; i++) {
      const n = this._intersectionsInProgress[i], a = n._intersectionsInProgress.indexOf(this);
      n._intersectionsInProgress.splice(a, 1);
    }
    this._intersectionsInProgress.length = 0, this.getScene().lights.forEach((n) => {
      let a = n.includedOnlyMeshes.indexOf(this);
      a !== -1 && n.includedOnlyMeshes.splice(a, 1), a = n.excludedMeshes.indexOf(this), a !== -1 && n.excludedMeshes.splice(a, 1);
      const o = n.getShadowGenerators();
      if (o) {
        const h = o.values();
        for (let c = h.next(); c.done !== !0; c = h.next()) {
          const d = c.value.getShadowMap();
          d && d.renderList && (a = d.renderList.indexOf(this), a !== -1 && d.renderList.splice(a, 1));
        }
      }
    }), (this.getClassName() !== "InstancedMesh" || this.getClassName() !== "InstancedLinesMesh") && this.releaseSubMeshes();
    const r = this.getScene().getEngine();
    if (this._occlusionQuery !== null && (this.isOcclusionQueryInProgress = !1, r.deleteQuery(this._occlusionQuery), this._occlusionQuery = null), r.wipeCaches(), this.getScene().removeMesh(this), this._parentContainer) {
      const n = this._parentContainer.meshes.indexOf(this);
      n > -1 && this._parentContainer.meshes.splice(n, 1), this._parentContainer = null;
    }
    if (t && this.material && (this.material.getClassName() === "MultiMaterial" ? this.material.dispose(!1, !0, !0) : this.material.dispose(!1, !0)), !e)
      for (i = 0; i < this.getScene().particleSystems.length; i++)
        this.getScene().particleSystems[i].emitter === this && (this.getScene().particleSystems[i].dispose(), i--);
    this._internalAbstractMeshDataInfo._facetData.facetDataEnabled && this.disableFacetData(), this._uniformBuffer.dispose(), this.onAfterWorldMatrixUpdateObservable.clear(), this.onCollideObservable.clear(), this.onCollisionPositionChangeObservable.clear(), this.onRebuildObservable.clear(), super.dispose(e, t);
  }
  /**
   * Adds the passed mesh as a child to the current mesh
   * @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(e, t = !1) {
    return e.setParent(this, t), 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(e, t = !1) {
    return e.setParent(null, t), this;
  }
  // Facet data
  /** @internal */
  _initFacetData() {
    const e = this._internalAbstractMeshDataInfo._facetData;
    e.facetNormals || (e.facetNormals = new Array()), e.facetPositions || (e.facetPositions = new Array()), e.facetPartitioning || (e.facetPartitioning = new Array()), e.facetNb = this.getIndices().length / 3 | 0, e.partitioningSubdivisions = e.partitioningSubdivisions ? e.partitioningSubdivisions : 10, e.partitioningBBoxRatio = e.partitioningBBoxRatio ? e.partitioningBBoxRatio : 1.01;
    for (let t = 0; t < e.facetNb; t++)
      e.facetNormals[t] = p.Zero(), e.facetPositions[t] = p.Zero();
    return e.facetDataEnabled = !0, 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 e = this._internalAbstractMeshDataInfo._facetData;
    e.facetDataEnabled || this._initFacetData();
    const t = this.getVerticesData(_.PositionKind), i = this.getIndices(), s = this.getVerticesData(_.NormalKind), r = this.getBoundingInfo();
    if (e.facetDepthSort && !e.facetDepthSortEnabled) {
      if (e.facetDepthSortEnabled = !0, i instanceof Uint16Array)
        e.depthSortedIndices = new Uint16Array(i);
      else if (i instanceof Uint32Array)
        e.depthSortedIndices = new Uint32Array(i);
      else {
        let a = !1;
        for (let o = 0; o < i.length; o++)
          if (i[o] > 65535) {
            a = !0;
            break;
          }
        a ? e.depthSortedIndices = new Uint32Array(i) : e.depthSortedIndices = new Uint16Array(i);
      }
      if (e.facetDepthSortFunction = function(a, o) {
        return o.sqDistance - a.sqDistance;
      }, !e.facetDepthSortFrom) {
        const a = this.getScene().activeCamera;
        e.facetDepthSortFrom = a ? a.position : p.Zero();
      }
      e.depthSortedFacets = [];
      for (let a = 0; a < e.facetNb; a++) {
        const o = { ind: a * 3, sqDistance: 0 };
        e.depthSortedFacets.push(o);
      }
      e.invertedMatrix = R.Identity(), e.facetDepthSortOrigin = p.Zero();
    }
    e.bbSize.x = r.maximum.x - r.minimum.x > ye ? r.maximum.x - r.minimum.x : ye, e.bbSize.y = r.maximum.y - r.minimum.y > ye ? r.maximum.y - r.minimum.y : ye, e.bbSize.z = r.maximum.z - r.minimum.z > ye ? r.maximum.z - r.minimum.z : ye;
    let n = e.bbSize.x > e.bbSize.y ? e.bbSize.x : e.bbSize.y;
    if (n = n > e.bbSize.z ? n : e.bbSize.z, e.subDiv.max = e.partitioningSubdivisions, e.subDiv.X = Math.floor(e.subDiv.max * e.bbSize.x / n), e.subDiv.Y = Math.floor(e.subDiv.max * e.bbSize.y / n), e.subDiv.Z = Math.floor(e.subDiv.max * e.bbSize.z / n), e.subDiv.X = e.subDiv.X < 1 ? 1 : e.subDiv.X, e.subDiv.Y = e.subDiv.Y < 1 ? 1 : e.subDiv.Y, e.subDiv.Z = e.subDiv.Z < 1 ? 1 : e.subDiv.Z, e.facetParameters.facetNormals = this.getFacetLocalNormals(), e.facetParameters.facetPositions = this.getFacetLocalPositions(), e.facetParameters.facetPartitioning = this.getFacetLocalPartitioning(), e.facetParameters.bInfo = r, e.facetParameters.bbSize = e.bbSize, e.facetParameters.subDiv = e.subDiv, e.facetParameters.ratio = this.partitioningBBoxRatio, e.facetParameters.depthSort = e.facetDepthSort, e.facetDepthSort && e.facetDepthSortEnabled && (this.computeWorldMatrix(!0), this._worldMatrix.invertToRef(e.invertedMatrix), p.TransformCoordinatesToRef(e.facetDepthSortFrom, e.invertedMatrix, e.facetDepthSortOrigin), e.facetParameters.distanceTo = e.facetDepthSortOrigin), e.facetParameters.depthSortedFacets = e.depthSortedFacets, s && q.ComputeNormals(t, i, s, e.facetParameters), e.facetDepthSort && e.facetDepthSortEnabled) {
      e.depthSortedFacets.sort(e.facetDepthSortFunction);
      const a = e.depthSortedIndices.length / 3 | 0;
      for (let o = 0; o < a; o++) {
        const h = e.depthSortedFacets[o].ind;
        e.depthSortedIndices[o * 3] = i[h], e.depthSortedIndices[o * 3 + 1] = i[h + 1], e.depthSortedIndices[o * 3 + 2] = i[h + 2];
      }
      this.updateIndices(e.depthSortedIndices, void 0, !0);
    }
    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 e = this._internalAbstractMeshDataInfo._facetData;
    return e.facetNormals || this.updateFacetData(), e.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 e = this._internalAbstractMeshDataInfo._facetData;
    return e.facetPositions || this.updateFacetData(), e.facetPositions;
  }
  /**
   * Returns the facetLocalPartitioning array
   * @returns an array of array of numbers
   * @see https://doc.babylonjs.com/features/featuresDeepDive/mesh/facetData
   */
  getFacetLocalPartitioning() {
    const e = this._internalAbstractMeshDataInfo._facetData;
    return e.facetPartitioning || this.updateFacetData(), e.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(e) {
    const t = p.Zero();
    return this.getFacetPositionToRef(e, t), t;
  }
  /**
   * 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(e, t) {
    const i = this.getFacetLocalPositions()[e], s = this.getWorldMatrix();
    return p.TransformCoordinatesToRef(i, s, t), 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(e) {
    const t = p.Zero();
    return this.getFacetNormalToRef(e, t), t;
  }
  /**
   * 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(e, t) {
    const i = this.getFacetLocalNormals()[e];
    return p.TransformNormalToRef(i, this.getWorldMatrix(), t), 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(e, t, i) {
    const s = this.getBoundingInfo(), r = this._internalAbstractMeshDataInfo._facetData, n = Math.floor((e - s.minimum.x * r.partitioningBBoxRatio) * r.subDiv.X * r.partitioningBBoxRatio / r.bbSize.x), a = Math.floor((t - s.minimum.y * r.partitioningBBoxRatio) * r.subDiv.Y * r.partitioningBBoxRatio / r.bbSize.y), o = Math.floor((i - s.minimum.z * r.partitioningBBoxRatio) * r.subDiv.Z * r.partitioningBBoxRatio / r.bbSize.z);
    return n < 0 || n > r.subDiv.max || a < 0 || a > r.subDiv.max || o < 0 || o > r.subDiv.max ? null : r.facetPartitioning[n + r.subDiv.max * a + r.subDiv.max * r.subDiv.max * o];
  }
  /**
   * 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(e, t, i, s, r = !1, n = !0) {
    const a = this.getWorldMatrix(), o = C.Matrix[5];
    a.invertToRef(o);
    const h = C.Vector3[8];
    p.TransformCoordinatesFromFloatsToRef(e, t, i, o, h);
    const c = this.getClosestFacetAtLocalCoordinates(h.x, h.y, h.z, s, r, n);
    return s && p.TransformCoordinatesFromFloatsToRef(s.x, s.y, s.z, a, s), c;
  }
  /**
   * 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(e, t, i, s, r = !1, n = !0) {
    let a = null, o = 0, h = 0, c = 0, u = 0, d = 0, g = 0, f = 0, m = 0;
    const b = this.getFacetLocalPositions(), T = this.getFacetLocalNormals(), M = this.getFacetsAtLocalCoordinates(e, t, i);
    if (!M)
      return null;
    let v = Number.MAX_VALUE, A = v, E, y, x;
    for (let D = 0; D < M.length; D++)
      E = M[D], y = T[E], x = b[E], u = (e - x.x) * y.x + (t - x.y) * y.y + (i - x.z) * y.z, (!r || r && n && u >= 0 || r && !n && u <= 0) && (u = y.x * x.x + y.y * x.y + y.z * x.z, d = -(y.x * e + y.y * t + y.z * i - u) / (y.x * y.x + y.y * y.y + y.z * y.z), g = e + y.x * d, f = t + y.y * d, m = i + y.z * d, o = g - e, h = f - t, c = m - i, A = o * o + h * h + c * c, A < v && (v = A, a = E, s && (s.x = g, s.y = f, s.z = m)));
    return a;
  }
  /**
   * 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 e = this._internalAbstractMeshDataInfo._facetData;
    return e.facetDataEnabled && (e.facetDataEnabled = !1, e.facetPositions = new Array(), e.facetNormals = new Array(), e.facetPartitioning = new Array(), e.facetParameters = null, e.depthSortedIndices = new Uint32Array(0)), 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(e, t, i = !1) {
    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(e) {
    const t = this.getVerticesData(_.PositionKind), i = this.getIndices();
    let s;
    return this.isVerticesDataPresent(_.NormalKind) ? s = this.getVerticesData(_.NormalKind) : s = [], q.ComputeNormals(t, i, s, { useRightHandedSystem: this.getScene().useRightHandedSystem }), this.setVerticesData(_.NormalKind, s, e), 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(e, t) {
    t || (t = ci.Y);
    const i = C.Vector3[0], s = C.Vector3[1];
    return p.CrossToRef(t, e, s), p.CrossToRef(e, s, i), this.rotationQuaternion ? X.RotationQuaternionFromAxisToRef(i, e, s, this.rotationQuaternion) : p.RotationFromAxisToRef(i, e, s, this.rotation), this;
  }
  /** @internal */
  _checkOcclusionQuery() {
    return !1;
  }
  /**
   * Disables the mesh edge rendering mode
   * @returns the currentAbstractMesh
   */
  disableEdgesRendering() {
    throw Y("EdgesRenderer");
  }
  /**
   * 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(e, t, i) {
    throw Y("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((e) => e.emitter === this);
  }
}
Ge.OCCLUSION_TYPE_NONE = 0;
Ge.OCCLUSION_TYPE_OPTIMISTIC = 1;
Ge.OCCLUSION_TYPE_STRICT = 2;
Ge.OCCLUSION_ALGORITHM_TYPE_ACCURATE = 0;
Ge.OCCLUSION_ALGORITHM_TYPE_CONSERVATIVE = 1;
Ge.CULLINGSTRATEGY_STANDARD = 0;
Ge.CULLINGSTRATEGY_BOUNDINGSPHERE_ONLY = 1;
Ge.CULLINGSTRATEGY_OPTIMISTIC_INCLUSION = 2;
Ge.CULLINGSTRATEGY_OPTIMISTIC_INCLUSION_THEN_BSPHERE_ONLY = 3;
dt("BABYLON.AbstractMesh", Ge);
function Ur(l) {
  l.indexOf("vClipPlane") === -1 && l.push("vClipPlane"), l.indexOf("vClipPlane2") === -1 && l.push("vClipPlane2"), l.indexOf("vClipPlane3") === -1 && l.push("vClipPlane3"), l.indexOf("vClipPlane4") === -1 && l.push("vClipPlane4"), l.indexOf("vClipPlane5") === -1 && l.push("vClipPlane5"), l.indexOf("vClipPlane6") === -1 && l.push("vClipPlane6");
}
function Nr(l, e, t) {
  var i, s, r, n, a, o;
  const h = !!((i = l.clipPlane) !== null && i !== void 0 ? i : e.clipPlane), c = !!((s = l.clipPlane2) !== null && s !== void 0 ? s : e.clipPlane2), u = !!((r = l.clipPlane3) !== null && r !== void 0 ? r : e.clipPlane3), d = !!((n = l.clipPlane4) !== null && n !== void 0 ? n : e.clipPlane4), g = !!((a = l.clipPlane5) !== null && a !== void 0 ? a : e.clipPlane5), f = !!((o = l.clipPlane6) !== null && o !== void 0 ? o : e.clipPlane6);
  h && t.push("#define CLIPPLANE"), c && t.push("#define CLIPPLANE2"), u && t.push("#define CLIPPLANE3"), d && t.push("#define CLIPPLANE4"), g && t.push("#define CLIPPLANE5"), f && t.push("#define CLIPPLANE6");
}
function Rr(l, e, t) {
  var i, s, r, n, a, o;
  let h = !1;
  const c = !!((i = l.clipPlane) !== null && i !== void 0 ? i : e.clipPlane), u = !!((s = l.clipPlane2) !== null && s !== void 0 ? s : e.clipPlane2), d = !!((r = l.clipPlane3) !== null && r !== void 0 ? r : e.clipPlane3), g = !!((n = l.clipPlane4) !== null && n !== void 0 ? n : e.clipPlane4), f = !!((a = l.clipPlane5) !== null && a !== void 0 ? a : e.clipPlane5), m = !!((o = l.clipPlane6) !== null && o !== void 0 ? o : e.clipPlane6);
  return t.CLIPPLANE !== c && (t.CLIPPLANE = c, h = !0), t.CLIPPLANE2 !== u && (t.CLIPPLANE2 = u, h = !0), t.CLIPPLANE3 !== d && (t.CLIPPLANE3 = d, h = !0), t.CLIPPLANE4 !== g && (t.CLIPPLANE4 = g, h = !0), t.CLIPPLANE5 !== f && (t.CLIPPLANE5 = f, h = !0), t.CLIPPLANE6 !== m && (t.CLIPPLANE6 = m, h = !0), h;
}
function kr(l, e, t) {
  var i, s, r, n, a, o;
  let h = (i = e.clipPlane) !== null && i !== void 0 ? i : t.clipPlane;
  Pt(l, "vClipPlane", h), h = (s = e.clipPlane2) !== null && s !== void 0 ? s : t.clipPlane2, Pt(l, "vClipPlane2", h), h = (r = e.clipPlane3) !== null && r !== void 0 ? r : t.clipPlane3, Pt(l, "vClipPlane3", h), h = (n = e.clipPlane4) !== null && n !== void 0 ? n : t.clipPlane4, Pt(l, "vClipPlane4", h), h = (a = e.clipPlane5) !== null && a !== void 0 ? a : t.clipPlane5, Pt(l, "vClipPlane5", h), h = (o = e.clipPlane6) !== null && o !== void 0 ? o : t.clipPlane6, Pt(l, "vClipPlane6", h);
}
function Pt(l, e, t) {
  t && l.setFloat4(e, t.normal.x, t.normal.y, t.normal.z, t.d);
}
class Bt {
  /**
   * Binds the scene's uniform buffer to the effect.
   * @param effect defines the effect to bind to the scene uniform buffer
   * @param sceneUbo defines the uniform buffer storing scene data
   */
  static BindSceneUniformBuffer(e, t) {
    t.bindToEffect(e, "Scene");
  }
  /**
   * Helps preparing the defines values about the UVs in used in the effect.
   * UVs are shared as much as we can across channels in the shaders.
   * @param texture The texture we are preparing the UVs for
   * @param defines The defines to update
   * @param key The channel key "diffuse", "specular"... used in the shader
   */
  static PrepareDefinesForMergedUV(e, t, i) {
    t._needUVs = !0, t[i] = !0, e.optimizeUVAllocation && e.getTextureMatrix().isIdentityAs3x2() ? (t[i + "DIRECTUV"] = e.coordinatesIndex + 1, t["MAINUV" + (e.coordinatesIndex + 1)] = !0) : t[i + "DIRECTUV"] = 0;
  }
  /**
   * Binds a texture matrix value to its corresponding uniform
   * @param texture The texture to bind the matrix for
   * @param uniformBuffer The uniform buffer receiving the data
   * @param key The channel key "diffuse", "specular"... used in the shader
   */
  static BindTextureMatrix(e, t, i) {
    const s = e.getTextureMatrix();
    t.updateMatrix(i + "Matrix", s);
  }
  /**
   * Gets the current status of the fog (should it be enabled?)
   * @param mesh defines the mesh to evaluate for fog support
   * @param scene defines the hosting scene
   * @returns true if fog must be enabled
   */
  static GetFogState(e, t) {
    return t.fogEnabled && e.applyFog && t.fogMode !== Q.FOGMODE_NONE;
  }
  /**
   * Helper used to prepare the list of defines associated with misc. values for shader compilation
   * @param mesh defines the current mesh
   * @param scene defines the current scene
   * @param useLogarithmicDepth defines if logarithmic depth has to be turned on
   * @param pointsCloud defines if point cloud rendering has to be turned on
   * @param fogEnabled defines if fog has to be turned on
   * @param alphaTest defines if alpha testing has to be turned on
   * @param defines defines the current list of defines
   */
  static PrepareDefinesForMisc(e, t, i, s, r, n, a) {
    a._areMiscDirty && (a.LOGARITHMICDEPTH = i, a.POINTSIZE = s, a.FOG = r && this.GetFogState(e, t), a.NONUNIFORMSCALING = e.nonUniformScaling, a.ALPHATEST = n);
  }
  /**
   * Helper used to prepare the defines relative to the active camera
   * @param scene defines the current scene
   * @param defines specifies the list of active defines
   * @returns true if the defines have been updated, else false
   */
  static PrepareDefinesForCamera(e, t) {
    let i = !1;
    if (e.activeCamera) {
      const s = t.CAMERA_ORTHOGRAPHIC ? 1 : 0, r = t.CAMERA_PERSPECTIVE ? 1 : 0, n = e.activeCamera.mode === Z.ORTHOGRAPHIC_CAMERA ? 1 : 0, a = e.activeCamera.mode === Z.PERSPECTIVE_CAMERA ? 1 : 0;
      (s ^ n || r ^ a) && (t.CAMERA_ORTHOGRAPHIC = n === 1, t.CAMERA_PERSPECTIVE = a === 1, i = !0);
    }
    return i;
  }
  /**
   * Helper used to prepare the list of defines associated with frame values for shader compilation
   * @param scene defines the current scene
   * @param engine defines the current engine
   * @param material defines the material we are compiling the shader for
   * @param defines specifies the list of active defines
   * @param useInstances defines if instances have to be turned on
   * @param useClipPlane defines if clip plane have to be turned on
   * @param useThinInstances defines if thin instances have to be turned on
   */
  static PrepareDefinesForFrameBoundValues(e, t, i, s, r, n = null, a = !1) {
    let o = Bt.PrepareDefinesForCamera(e, s);
    n !== !1 && (o = Rr(i, e, s)), s.DEPTHPREPASS !== !t.getColorWrite() && (s.DEPTHPREPASS = !s.DEPTHPREPASS, o = !0), s.INSTANCES !== r && (s.INSTANCES = r, o = !0), s.THIN_INSTANCES !== a && (s.THIN_INSTANCES = a, o = !0), o && s.markAsUnprocessed();
  }
  /**
   * Prepares the defines for bones
   * @param mesh The mesh containing the geometry data we will draw
   * @param defines The defines to update
   */
  static PrepareDefinesForBones(e, t) {
    if (e.useBones && e.computeBonesUsingShaders && e.skeleton) {
      t.NUM_BONE_INFLUENCERS = e.numBoneInfluencers;
      const i = t.BONETEXTURE !== void 0;
      if (e.skeleton.isUsingTextureForMatrices && i)
        t.BONETEXTURE = !0;
      else {
        t.BonesPerMesh = e.skeleton.bones.length + 1, t.BONETEXTURE = i ? !1 : void 0;
        const s = e.getScene().prePassRenderer;
        if (s && s.enabled) {
          const r = s.excludedSkinnedMesh.indexOf(e) === -1;
          t.BONES_VELOCITY_ENABLED = r;
        }
      }
    } else
      t.NUM_BONE_INFLUENCERS = 0, t.BonesPerMesh = 0, t.BONETEXTURE !== void 0 && (t.BONETEXTURE = !1);
  }
  /**
   * Prepares the defines for morph targets
   * @param mesh The mesh containing the geometry data we will draw
   * @param defines The defines to update
   */
  static PrepareDefinesForMorphTargets(e, t) {
    const i = e.morphTargetManager;
    i ? (t.MORPHTARGETS_UV = i.supportsUVs && t.UV1, t.MORPHTARGETS_TANGENT = i.supportsTangents && t.TANGENT, t.MORPHTARGETS_NORMAL = i.supportsNormals && t.NORMAL, t.MORPHTARGETS = i.numInfluencers > 0, t.NUM_MORPH_INFLUENCERS = i.numInfluencers, t.MORPHTARGETS_TEXTURE = i.isUsingTextureForTargets) : (t.MORPHTARGETS_UV = !1, t.MORPHTARGETS_TANGENT = !1, t.MORPHTARGETS_NORMAL = !1, t.MORPHTARGETS = !1, t.NUM_MORPH_INFLUENCERS = 0);
  }
  /**
   * Prepares the defines for baked vertex animation
   * @param mesh The mesh containing the geometry data we will draw
   * @param defines The defines to update
   */
  static PrepareDefinesForBakedVertexAnimation(e, t) {
    const i = e.bakedVertexAnimationManager;
    t.BAKED_VERTEX_ANIMATION_TEXTURE = !!(i && i.isEnabled);
  }
  /**
   * Prepares the defines used in the shader depending on the attributes data available in the mesh
   * @param mesh The mesh containing the geometry data we will draw
   * @param defines The defines to update
   * @param useVertexColor Precise whether vertex colors should be used or not (override mesh info)
   * @param useBones Precise whether bones should be used or not (override mesh info)
   * @param useMorphTargets Precise whether morph targets should be used or not (override mesh info)
   * @param useVertexAlpha Precise whether vertex alpha should be used or not (override mesh info)
   * @param useBakedVertexAnimation Precise whether baked vertex animation should be used or not (override mesh info)
   * @returns false if defines are considered not dirty and have not been checked
   */
  static PrepareDefinesForAttributes(e, t, i, s, r = !1, n = !0, a = !0) {
    if (!t._areAttributesDirty && t._needNormals === t._normals && t._needUVs === t._uvs)
      return !1;
    t._normals = t._needNormals, t._uvs = t._needUVs, t.NORMAL = t._needNormals && e.isVerticesDataPresent(_.NormalKind), t._needNormals && e.isVerticesDataPresent(_.TangentKind) && (t.TANGENT = !0);
    for (let o = 1; o <= 6; ++o)
      t["UV" + o] = t._needUVs ? e.isVerticesDataPresent(`uv${o === 1 ? "" : o}`) : !1;
    if (i) {
      const o = e.useVertexColors && e.isVerticesDataPresent(_.ColorKind);
      t.VERTEXCOLOR = o, t.VERTEXALPHA = e.hasVertexAlpha && o && n;
    }
    return e.isVerticesDataPresent(_.ColorInstanceKind) && (e.hasInstances || e.hasThinInstances) && (t.INSTANCESCOLOR = !0), s && this.PrepareDefinesForBones(e, t), r && this.PrepareDefinesForMorphTargets(e, t), a && this.PrepareDefinesForBakedVertexAnimation(e, t), !0;
  }
  /**
   * Prepares the defines related to multiview
   * @param scene The scene we are intending to draw
   * @param defines The defines to update
   */
  static PrepareDefinesForMultiview(e, t) {
    if (e.activeCamera) {
      const i = t.MULTIVIEW;
      t.MULTIVIEW = e.activeCamera.outputRenderTarget !== null && e.activeCamera.outputRenderTarget.getViewCount() > 1, t.MULTIVIEW != i && t.markAsUnprocessed();
    }
  }
  /**
   * Prepares the defines related to order independant transparency
   * @param scene The scene we are intending to draw
   * @param defines The defines to update
   * @param needAlphaBlending Determines if the material needs alpha blending
   */
  static PrepareDefinesForOIT(e, t, i) {
    const s = t.ORDER_INDEPENDENT_TRANSPARENCY, r = t.ORDER_INDEPENDENT_TRANSPARENCY_16BITS;
    t.ORDER_INDEPENDENT_TRANSPARENCY = e.useOrderIndependentTransparency && i, t.ORDER_INDEPENDENT_TRANSPARENCY_16BITS = !e.getEngine().getCaps().textureFloatLinearFiltering, (s !== t.ORDER_INDEPENDENT_TRANSPARENCY || r !== t.ORDER_INDEPENDENT_TRANSPARENCY_16BITS) && t.markAsUnprocessed();
  }
  /**
   * Prepares the defines related to the prepass
   * @param scene The scene we are intending to draw
   * @param defines The defines to update
   * @param canRenderToMRT Indicates if this material renders to several textures in the prepass
   */
  static PrepareDefinesForPrePass(e, t, i) {
    const s = t.PREPASS;
    if (!t._arePrePassDirty)
      return;
    const r = [
      {
        type: 1,
        define: "PREPASS_POSITION",
        index: "PREPASS_POSITION_INDEX"
      },
      {
        type: 2,
        define: "PREPASS_VELOCITY",
        index: "PREPASS_VELOCITY_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: 6,
        define: "PREPASS_NORMAL",
        index: "PREPASS_NORMAL_INDEX"
      }
    ];
    if (e.prePassRenderer && e.prePassRenderer.enabled && i) {
      t.PREPASS = !0, t.SCENE_MRT_COUNT = e.prePassRenderer.mrtCount;
      for (let n = 0; n < r.length; n++) {
        const a = e.prePassRenderer.getIndex(r[n].type);
        a !== -1 ? (t[r[n].define] = !0, t[r[n].index] = a) : t[r[n].define] = !1;
      }
    } else {
      t.PREPASS = !1;
      for (let n = 0; n < r.length; n++)
        t[r[n].define] = !1;
    }
    t.PREPASS != s && (t.markAsUnprocessed(), t.markAsImageProcessingDirty());
  }
  /**
   * Prepares the defines related to the light information passed in parameter
   * @param scene The scene we are intending to draw
   * @param mesh The mesh the effect is compiling for
   * @param light The light the effect is compiling for
   * @param lightIndex The index of the light
   * @param defines The defines to update
   * @param specularSupported Specifies whether specular is supported or not (override lights data)
   * @param state Defines the current state regarding what is needed (normals, etc...)
   * @param state.needNormals
   * @param state.needRebuild
   * @param state.shadowEnabled
   * @param state.specularEnabled
   * @param state.lightmapMode
   */
  static PrepareDefinesForLight(e, t, i, s, r, n, a) {
    var o;
    switch (a.needNormals = !0, r["LIGHT" + s] === void 0 && (a.needRebuild = !0), r["LIGHT" + s] = !0, r["SPOTLIGHT" + s] = !1, r["HEMILIGHT" + s] = !1, r["POINTLIGHT" + s] = !1, r["DIRLIGHT" + s] = !1, i.prepareLightSpecificDefines(r, s), r["LIGHT_FALLOFF_PHYSICAL" + s] = !1, r["LIGHT_FALLOFF_GLTF" + s] = !1, r["LIGHT_FALLOFF_STANDARD" + s] = !1, i.falloffType) {
      case me.FALLOFF_GLTF:
        r["LIGHT_FALLOFF_GLTF" + s] = !0;
        break;
      case me.FALLOFF_PHYSICAL:
        r["LIGHT_FALLOFF_PHYSICAL" + s] = !0;
        break;
      case me.FALLOFF_STANDARD:
        r["LIGHT_FALLOFF_STANDARD" + s] = !0;
        break;
    }
    if (n && !i.specular.equalsFloats(0, 0, 0) && (a.specularEnabled = !0), r["SHADOW" + s] = !1, r["SHADOWCSM" + s] = !1, r["SHADOWCSMDEBUG" + s] = !1, r["SHADOWCSMNUM_CASCADES" + s] = !1, r["SHADOWCSMUSESHADOWMAXZ" + s] = !1, r["SHADOWCSMNOBLEND" + s] = !1, r["SHADOWCSM_RIGHTHANDED" + s] = !1, r["SHADOWPCF" + s] = !1, r["SHADOWPCSS" + s] = !1, r["SHADOWPOISSON" + s] = !1, r["SHADOWESM" + s] = !1, r["SHADOWCLOSEESM" + s] = !1, r["SHADOWCUBE" + s] = !1, r["SHADOWLOWQUALITY" + s] = !1, r["SHADOWMEDIUMQUALITY" + s] = !1, t && t.receiveShadows && e.shadowsEnabled && i.shadowEnabled) {
      const h = (o = i.getShadowGenerator(e.activeCamera)) !== null && o !== void 0 ? o : i.getShadowGenerator();
      if (h) {
        const c = h.getShadowMap();
        c && c.renderList && c.renderList.length > 0 && (a.shadowEnabled = !0, h.prepareDefines(r, s));
      }
    }
    i.lightmapMode != me.LIGHTMAP_DEFAULT ? (a.lightmapMode = !0, r["LIGHTMAPEXCLUDED" + s] = !0, r["LIGHTMAPNOSPECULAR" + s] = i.lightmapMode == me.LIGHTMAP_SHADOWSONLY) : (r["LIGHTMAPEXCLUDED" + s] = !1, r["LIGHTMAPNOSPECULAR" + s] = !1);
  }
  /**
   * Prepares the defines related to the light information passed in parameter
   * @param scene The scene we are intending to draw
   * @param mesh The mesh the effect is compiling for
   * @param defines The defines to update
   * @param specularSupported Specifies whether specular is supported or not (override lights data)
   * @param maxSimultaneousLights Specifies how manuy lights can be added to the effect at max
   * @param disableLighting Specifies whether the lighting is disabled (override scene and light)
   * @returns true if normals will be required for the rest of the effect
   */
  static PrepareDefinesForLights(e, t, i, s, r = 4, n = !1) {
    if (!i._areLightsDirty)
      return i._needNormals;
    let a = 0;
    const o = {
      needNormals: i._needNormals,
      needRebuild: !1,
      lightmapMode: !1,
      shadowEnabled: !1,
      specularEnabled: !1
    };
    if (e.lightsEnabled && !n) {
      for (const c of t.lightSources)
        if (this.PrepareDefinesForLight(e, t, c, a, i, s, o), a++, a === r)
          break;
    }
    i.SPECULARTERM = o.specularEnabled, i.SHADOWS = o.shadowEnabled;
    for (let c = a; c < r; c++)
      i["LIGHT" + c] !== void 0 && (i["LIGHT" + c] = !1, i["HEMILIGHT" + c] = !1, i["POINTLIGHT" + c] = !1, i["DIRLIGHT" + c] = !1, i["SPOTLIGHT" + c] = !1, i["SHADOW" + c] = !1, i["SHADOWCSM" + c] = !1, i["SHADOWCSMDEBUG" + c] = !1, i["SHADOWCSMNUM_CASCADES" + c] = !1, i["SHADOWCSMUSESHADOWMAXZ" + c] = !1, i["SHADOWCSMNOBLEND" + c] = !1, i["SHADOWCSM_RIGHTHANDED" + c] = !1, i["SHADOWPCF" + c] = !1, i["SHADOWPCSS" + c] = !1, i["SHADOWPOISSON" + c] = !1, i["SHADOWESM" + c] = !1, i["SHADOWCLOSEESM" + c] = !1, i["SHADOWCUBE" + c] = !1, i["SHADOWLOWQUALITY" + c] = !1, i["SHADOWMEDIUMQUALITY" + c] = !1);
    const h = e.getEngine().getCaps();
    return i.SHADOWFLOAT === void 0 && (o.needRebuild = !0), i.SHADOWFLOAT = o.shadowEnabled && (h.textureFloatRender && h.textureFloatLinearFiltering || h.textureHalfFloatRender && h.textureHalfFloatLinearFiltering), i.LIGHTMAPEXCLUDED = o.lightmapMode, o.needRebuild && i.rebuild(), o.needNormals;
  }
  /**
   * Prepares the uniforms and samplers list to be used in the effect (for a specific light)
   * @param lightIndex defines the light index
   * @param uniformsList The uniform list
   * @param samplersList The sampler list
   * @param projectedLightTexture defines if projected texture must be used
   * @param uniformBuffersList defines an optional list of uniform buffers
   * @param updateOnlyBuffersList True to only update the uniformBuffersList array
   */
  static PrepareUniformsAndSamplersForLight(e, t, i, s, r = null, n = !1) {
    r && r.push("Light" + e), !n && (t.push("vLightData" + e, "vLightDiffuse" + e, "vLightSpecular" + e, "vLightDirection" + e, "vLightFalloff" + e, "vLightGround" + e, "lightMatrix" + e, "shadowsInfo" + e, "depthValues" + e), i.push("shadowSampler" + e), i.push("depthSampler" + e), t.push("viewFrustumZ" + e, "cascadeBlendFactor" + e, "lightSizeUVCorrection" + e, "depthCorrection" + e, "penumbraDarkness" + e, "frustumLengths" + e), s && (i.push("projectionLightSampler" + e), t.push("textureProjectionMatrix" + e)));
  }
  /**
   * Prepares the uniforms and samplers list to be used in the effect
   * @param uniformsListOrOptions The uniform names to prepare or an EffectCreationOptions containing the list and extra information
   * @param samplersList The sampler list
   * @param defines The defines helping in the list generation
   * @param maxSimultaneousLights The maximum number of simultaneous light allowed in the effect
   */
  static PrepareUniformsAndSamplersList(e, t, i, s = 4) {
    let r, n = null;
    if (e.uniformsNames) {
      const a = e;
      r = a.uniformsNames, n = a.uniformBuffersNames, t = a.samplers, i = a.defines, s = a.maxSimultaneousLights || 0;
    } else
      r = e, t || (t = []);
    for (let a = 0; a < s && i["LIGHT" + a]; a++)
      this.PrepareUniformsAndSamplersForLight(a, r, t, i["PROJECTEDLIGHTTEXTURE" + a], n);
    i.NUM_MORPH_INFLUENCERS && r.push("morphTargetInfluences"), i.BAKED_VERTEX_ANIMATION_TEXTURE && (r.push("bakedVertexAnimationSettings"), r.push("bakedVertexAnimationTextureSizeInverted"), r.push("bakedVertexAnimationTime"), t.push("bakedVertexAnimationTexture"));
  }
  /**
   * This helps decreasing rank by rank the shadow quality (0 being the highest rank and quality)
   * @param defines The defines to update while falling back
   * @param fallbacks The authorized effect fallbacks
   * @param maxSimultaneousLights The maximum number of lights allowed
   * @param rank the current rank of the Effect
   * @returns The newly affected rank
   */
  static HandleFallbacksForShadows(e, t, i = 4, s = 0) {
    let r = 0;
    for (let n = 0; n < i && e["LIGHT" + n]; n++)
      n > 0 && (r = s + n, t.addFallback(r, "LIGHT" + n)), e.SHADOWS || (e["SHADOW" + n] && t.addFallback(s, "SHADOW" + n), e["SHADOWPCF" + n] && t.addFallback(s, "SHADOWPCF" + n), e["SHADOWPCSS" + n] && t.addFallback(s, "SHADOWPCSS" + n), e["SHADOWPOISSON" + n] && t.addFallback(s, "SHADOWPOISSON" + n), e["SHADOWESM" + n] && t.addFallback(s, "SHADOWESM" + n), e["SHADOWCLOSEESM" + n] && t.addFallback(s, "SHADOWCLOSEESM" + n));
    return r++;
  }
  /**
   * Prepares the list of attributes required for morph targets according to the effect defines.
   * @param attribs The current list of supported attribs
   * @param mesh The mesh to prepare the morph targets attributes for
   * @param influencers The number of influencers
   */
  static PrepareAttributesForMorphTargetsInfluencers(e, t, i) {
    this._TmpMorphInfluencers.NUM_MORPH_INFLUENCERS = i, this.PrepareAttributesForMorphTargets(e, t, this._TmpMorphInfluencers);
  }
  /**
   * Prepares the list of attributes required for morph targets according to the effect defines.
   * @param attribs The current list of supported attribs
   * @param mesh The mesh to prepare the morph targets attributes for
   * @param defines The current Defines of the effect
   */
  static PrepareAttributesForMorphTargets(e, t, i) {
    const s = i.NUM_MORPH_INFLUENCERS;
    if (s > 0 && J.LastCreatedEngine) {
      const r = J.LastCreatedEngine.getCaps().maxVertexAttribs, n = t.morphTargetManager;
      if (n != null && n.isUsingTextureForTargets)
        return;
      const a = n && n.supportsNormals && i.NORMAL, o = n && n.supportsTangents && i.TANGENT, h = n && n.supportsUVs && i.UV1;
      for (let c = 0; c < s; c++)
        e.push(_.PositionKind + c), a && e.push(_.NormalKind + c), o && e.push(_.TangentKind + c), h && e.push(_.UVKind + "_" + c), e.length > r && S.Error("Cannot add more vertex attributes for mesh " + t.name);
    }
  }
  /**
   * Prepares the list of attributes required for baked vertex animations according to the effect defines.
   * @param attribs The current list of supported attribs
   * @param mesh The mesh to prepare the morph targets attributes for
   * @param defines The current Defines of the effect
   */
  static PrepareAttributesForBakedVertexAnimation(e, t, i) {
    i.BAKED_VERTEX_ANIMATION_TEXTURE && i.INSTANCES && e.push("bakedVertexAnimationSettingsInstanced");
  }
  /**
   * Prepares the list of attributes required for bones according to the effect defines.
   * @param attribs The current list of supported attribs
   * @param mesh The mesh to prepare the bones attributes for
   * @param defines The current Defines of the effect
   * @param fallbacks The current effect fallback strategy
   */
  static PrepareAttributesForBones(e, t, i, s) {
    i.NUM_BONE_INFLUENCERS > 0 && (s.addCPUSkinningFallback(0, t), e.push(_.MatricesIndicesKind), e.push(_.MatricesWeightsKind), i.NUM_BONE_INFLUENCERS > 4 && (e.push(_.MatricesIndicesExtraKind), e.push(_.MatricesWeightsExtraKind)));
  }
  /**
   * Check and prepare the list of attributes required for instances according to the effect defines.
   * @param attribs The current list of supported attribs
   * @param defines The current MaterialDefines of the effect
   */
  static PrepareAttributesForInstances(e, t) {
    (t.INSTANCES || t.THIN_INSTANCES) && this.PushAttributesForInstances(e, !!t.PREPASS_VELOCITY), t.INSTANCESCOLOR && e.push(_.ColorInstanceKind);
  }
  /**
   * Add the list of attributes required for instances to the attribs array.
   * @param attribs The current list of supported attribs
   * @param needsPreviousMatrices If the shader needs previous matrices
   */
  static PushAttributesForInstances(e, t = !1) {
    e.push("world0"), e.push("world1"), e.push("world2"), e.push("world3"), t && (e.push("previousWorld0"), e.push("previousWorld1"), e.push("previousWorld2"), e.push("previousWorld3"));
  }
  /**
   * Binds the light information to the effect.
   * @param light The light containing the generator
   * @param effect The effect we are binding the data to
   * @param lightIndex The light index in the effect used to render
   */
  static BindLightProperties(e, t, i) {
    e.transferToEffect(t, i + "");
  }
  /**
   * Binds the lights information from the scene to the effect for the given mesh.
   * @param light Light to bind
   * @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
   */
  static BindLight(e, t, i, s, r, n = !0) {
    e._bindLight(t, i, s, r, n);
  }
  /**
   * Binds the lights information from the scene to the effect for the given mesh.
   * @param scene The scene the lights belongs to
   * @param mesh The mesh we are binding the information to render
   * @param effect The effect we are binding the data to
   * @param defines The generated defines for the effect
   * @param maxSimultaneousLights The maximum number of light that can be bound to the effect
   */
  static BindLights(e, t, i, s, r = 4) {
    const n = Math.min(t.lightSources.length, r);
    for (let a = 0; a < n; a++) {
      const o = t.lightSources[a];
      this.BindLight(o, a, e, i, typeof s == "boolean" ? s : s.SPECULARTERM, t.receiveShadows);
    }
  }
  /**
   * Binds the fog information from the scene to the effect for the given mesh.
   * @param scene The scene the lights belongs to
   * @param mesh The mesh we are binding the information to render
   * @param effect The effect we are binding the data to
   * @param linearSpace Defines if the fog effect is applied in linear space
   */
  static BindFogParameters(e, t, i, s = !1) {
    e.fogEnabled && t.applyFog && e.fogMode !== Q.FOGMODE_NONE && (i.setFloat4("vFogInfos", e.fogMode, e.fogStart, e.fogEnd, e.fogDensity), s ? (e.fogColor.toLinearSpaceToRef(this._TempFogColor, e.getEngine().useExactSrgbConversions), i.setColor3("vFogColor", this._TempFogColor)) : i.setColor3("vFogColor", e.fogColor));
  }
  /**
   * Binds the bones information from the mesh to the effect.
   * @param mesh The mesh we are binding the information to render
   * @param effect The effect we are binding the data to
   * @param prePassConfiguration Configuration for the prepass, in case prepass is activated
   */
  static BindBonesParameters(e, t, i) {
    if (!(!t || !e) && (e.computeBonesUsingShaders && t._bonesComputationForcedToCPU && (e.computeBonesUsingShaders = !1), e.useBones && e.computeBonesUsingShaders && e.skeleton)) {
      const s = e.skeleton;
      if (s.isUsingTextureForMatrices && t.getUniformIndex("boneTextureWidth") > -1) {
        const r = s.getTransformMatrixTexture(e);
        t.setTexture("boneSampler", r), t.setFloat("boneTextureWidth", 4 * (s.bones.length + 1));
      } else {
        const r = s.getTransformMatrices(e);
        r && (t.setMatrices("mBones", r), i && e.getScene().prePassRenderer && e.getScene().prePassRenderer.getIndex(2) && (i.previousBones[e.uniqueId] || (i.previousBones[e.uniqueId] = r.slice()), t.setMatrices("mPreviousBones", i.previousBones[e.uniqueId]), Bt._CopyBonesTransformationMatrices(r, i.previousBones[e.uniqueId])));
      }
    }
  }
  // Copies the bones transformation matrices into the target array and returns the target's reference
  static _CopyBonesTransformationMatrices(e, t) {
    return t.set(e), t;
  }
  /**
   * Binds the morph targets information from the mesh to the effect.
   * @param abstractMesh The mesh we are binding the information to render
   * @param effect The effect we are binding the data to
   */
  static BindMorphTargetParameters(e, t) {
    const i = e.morphTargetManager;
    !e || !i || t.setFloatArray("morphTargetInfluences", i.influences);
  }
  /**
   * Binds the logarithmic depth information from the scene to the effect for the given defines.
   * @param defines The generated defines used in the effect
   * @param effect The effect we are binding the data to
   * @param scene The scene we are willing to render with logarithmic scale for
   */
  static BindLogDepth(e, t, i) {
    if (!e || e.LOGARITHMICDEPTH || e.indexOf && e.indexOf("LOGARITHMICDEPTH") >= 0) {
      const s = i.activeCamera;
      s.mode === Z.ORTHOGRAPHIC_CAMERA && S.Error("Logarithmic depth is not compatible with orthographic cameras!", 20), t.setFloat("logarithmicDepthConstant", 2 / (Math.log(s.maxZ + 1) / Math.LN2));
    }
  }
}
Bt._TmpMorphInfluencers = { NUM_MORPH_INFLUENCERS: 0 };
Bt._TempFogColor = te.Black();
class ft {
  /**
   * Creates a material stencil state instance
   */
  constructor() {
    this.reset();
  }
  /**
   * Resets all the stencil states to default values
   */
  reset() {
    this.enabled = !1, this.mask = 255, this.func = 519, this.funcRef = 1, this.funcMask = 255, this.opStencilFail = 7680, this.opDepthFail = 7680, this.opStencilDepthPass = 7681;
  }
  /**
   * Gets or sets the stencil function
   */
  get func() {
    return this._func;
  }
  set func(e) {
    this._func = e;
  }
  /**
   * Gets or sets the stencil function reference
   */
  get funcRef() {
    return this._funcRef;
  }
  set funcRef(e) {
    this._funcRef = e;
  }
  /**
   * Gets or sets the stencil function mask
   */
  get funcMask() {
    return this._funcMask;
  }
  set funcMask(e) {
    this._funcMask = e;
  }
  /**
   * Gets or sets the operation when the stencil test fails
   */
  get opStencilFail() {
    return this._opStencilFail;
  }
  set opStencilFail(e) {
    this._opStencilFail = e;
  }
  /**
   * Gets or sets the operation when the depth test fails
   */
  get opDepthFail() {
    return this._opDepthFail;
  }
  set opDepthFail(e) {
    this._opDepthFail = e;
  }
  /**
   * Gets or sets the operation when the stencil+depth test succeeds
   */
  get opStencilDepthPass() {
    return this._opStencilDepthPass;
  }
  set opStencilDepthPass(e) {
    this._opStencilDepthPass = e;
  }
  /**
   * Gets or sets the stencil mask
   */
  get mask() {
    return this._mask;
  }
  set mask(e) {
    this._mask = e;
  }
  /**
   * Enables or disables the stencil test
   */
  get enabled() {
    return this._enabled;
  }
  set enabled(e) {
    this._enabled = e;
  }
  /**
   * 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(e) {
    he.Clone(() => e, this);
  }
  /**
   * Serializes this stencil configuration.
   * @returns - An object with the serialized config.
   */
  serialize() {
    return he.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(e, t, i) {
    he.Parse(() => this, e, t, i);
  }
}
F([
  B()
], ft.prototype, "func", null);
F([
  B()
], ft.prototype, "funcRef", null);
F([
  B()
], ft.prototype, "funcMask", null);
F([
  B()
], ft.prototype, "opStencilFail", null);
F([
  B()
], ft.prototype, "opDepthFail", null);
F([
  B()
], ft.prototype, "opStencilDepthPass", null);
F([
  B()
], ft.prototype, "mask", null);
F([
  B()
], ft.prototype, "enabled", null);
var mt;
(function(l) {
  l[l.Created = 1] = "Created", l[l.Disposed = 2] = "Disposed", l[l.GetDefineNames = 4] = "GetDefineNames", l[l.PrepareUniformBuffer = 8] = "PrepareUniformBuffer", l[l.IsReadyForSubMesh = 16] = "IsReadyForSubMesh", l[l.PrepareDefines = 32] = "PrepareDefines", l[l.BindForSubMesh = 64] = "BindForSubMesh", l[l.PrepareEffect = 128] = "PrepareEffect", l[l.GetAnimatables = 256] = "GetAnimatables", l[l.GetActiveTextures = 512] = "GetActiveTextures", l[l.HasTexture = 1024] = "HasTexture", l[l.FillRenderTargetTextures = 2048] = "FillRenderTargetTextures", l[l.HasRenderTargetTextures = 4096] = "HasRenderTargetTextures", l[l.HardBindForSubMesh = 8192] = "HardBindForSubMesh";
})(mt || (mt = {}));
class I {
  /**
   * If the material can be rendered to several textures with MRT extension
   */
  get canRenderToMRT() {
    return !1;
  }
  /**
   * Sets the alpha value of the material
   */
  set alpha(e) {
    if (this._alpha === e)
      return;
    const t = this._alpha;
    this._alpha = e, (t === 1 || e === 1) && this.markAsDirty(I.MiscDirtyFlag);
  }
  /**
   * 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(e) {
    this._backFaceCulling !== e && (this._backFaceCulling = e, this.markAsDirty(I.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(e) {
    this._cullBackFaces !== e && (this._cullBackFaces = e, this.markAsDirty(I.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(e) {
    this._blockDirtyMechanism !== e && (this._blockDirtyMechanism = e, e || 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(e) {
    this.blockDirtyMechanism = !0;
    try {
      e(this);
    } finally {
      this.blockDirtyMechanism = !1;
    }
  }
  /**
   * Gets a boolean indicating that current material needs to register RTT
   */
  get hasRenderTargetTextures() {
    return this._eventInfo.hasRenderTargetTextures = !1, this._callbackPluginEventHasRenderTargetTextures(this._eventInfo), this._eventInfo.hasRenderTargetTextures;
  }
  /**
   * Called during a dispose event
   */
  set onDispose(e) {
    this._onDisposeObserver && this.onDisposeObservable.remove(this._onDisposeObserver), this._onDisposeObserver = this.onDisposeObservable.add(e);
  }
  /**
   * An event triggered when the material is bound
   */
  get onBindObservable() {
    return this._onBindObservable || (this._onBindObservable = new w()), this._onBindObservable;
  }
  /**
   * Called during a bind event
   */
  set onBind(e) {
    this._onBindObserver && this.onBindObservable.remove(this._onBindObserver), this._onBindObserver = this.onBindObservable.add(e);
  }
  /**
   * An event triggered when the material is unbound
   */
  get onUnBindObservable() {
    return this._onUnBindObservable || (this._onUnBindObservable = new w()), this._onUnBindObservable;
  }
  /**
   * An event triggered when the effect is (re)created
   */
  get onEffectCreatedObservable() {
    return this._onEffectCreatedObservable || (this._onEffectCreatedObservable = new w()), this._onEffectCreatedObservable;
  }
  /**
   * Sets the value of the alpha mode.
   *
   * | Value | Type | Description |
   * | --- | --- | --- |
   * | 0 | ALPHA_DISABLE |   |
   * | 1 | ALPHA_ADD |   |
   * | 2 | ALPHA_COMBINE |   |
   * | 3 | ALPHA_SUBTRACT |   |
   * | 4 | ALPHA_MULTIPLY |   |
   * | 5 | ALPHA_MAXIMIZED |   |
   * | 6 | ALPHA_ONEONE |   |
   * | 7 | ALPHA_PREMULTIPLIED |   |
   * | 8 | ALPHA_PREMULTIPLIED_PORTERDUFF |   |
   * | 9 | ALPHA_INTERPOLATE |   |
   * | 10 | ALPHA_SCREENMODE |   |
   *
   */
  set alphaMode(e) {
    this._alphaMode !== e && (this._alphaMode = e, this.markAsDirty(I.TextureDirtyFlag));
  }
  /**
   * Gets the value of the alpha mode
   */
  get alphaMode() {
    return this._alphaMode;
  }
  /**
   * Sets the need depth pre-pass value
   */
  set needDepthPrePass(e) {
    this._needDepthPrePass !== e && (this._needDepthPrePass = e, this._needDepthPrePass && (this.checkReadyOnEveryCall = !0));
  }
  /**
   * Gets the depth pre-pass value
   */
  get needDepthPrePass() {
    return this._needDepthPrePass;
  }
  /**
   * Can this material render to prepass
   */
  get isPrePassCapable() {
    return !1;
  }
  /**
   * Sets the state for enabling fog
   */
  set fogEnabled(e) {
    this._fogEnabled !== e && (this._fogEnabled = e, this.markAsDirty(I.MiscDirtyFlag));
  }
  /**
   * Gets the value of the fog enabled state
   */
  get fogEnabled() {
    return this._fogEnabled;
  }
  get wireframe() {
    switch (this._fillMode) {
      case I.WireFrameFillMode:
      case I.LineListDrawMode:
      case I.LineLoopDrawMode:
      case I.LineStripDrawMode:
        return !0;
    }
    return this._scene.forceWireframe;
  }
  /**
   * Sets the state of wireframe mode
   */
  set wireframe(e) {
    this.fillMode = e ? I.WireFrameFillMode : I.TriangleFillMode;
  }
  /**
   * Gets the value specifying if point clouds are enabled
   */
  get pointsCloud() {
    switch (this._fillMode) {
      case I.PointFillMode:
      case I.PointListDrawMode:
        return !0;
    }
    return this._scene.forcePointsCloud;
  }
  /**
   * Sets the state of point cloud mode
   */
  set pointsCloud(e) {
    this.fillMode = e ? I.PointFillMode : I.TriangleFillMode;
  }
  /**
   * Gets the material fill mode
   */
  get fillMode() {
    return this._fillMode;
  }
  /**
   * Sets the material fill mode
   */
  set fillMode(e) {
    this._fillMode !== e && (this._fillMode = e, this.markAsDirty(I.MiscDirtyFlag));
  }
  /** @internal */
  _getDrawWrapper() {
    return this._drawWrapper;
  }
  /**
   * @internal
   */
  _setDrawWrapper(e) {
    this._drawWrapper = e;
  }
  /**
   * 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
   */
  constructor(e, t, i) {
    this.shadowDepthWrapper = null, this.allowShaderHotSwapping = !0, this.metadata = null, this.reservedDataStore = null, this.checkReadyOnEveryCall = !1, this.checkReadyOnlyOnce = !1, this.state = "", this._alpha = 1, this._backFaceCulling = !0, this._cullBackFaces = !0, this._blockDirtyMechanism = !1, this.onCompiled = null, this.onError = null, this.getRenderTargetTextures = null, this.doNotSerialize = !1, this._storeEffectOnSubMeshes = !1, this.animations = null, this.onDisposeObservable = new w(), this._onDisposeObserver = null, this._onUnBindObservable = null, this._onBindObserver = null, this._alphaMode = 2, this._needDepthPrePass = !1, this.disableDepthWrite = !1, this.disableColorWrite = !1, this.forceDepthWrite = !1, this.depthFunction = 0, this.separateCullingPass = !1, this._fogEnabled = !0, this.pointSize = 1, this.zOffset = 0, this.zOffsetUnits = 0, this.stencil = new ft(), this._useUBO = !1, this._fillMode = I.TriangleFillMode, this._cachedDepthWriteState = !1, this._cachedColorWriteState = !1, this._cachedDepthFunctionState = 0, this._indexInSceneMaterialArray = -1, this.meshMap = null, this._parentContainer = null, this._uniformBufferLayoutBuilt = !1, this._eventInfo = {}, this._callbackPluginEventGeneric = () => {
    }, this._callbackPluginEventIsReadyForSubMesh = () => {
    }, this._callbackPluginEventPrepareDefines = () => {
    }, this._callbackPluginEventPrepareDefinesBeforeAttributes = () => {
    }, this._callbackPluginEventHardBindForSubMesh = () => {
    }, this._callbackPluginEventBindForSubMesh = () => {
    }, this._callbackPluginEventHasRenderTargetTextures = () => {
    }, this._callbackPluginEventFillRenderTargetTextures = () => {
    }, this._forceAlphaTest = !1, this._transparencyMode = null, this.name = e;
    const s = t || J.LastCreatedScene;
    s && (this._scene = s, this._dirtyCallbacks = {}, 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[63] = this._markAllSubMeshesAsAllDirty.bind(this), this.id = e || k.RandomId(), this.uniqueId = this._scene.getUniqueId(), this._materialContext = this._scene.getEngine().createMaterialContext(), this._drawWrapper = new Pi(this._scene.getEngine(), !1), this._drawWrapper.materialContext = this._materialContext, this._scene.useRightHandedSystem ? this.sideOrientation = I.ClockWiseSideOrientation : this.sideOrientation = I.CounterClockWiseSideOrientation, this._uniformBuffer = new O(this._scene.getEngine(), void 0, void 0, e), this._useUBO = this.getScene().getEngine().supportsUniformBuffers, i || this._scene.addMaterial(this), this._scene.useMaterialMeshMap && (this.meshMap = {}), I.OnEventObservable.notifyObservers(this, mt.Created));
  }
  /**
   * 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(e) {
    return "Name: " + this.name;
  }
  /**
   * Gets the class name of the material
   * @returns a string with the class name of the material
   */
  getClassName() {
    return "Material";
  }
  /** @internal */
  get _isMaterial() {
    return !0;
  }
  /**
   * Specifies if updates for the material been locked
   */
  get isFrozen() {
    return this.checkReadyOnlyOnce;
  }
  /**
   * Locks updates for the material
   */
  freeze() {
    this.markDirty(), this.checkReadyOnlyOnce = !0;
  }
  /**
   * Unlocks updates for the material
   */
  unfreeze() {
    this.markDirty(), this.checkReadyOnlyOnce = !1;
  }
  /**
   * 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(e, t) {
    return !0;
  }
  /**
   * 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(e, t, i) {
    const s = t.materialDefines;
    return s ? (this._eventInfo.isReadyForSubMesh = !0, this._eventInfo.defines = s, this._callbackPluginEventIsReadyForSubMesh(this._eventInfo), this._eventInfo.isReadyForSubMesh) : !1;
  }
  /**
   * 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;
  }
  /**
   * 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(e) {
    this._transparencyMode !== e && (this._transparencyMode = e, this._forceAlphaTest = e === I.MATERIAL_ALPHATESTANDBLEND, this._markAllSubMeshesAsTexturesAndMiscDirty());
  }
  /**
   * Returns true if alpha blending should be disabled.
   */
  get _disableAlphaBlending() {
    return this._transparencyMode === I.MATERIAL_OPAQUE || this._transparencyMode === I.MATERIAL_ALPHATEST;
  }
  /**
   * Specifies whether or not this material should be rendered in alpha blend mode.
   * @returns a boolean specifying if alpha blending is needed
   */
  needAlphaBlending() {
    return this._disableAlphaBlending ? !1 : 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(e) {
    return e.visibility < 1 ? !0 : this._disableAlphaBlending ? !1 : e.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.
   */
  needAlphaTesting() {
    return !!this._forceAlphaTest;
  }
  /**
   * Specifies if material alpha testing should be turned on for the mesh
   * @param mesh defines the mesh to check
   */
  _shouldTurnAlphaTestOn(e) {
    return !this.needAlphaBlendingForMesh(e) && 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(e = !1) {
    const t = this.getScene().meshes;
    for (const i of t)
      if (i.subMeshes)
        for (const s of i.subMeshes)
          s.getMaterial() === this && s.effect && (s.effect._wasPreviouslyReady = !1, s.effect._wasPreviouslyUsingInstances = null, s.effect._forceRebindOnNextCall = e);
    e && this.markAsDirty(I.AllDirtyFlag);
  }
  /**
   * @internal
   */
  _preBind(e, t = null) {
    const i = this._scene.getEngine(), r = (t ?? this.sideOrientation) === I.ClockWiseSideOrientation;
    return i.enableEffect(e || this._getDrawWrapper()), i.setState(this.backFaceCulling, this.zOffset, !1, r, this._scene._mirroredCameraPosition ? !this.cullBackFaces : this.cullBackFaces, this.stencil, this.zOffsetUnits), r;
  }
  /**
   * 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(e, t) {
  }
  /**
   * Initializes the uniform buffer layout for the shader.
   */
  buildUniformLayout() {
    const e = this._uniformBuffer;
    this._eventInfo.ubo = e, this._callbackPluginEventGeneric(mt.PrepareUniformBuffer, this._eventInfo), e.create(), this._uniformBufferLayoutBuilt = !0;
  }
  /**
   * 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(e, t, i) {
    const s = i.effect;
    s && (this._eventInfo.subMesh = i, this._callbackPluginEventBindForSubMesh(this._eventInfo), s._forceRebindOnNextCall = !1);
  }
  /**
   * Binds the world matrix to the material
   * @param world defines the world transformation matrix
   */
  // eslint-disable-next-line @typescript-eslint/no-unused-vars
  bindOnlyWorldMatrix(e) {
  }
  /**
   * Binds the view matrix to the effect
   * @param effect defines the effect to bind the view matrix to
   */
  bindView(e) {
    this._useUBO ? this._needToBindSceneUbo = !0 : e.setMatrix("view", this.getScene().getViewMatrix());
  }
  /**
   * 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(e) {
    this._useUBO ? this._needToBindSceneUbo = !0 : (e.setMatrix("viewProjection", this.getScene().getTransformMatrix()), e.setMatrix("projection", this.getScene().getProjectionMatrix()));
  }
  /**
   * 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(e, t) {
    this._useUBO ? this._needToBindSceneUbo = !0 : this._scene.bindEyePosition(e, t);
  }
  /**
   * Processes to execute after binding the material to a mesh
   * @param mesh defines the rendered mesh
   * @param effect
   */
  _afterBind(e, t = null) {
    if (this._scene._cachedMaterial = this, this._needToBindSceneUbo && t && (this._needToBindSceneUbo = !1, Bt.BindSceneUniformBuffer(t, this.getScene().getSceneUniformBuffer()), this._scene.finalizeSceneUbo()), e ? this._scene._cachedVisibility = e.visibility : this._scene._cachedVisibility = 1, this._onBindObservable && e && this._onBindObservable.notifyObservers(e), this.disableDepthWrite) {
      const i = this._scene.getEngine();
      this._cachedDepthWriteState = i.getDepthWrite(), i.setDepthWrite(!1);
    }
    if (this.disableColorWrite) {
      const i = this._scene.getEngine();
      this._cachedColorWriteState = i.getColorWrite(), i.setColorWrite(!1);
    }
    if (this.depthFunction !== 0) {
      const i = this._scene.getEngine();
      this._cachedDepthFunctionState = i.getDepthFunction() || 0, i.setDepthFunction(this.depthFunction);
    }
  }
  /**
   * Unbinds the material from the mesh
   */
  unbind() {
    this._onUnBindObservable && this._onUnBindObservable.notifyObservers(this), this.depthFunction !== 0 && this._scene.getEngine().setDepthFunction(this._cachedDepthFunctionState), this.disableDepthWrite && this._scene.getEngine().setDepthWrite(this._cachedDepthWriteState), this.disableColorWrite && this._scene.getEngine().setColorWrite(this._cachedColorWriteState);
  }
  /**
   * Returns the animatable textures.
   * @returns - Array of animatable textures.
   */
  getAnimatables() {
    return this._eventInfo.animatables = [], this._callbackPluginEventGeneric(mt.GetAnimatables, this._eventInfo), this._eventInfo.animatables;
  }
  /**
   * Gets the active textures from the material
   * @returns an array of textures
   */
  getActiveTextures() {
    return this._eventInfo.activeTextures = [], this._callbackPluginEventGeneric(mt.GetActiveTextures, this._eventInfo), 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(e) {
    return this._eventInfo.hasTexture = !1, this._eventInfo.texture = e, this._callbackPluginEventGeneric(mt.HasTexture, this._eventInfo), 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(e) {
    return null;
  }
  /**
   * Gets the meshes bound to the material
   * @returns an array of meshes bound to the material
   */
  getBindedMeshes() {
    if (this.meshMap) {
      const e = new Array();
      for (const t in this.meshMap) {
        const i = this.meshMap[t];
        i && e.push(i);
      }
      return e;
    } else
      return this._scene.meshes.filter((t) => t.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(e, t, i, s) {
    const r = {
      clipPlane: !1,
      useInstances: !1,
      ...i
    }, n = this.getScene(), a = this.allowShaderHotSwapping;
    this.allowShaderHotSwapping = !1;
    const o = () => {
      if (!this._scene || !this._scene.getEngine())
        return;
      const h = n.clipPlane;
      if (r.clipPlane && (n.clipPlane = new $e(0, 0, 0, 1)), this._storeEffectOnSubMeshes) {
        let c = !0, u = null;
        if (e.subMeshes) {
          const d = new Ye(0, 0, 0, 0, 0, e, void 0, !1, !1);
          d.materialDefines && (d.materialDefines._renderId = -1), this.isReadyForSubMesh(e, d, r.useInstances) || (d.effect && d.effect.getCompilationError() && d.effect.allFallbacksProcessed() ? u = d.effect.getCompilationError() : (c = !1, setTimeout(o, 16)));
        }
        c && (this.allowShaderHotSwapping = a, u && s && s(u), t && t(this));
      } else
        this.isReady() ? (this.allowShaderHotSwapping = a, t && t(this)) : setTimeout(o, 16);
      r.clipPlane && (n.clipPlane = h);
    };
    o();
  }
  /**
   * 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
   */
  forceCompilationAsync(e, t) {
    return new Promise((i, s) => {
      this.forceCompilation(e, () => {
        i();
      }, t, (r) => {
        s(r);
      });
    });
  }
  /**
   * 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(e) {
    this.getScene().blockMaterialDirtyMechanism || this._blockDirtyMechanism || (I._DirtyCallbackArray.length = 0, e & I.TextureDirtyFlag && I._DirtyCallbackArray.push(I._TextureDirtyCallBack), e & I.LightDirtyFlag && I._DirtyCallbackArray.push(I._LightsDirtyCallBack), e & I.FresnelDirtyFlag && I._DirtyCallbackArray.push(I._FresnelDirtyCallBack), e & I.AttributesDirtyFlag && I._DirtyCallbackArray.push(I._AttributeDirtyCallBack), e & I.MiscDirtyFlag && I._DirtyCallbackArray.push(I._MiscDirtyCallBack), e & I.PrePassDirtyFlag && I._DirtyCallbackArray.push(I._PrePassDirtyCallBack), I._DirtyCallbackArray.length && this._markAllSubMeshesAsDirty(I._RunDirtyCallBacks), this.getScene().resetCachedMaterial());
  }
  /**
   * Resets the draw wrappers cache for all submeshes that are using this material
   */
  resetDrawCache() {
    const e = this.getScene().meshes;
    for (const t of e)
      if (t.subMeshes)
        for (const i of t.subMeshes)
          i.getMaterial() === this && i.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(e) {
    if (this.getScene().blockMaterialDirtyMechanism || this._blockDirtyMechanism)
      return;
    const t = this.getScene().meshes;
    for (const i of t)
      if (i.subMeshes) {
        for (const s of i.subMeshes)
          if (s.getMaterial(!1) === this)
            for (const r of s._drawWrappers)
              !r || !r.defines || !r.defines.markAllAsDirty || this._materialContext === r.materialContext && e(r.defines);
      }
  }
  /**
   * Indicates that the scene should check if the rendering now needs a prepass
   */
  _markScenePrePassDirty() {
    if (this.getScene().blockMaterialDirtyMechanism || this._blockDirtyMechanism)
      return;
    const e = this.getScene().enablePrePassRenderer();
    e && e.markAsDirty();
  }
  /**
   * Indicates that we need to re-calculated for all submeshes
   */
  _markAllSubMeshesAsAllDirty() {
    this._markAllSubMeshesAsDirty(I._AllDirtyCallBack);
  }
  /**
   * Indicates that image processing needs to be re-calculated for all submeshes
   */
  _markAllSubMeshesAsImageProcessingDirty() {
    this._markAllSubMeshesAsDirty(I._ImageProcessingDirtyCallBack);
  }
  /**
   * Indicates that textures need to be re-calculated for all submeshes
   */
  _markAllSubMeshesAsTexturesDirty() {
    this._markAllSubMeshesAsDirty(I._TextureDirtyCallBack);
  }
  /**
   * Indicates that fresnel needs to be re-calculated for all submeshes
   */
  _markAllSubMeshesAsFresnelDirty() {
    this._markAllSubMeshesAsDirty(I._FresnelDirtyCallBack);
  }
  /**
   * Indicates that fresnel and misc need to be re-calculated for all submeshes
   */
  _markAllSubMeshesAsFresnelAndMiscDirty() {
    this._markAllSubMeshesAsDirty(I._FresnelAndMiscDirtyCallBack);
  }
  /**
   * Indicates that lights need to be re-calculated for all submeshes
   */
  _markAllSubMeshesAsLightsDirty() {
    this._markAllSubMeshesAsDirty(I._LightsDirtyCallBack);
  }
  /**
   * Indicates that attributes need to be re-calculated for all submeshes
   */
  _markAllSubMeshesAsAttributesDirty() {
    this._markAllSubMeshesAsDirty(I._AttributeDirtyCallBack);
  }
  /**
   * Indicates that misc needs to be re-calculated for all submeshes
   */
  _markAllSubMeshesAsMiscDirty() {
    this._markAllSubMeshesAsDirty(I._MiscDirtyCallBack);
  }
  /**
   * Indicates that prepass needs to be re-calculated for all submeshes
   */
  _markAllSubMeshesAsPrePassDirty() {
    this._markAllSubMeshesAsDirty(I._MiscDirtyCallBack);
  }
  /**
   * Indicates that textures and misc need to be re-calculated for all submeshes
   */
  _markAllSubMeshesAsTexturesAndMiscDirty() {
    this._markAllSubMeshesAsDirty(I._TextureAndMiscDirtyCallBack);
  }
  _checkScenePerformancePriority() {
    if (this._scene.performancePriority !== et.BackwardCompatible) {
      this.checkReadyOnlyOnce = !0;
      const e = this._scene.onScenePerformancePriorityChangedObservable.addOnce(() => {
        this.checkReadyOnlyOnce = !1;
      });
      this.onDisposeObservable.add(() => {
        this._scene.onScenePerformancePriorityChangedObservable.remove(e);
      });
    }
  }
  /**
   * 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(e) {
    return !1;
  }
  /**
   * 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(e, t, i) {
    const s = this.getScene();
    if (s.stopAnimation(this), s.freeProcessedMaterials(), s.removeMaterial(this), this._eventInfo.forceDisposeTextures = t, this._callbackPluginEventGeneric(mt.Disposed, this._eventInfo), this._parentContainer) {
      const r = this._parentContainer.materials.indexOf(this);
      r > -1 && this._parentContainer.materials.splice(r, 1), this._parentContainer = null;
    }
    if (i !== !0)
      if (this.meshMap)
        for (const r in this.meshMap) {
          const n = this.meshMap[r];
          n && (n.material = null, this.releaseVertexArrayObject(n, e));
        }
      else {
        const r = s.meshes;
        for (const n of r)
          n.material === this && !n.sourceMesh && (n.material = null, this.releaseVertexArrayObject(n, e));
      }
    this._uniformBuffer.dispose(), e && this._drawWrapper.effect && (this._storeEffectOnSubMeshes || this._drawWrapper.effect.dispose(), this._drawWrapper.effect = null), this.metadata = null, this.onDisposeObservable.notifyObservers(this), this.onDisposeObservable.clear(), this._onBindObservable && this._onBindObservable.clear(), this._onUnBindObservable && this._onUnBindObservable.clear(), this._onEffectCreatedObservable && this._onEffectCreatedObservable.clear(), this._eventInfo && (this._eventInfo = {});
  }
  /**
   * @internal
   */
  // eslint-disable-next-line @typescript-eslint/naming-convention
  releaseVertexArrayObject(e, t) {
    if (e.geometry) {
      const i = e.geometry;
      if (this._storeEffectOnSubMeshes)
        for (const s of e.subMeshes)
          i._releaseVertexArrayObject(s.effect), t && s.effect && s.effect.dispose();
      else
        i._releaseVertexArrayObject(this._drawWrapper.effect);
    }
  }
  /**
   * Serializes this material
   * @returns the serialized material object
   */
  serialize() {
    const e = he.Serialize(this);
    return e.stencil = this.stencil.serialize(), e.uniqueId = this.uniqueId, e;
  }
  /**
   * 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(e, t, i) {
    if (!e.customType)
      e.customType = "BABYLON.StandardMaterial";
    else if (e.customType === "BABYLON.PBRMaterial" && e.overloadedAlbedo && (e.customType = "BABYLON.LegacyPBRMaterial", !BABYLON.LegacyPBRMaterial))
      return S.Error("Your scene is trying to load a legacy version of the PBRMaterial, please, include it from the materials library."), null;
    const r = k.Instantiate(e.customType).Parse(e, t, i);
    return r._loadedUniqueId = e.uniqueId, r;
  }
}
I.TriangleFillMode = 0;
I.WireFrameFillMode = 1;
I.PointFillMode = 2;
I.PointListDrawMode = 3;
I.LineListDrawMode = 4;
I.LineLoopDrawMode = 5;
I.LineStripDrawMode = 6;
I.TriangleStripDrawMode = 7;
I.TriangleFanDrawMode = 8;
I.ClockWiseSideOrientation = 0;
I.CounterClockWiseSideOrientation = 1;
I.TextureDirtyFlag = 1;
I.LightDirtyFlag = 2;
I.FresnelDirtyFlag = 4;
I.AttributesDirtyFlag = 8;
I.MiscDirtyFlag = 16;
I.PrePassDirtyFlag = 32;
I.AllDirtyFlag = 63;
I.MATERIAL_OPAQUE = 0;
I.MATERIAL_ALPHATEST = 1;
I.MATERIAL_ALPHABLEND = 2;
I.MATERIAL_ALPHATESTANDBLEND = 3;
I.MATERIAL_NORMALBLENDMETHOD_WHITEOUT = 0;
I.MATERIAL_NORMALBLENDMETHOD_RNM = 1;
I.OnEventObservable = new w();
J.OnEnginesDisposedObservable.addOnce(() => {
  I.OnEventObservable.clear();
});
I._AllDirtyCallBack = (l) => l.markAllAsDirty();
I._ImageProcessingDirtyCallBack = (l) => l.markAsImageProcessingDirty();
I._TextureDirtyCallBack = (l) => l.markAsTexturesDirty();
I._FresnelDirtyCallBack = (l) => l.markAsFresnelDirty();
I._MiscDirtyCallBack = (l) => l.markAsMiscDirty();
I._PrePassDirtyCallBack = (l) => l.markAsPrePassDirty();
I._LightsDirtyCallBack = (l) => l.markAsLightDirty();
I._AttributeDirtyCallBack = (l) => l.markAsAttributesDirty();
I._FresnelAndMiscDirtyCallBack = (l) => {
  I._FresnelDirtyCallBack(l), I._MiscDirtyCallBack(l);
};
I._TextureAndMiscDirtyCallBack = (l) => {
  I._TextureDirtyCallBack(l), I._MiscDirtyCallBack(l);
};
I._DirtyCallbackArray = [];
I._RunDirtyCallBacks = (l) => {
  for (const e of I._DirtyCallbackArray)
    e(l);
};
F([
  B()
], I.prototype, "id", void 0);
F([
  B()
], I.prototype, "uniqueId", void 0);
F([
  B()
], I.prototype, "name", void 0);
F([
  B()
], I.prototype, "metadata", void 0);
F([
  B()
], I.prototype, "checkReadyOnEveryCall", void 0);
F([
  B()
], I.prototype, "checkReadyOnlyOnce", void 0);
F([
  B()
], I.prototype, "state", void 0);
F([
  B("alpha")
], I.prototype, "_alpha", void 0);
F([
  B("backFaceCulling")
], I.prototype, "_backFaceCulling", void 0);
F([
  B("cullBackFaces")
], I.prototype, "_cullBackFaces", void 0);
F([
  B()
], I.prototype, "sideOrientation", void 0);
F([
  B("alphaMode")
], I.prototype, "_alphaMode", void 0);
F([
  B()
], I.prototype, "_needDepthPrePass", void 0);
F([
  B()
], I.prototype, "disableDepthWrite", void 0);
F([
  B()
], I.prototype, "disableColorWrite", void 0);
F([
  B()
], I.prototype, "forceDepthWrite", void 0);
F([
  B()
], I.prototype, "depthFunction", void 0);
F([
  B()
], I.prototype, "separateCullingPass", void 0);
F([
  B("fogEnabled")
], I.prototype, "_fogEnabled", void 0);
F([
  B()
], I.prototype, "pointSize", void 0);
F([
  B()
], I.prototype, "zOffset", void 0);
F([
  B()
], I.prototype, "zOffsetUnits", void 0);
F([
  B()
], I.prototype, "pointsCloud", null);
F([
  B()
], I.prototype, "fillMode", null);
F([
  B()
], I.prototype, "transparencyMode", null);
class Lt extends I {
  /**
   * 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(e) {
    this._subMaterials = e, this._hookArray(e);
  }
  /**
   * 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(e, t) {
    super(e, t, !0), this._waitingSubMaterialsUniqueIds = [], this.getScene().multiMaterials.push(this), this.subMaterials = new Array(), this._storeEffectOnSubMeshes = !0;
  }
  _hookArray(e) {
    const t = e.push;
    e.push = (...s) => {
      const r = t.apply(e, s);
      return this._markAllSubMeshesAsTexturesDirty(), r;
    };
    const i = e.splice;
    e.splice = (s, r) => {
      const n = i.apply(e, [s, r]);
      return this._markAllSubMeshesAsTexturesDirty(), n;
    };
  }
  /**
   * 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(e) {
    return e < 0 || e >= this.subMaterials.length ? this.getScene().defaultMaterial : this.subMaterials[e];
  }
  /**
   * 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((e) => e ? e.getActiveTextures() : []));
  }
  /**
   * 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(e) {
    var t;
    if (super.hasTexture(e))
      return !0;
    for (let i = 0; i < this.subMaterials.length; i++)
      if (!((t = this.subMaterials[i]) === null || t === void 0) && t.hasTexture(e))
        return !0;
    return !1;
  }
  /**
   * 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(e, t, i) {
    for (let s = 0; s < this.subMaterials.length; s++) {
      const r = this.subMaterials[s];
      if (r) {
        if (r._storeEffectOnSubMeshes) {
          if (!r.isReadyForSubMesh(e, t, i))
            return !1;
          continue;
        }
        if (!r.isReady(e))
          return !1;
      }
    }
    return !0;
  }
  /**
   * 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(e, t) {
    const i = new Lt(e, this.getScene());
    for (let s = 0; s < this.subMaterials.length; s++) {
      let r = null;
      const n = this.subMaterials[s];
      t && n ? r = n.clone(e + "-" + n.name) : r = this.subMaterials[s], i.subMaterials.push(r);
    }
    return i;
  }
  /**
   * Serializes the materials into a JSON representation.
   * @returns the JSON representation
   */
  serialize() {
    const e = {};
    e.name = this.name, e.id = this.id, e.uniqueId = this.uniqueId, re && (e.tags = re.GetTags(this)), e.materialsUniqueIds = [], e.materials = [];
    for (let t = 0; t < this.subMaterials.length; t++) {
      const i = this.subMaterials[t];
      i ? (e.materialsUniqueIds.push(i.uniqueId), e.materials.push(i.id)) : (e.materialsUniqueIds.push(null), e.materials.push(null));
    }
    return e;
  }
  /**
   * 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(e, t, i) {
    const s = this.getScene();
    if (!s)
      return;
    if (i)
      for (let n = 0; n < this.subMaterials.length; n++) {
        const a = this.subMaterials[n];
        a && a.dispose(e, t);
      }
    const r = s.multiMaterials.indexOf(this);
    r >= 0 && s.multiMaterials.splice(r, 1), super.dispose(e, t);
  }
  /**
   * 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(e, t) {
    const i = new Lt(e.name, t);
    return i.id = e.id, i._loadedUniqueId = e.uniqueId, re && re.AddTagsTo(i, e.tags), e.materialsUniqueIds ? i._waitingSubMaterialsUniqueIds = e.materialsUniqueIds : e.materials.forEach((s) => i.subMaterials.push(t.getLastMaterialById(s))), i;
  }
}
dt("BABYLON.MultiMaterial", Lt);
class Ar {
  /**
   * 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(e, t) {
    this.distanceOrScreenCoverage = e, this.mesh = t;
  }
}
class xr {
  constructor() {
    this.visibleInstances = {}, this.batchCache = new ts(), this.batchCacheReplacementModeInFrozenMode = new ts(), this.instancesBufferSize = 32 * 16 * 4;
  }
}
class ts {
  constructor() {
    this.mustReturn = !1, this.visibleInstances = new Array(), this.renderSelf = new Array(), this.hardwareInstancedRendering = new Array();
  }
}
class Er {
  constructor() {
    this.instancesCount = 0, this.matrixBuffer = null, this.previousMatrixBuffer = null, this.matrixBufferSize = 32 * 16, this.matrixData = null, this.boundingVectors = [], this.worldMatrices = null;
  }
}
class vr {
  constructor() {
    this._areNormalsFrozen = !1, this._source = null, this.meshMap = null, this._preActivateId = -1, this._LODLevels = new Array(), this._useLODScreenCoverage = !1, this._effectiveMaterial = null, this._forcedInstanceCount = 0, this._overrideRenderingFillMode = null;
  }
}
class U extends Ge {
  /**
   * Gets the default side orientation.
   * @param orientation the orientation to value to attempt to get
   * @returns the default orientation
   * @internal
   */
  static _GetDefaultSideOrientation(e) {
    return e || U.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(e) {
    this._internalMeshDataInfo._useLODScreenCoverage = e, this._sortLODLevels();
  }
  get computeBonesUsingShaders() {
    return this._internalAbstractMeshDataInfo._computeBonesUsingShaders;
  }
  set computeBonesUsingShaders(e) {
    this._internalAbstractMeshDataInfo._computeBonesUsingShaders !== e && (e && this._internalMeshDataInfo._sourcePositions && (this.setVerticesData(_.PositionKind, this._internalMeshDataInfo._sourcePositions, !0), this._internalMeshDataInfo._sourceNormals && this.setVerticesData(_.NormalKind, this._internalMeshDataInfo._sourceNormals, !0), this._internalMeshDataInfo._sourcePositions = null, this._internalMeshDataInfo._sourceNormals = null), this._internalAbstractMeshDataInfo._computeBonesUsingShaders = e, this._markSubMeshesAsAttributesDirty());
  }
  /**
   * An event triggered before rendering the mesh
   */
  get onBeforeRenderObservable() {
    return this._internalMeshDataInfo._onBeforeRenderObservable || (this._internalMeshDataInfo._onBeforeRenderObservable = new w()), this._internalMeshDataInfo._onBeforeRenderObservable;
  }
  /**
   * An event triggered before binding the mesh
   */
  get onBeforeBindObservable() {
    return this._internalMeshDataInfo._onBeforeBindObservable || (this._internalMeshDataInfo._onBeforeBindObservable = new w()), this._internalMeshDataInfo._onBeforeBindObservable;
  }
  /**
   * An event triggered after rendering the mesh
   */
  get onAfterRenderObservable() {
    return this._internalMeshDataInfo._onAfterRenderObservable || (this._internalMeshDataInfo._onAfterRenderObservable = new w()), this._internalMeshDataInfo._onAfterRenderObservable;
  }
  /**
   * An event triggeredbetween rendering pass when using separateCullingPass = true
   */
  get onBetweenPassObservable() {
    return this._internalMeshDataInfo._onBetweenPassObservable || (this._internalMeshDataInfo._onBetweenPassObservable = new w()), this._internalMeshDataInfo._onBetweenPassObservable;
  }
  /**
   * An event triggered before drawing the mesh
   */
  get onBeforeDrawObservable() {
    return this._internalMeshDataInfo._onBeforeDrawObservable || (this._internalMeshDataInfo._onBeforeDrawObservable = new w()), this._internalMeshDataInfo._onBeforeDrawObservable;
  }
  /**
   * Sets a callback to call before drawing the mesh. It is recommended to use onBeforeDrawObservable instead
   */
  set onBeforeDraw(e) {
    this._onBeforeDrawObserver && this.onBeforeDrawObservable.remove(this._onBeforeDrawObserver), this._onBeforeDrawObserver = this.onBeforeDrawObservable.add(e);
  }
  get hasInstances() {
    return this.instances.length > 0;
  }
  get hasThinInstances() {
    var e;
    return ((e = this._thinInstanceDataStorage.instancesCount) !== null && e !== void 0 ? e : 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(e) {
    this._internalMeshDataInfo._forcedInstanceCount = e;
  }
  /**
   * Use this property to override the Material's fillMode value
   */
  get overrideRenderingFillMode() {
    return this._internalMeshDataInfo._overrideRenderingFillMode;
  }
  set overrideRenderingFillMode(e) {
    this._internalMeshDataInfo._overrideRenderingFillMode = e;
  }
  /**
   * 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(e) {
    this._unIndexed !== e && (this._unIndexed = e, this._markSubMeshesAsAttributesDirty());
  }
  /** Gets the array buffer used to store the instanced buffer used for instances' world matrices */
  get worldMatrixInstancedBuffer() {
    return this._instanceDataStorage.instancesData;
  }
  /** Gets the array buffer used to store the instanced buffer used for instances' previous world matrices */
  get previousWorldMatrixInstancedBuffer() {
    return this._instanceDataStorage.instancesPreviousData;
  }
  /** 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(e) {
    this._instanceDataStorage.manualUpdate = e;
  }
  /** 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(e) {
    this._instanceDataStorage.previousManualUpdate = e;
  }
  /** 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(e) {
    this._instanceDataStorage.forceMatrixUpdates = e;
  }
  /**
   * @constructor
   * @param name The value used by scene.getMeshByName() to do a lookup.
   * @param scene The scene to add this mesh to.
   * @param parent The parent of this mesh, if it has one
   * @param source An optional Mesh from which geometry is shared, cloned.
   * @param doNotCloneChildren When cloning, skip cloning child meshes of source, default False.
   *                  When false, achieved by calling a clone(), also passing False.
   *                  This will make creation of children, recursive.
   * @param clonePhysicsImpostor When cloning, include cloning mesh physics impostor, default True.
   */
  constructor(e, t = null, i = null, s = null, r, n = !0) {
    if (super(e, t), this._internalMeshDataInfo = new vr(), this.delayLoadState = 0, this.instances = new Array(), this._creationDataStorage = null, this._geometry = null, this._instanceDataStorage = new xr(), this._thinInstanceDataStorage = new Er(), this._shouldGenerateFlatShading = !1, this._originalBuilderSideOrientation = U.DEFAULTSIDE, this.overrideMaterialSideOrientation = null, this.ignoreCameraMaxZ = !1, t = this.getScene(), this._onBeforeDraw = (a, o, h) => {
      a && h && (this._uniformBuffer ? this.transferToEffect(o) : h.bindOnlyWorldMatrix(o));
    }, s) {
      if (s._geometry && s._geometry.applyToMesh(this), Ci.DeepCopy(s, 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"
      ], ["_poseMatrix"]), this._internalMeshDataInfo._source = s, t.useClonedMeshMap && (s._internalMeshDataInfo.meshMap || (s._internalMeshDataInfo.meshMap = {}), s._internalMeshDataInfo.meshMap[this.uniqueId] = this), this._originalBuilderSideOrientation = s._originalBuilderSideOrientation, this._creationDataStorage = s._creationDataStorage, s._ranges) {
        const a = s._ranges;
        for (const o in a)
          Object.prototype.hasOwnProperty.call(a, o) && a[o] && this.createAnimationRange(o, a[o].from, a[o].to);
      }
      if (s.metadata && s.metadata.clone ? this.metadata = s.metadata.clone() : this.metadata = s.metadata, this._internalMetadata = s._internalMetadata, re && re.HasTags(s) && re.AddTagsTo(this, re.GetTags(s, !0)), this.setEnabled(s.isEnabled(!1)), this.parent = s.parent, this.setPivotMatrix(s.getPivotMatrix()), this.id = e + "." + s.id, this.material = s.material, !r) {
        const a = s.getDescendants(!0);
        for (let o = 0; o < a.length; o++) {
          const h = a[o];
          h.clone && h.clone(e + "." + h.name, this);
        }
      }
      if (s.morphTargetManager && (this.morphTargetManager = s.morphTargetManager), t.getPhysicsEngine) {
        const a = t.getPhysicsEngine();
        if (n && a)
          if (a.getPluginVersion() === 1) {
            const o = a.getImpostorForPhysicsObject(s);
            o && (this.physicsImpostor = o.clone(this));
          } else
            a.getPluginVersion() === 2 && s.physicsBody && s.physicsBody.clone(this);
      }
      for (let a = 0; a < t.particleSystems.length; a++) {
        const o = t.particleSystems[a];
        o.emitter === s && o.clone(o.name, this);
      }
      this.skeleton = s.skeleton, this.refreshBoundingInfo(!0, !0), this.computeWorldMatrix(!0);
    }
    i !== null && (this.parent = i), this._instanceDataStorage.hardwareInstancedRendering = this.getEngine().getCaps().instancedArrays, this._internalMeshDataInfo._onMeshReadyObserverAdded = (a) => {
      a.unregisterOnNextCall = !0, this.isReady(!0) ? this.onMeshReadyObservable.notifyObservers(this) : this._internalMeshDataInfo._checkReadinessObserver || (this._internalMeshDataInfo._checkReadinessObserver = this._scene.onBeforeRenderObservable.add(() => {
        this.isReady(!0) && (this._scene.onBeforeRenderObservable.remove(this._internalMeshDataInfo._checkReadinessObserver), this._internalMeshDataInfo._checkReadinessObserver = null, this.onMeshReadyObservable.notifyObservers(this));
      }));
    }, this.onMeshReadyObservable = new w(this._internalMeshDataInfo._onMeshReadyObserverAdded), s && s.onClonedObservable.notifyObservers(this);
  }
  instantiateHierarchy(e = null, t, i) {
    const s = this.getTotalVertices() === 0 || t && t.doNotInstantiate && (t.doNotInstantiate === !0 || t.doNotInstantiate(this)) ? this.clone("Clone of " + (this.name || this.id), e || this.parent, !0) : this.createInstance("instance of " + (this.name || this.id));
    s.parent = e || this.parent, s.position = this.position.clone(), s.scaling = this.scaling.clone(), this.rotationQuaternion ? s.rotationQuaternion = this.rotationQuaternion.clone() : s.rotation = this.rotation.clone(), i && i(this, s);
    for (const r of this.getChildTransformNodes(!0))
      r.getClassName() === "InstancedMesh" && s.getClassName() === "Mesh" && r.sourceMesh === this ? r.instantiateHierarchy(s, {
        doNotInstantiate: t && t.doNotInstantiate || !1,
        newSourcedMesh: s
      }, i) : r.instantiateHierarchy(s, t, i);
    return s;
  }
  /**
   * Gets the class name
   * @returns the string "Mesh".
   */
  getClassName() {
    return "Mesh";
  }
  /** @internal */
  get _isMesh() {
    return !0;
  }
  /**
   * 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(e) {
    let t = super.toString(e);
    if (t += ", n vertices: " + this.getTotalVertices(), t += ", parent: " + (this._waitingParentId ? this._waitingParentId : this.parent ? this.parent.name : "NONE"), this.animations)
      for (let i = 0; i < this.animations.length; i++)
        t += ", animation[0]: " + this.animations[i].toString(e);
    if (e)
      if (this._geometry) {
        const i = this.getIndices(), s = this.getVerticesData(_.PositionKind);
        s && i && (t += ", flat shading: " + (s.length / 3 === i.length ? "YES" : "NO"));
      } else
        t += ", flat shading: UNKNOWN";
    return t;
  }
  /** @internal */
  _unBindEffect() {
    super._unBindEffect();
    for (const e of this.instances)
      e._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 e = this._internalMeshDataInfo._useLODScreenCoverage ? -1 : 1;
    this._internalMeshDataInfo._LODLevels.sort((t, i) => t.distanceOrScreenCoverage < i.distanceOrScreenCoverage ? e : t.distanceOrScreenCoverage > i.distanceOrScreenCoverage ? -e : 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(e, t) {
    if (t && t._masterMesh)
      return S.Warn("You cannot use a mesh as LOD level twice"), this;
    const i = new Ar(e, t);
    return this._internalMeshDataInfo._LODLevels.push(i), t && (t._masterMesh = this), this._sortLODLevels(), 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(e) {
    const t = this._internalMeshDataInfo;
    for (let i = 0; i < t._LODLevels.length; i++) {
      const s = t._LODLevels[i];
      if (s.distanceOrScreenCoverage === e)
        return s.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(e) {
    const t = this._internalMeshDataInfo;
    for (let i = 0; i < t._LODLevels.length; i++)
      t._LODLevels[i].mesh === e && (t._LODLevels.splice(i, 1), e && (e._masterMesh = null));
    return this._sortLODLevels(), 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(e, t) {
    const i = this._internalMeshDataInfo;
    if (!i._LODLevels || i._LODLevels.length === 0)
      return this;
    const s = t || this.getBoundingInfo().boundingSphere, r = e.mode === Z.ORTHOGRAPHIC_CAMERA ? e.minZ : s.centerWorld.subtract(e.globalPosition).length();
    let n = r, a = 1;
    if (i._useLODScreenCoverage) {
      const o = e.screenArea;
      let h = s.radiusWorld * e.minZ / r;
      h = h * h * Math.PI, n = h / o, a = -1;
    }
    if (a * i._LODLevels[i._LODLevels.length - 1].distanceOrScreenCoverage > a * n)
      return this.onLODLevelSelection && this.onLODLevelSelection(n, this, this), this;
    for (let o = 0; o < i._LODLevels.length; o++) {
      const h = i._LODLevels[o];
      if (a * h.distanceOrScreenCoverage < a * n) {
        if (h.mesh) {
          if (h.mesh.delayLoadState === 4)
            return h.mesh._checkDelayState(), this;
          if (h.mesh.delayLoadState === 2)
            return this;
          h.mesh._preActivate(), h.mesh._updateSubMeshesBoundingInfo(this.worldMatrixFromCache);
        }
        return this.onLODLevelSelection && this.onLODLevelSelection(n, this, h.mesh), h.mesh;
      }
    }
    return this.onLODLevelSelection && this.onLODLevelSelection(n, this, this), 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() {
    return this._geometry === null || this._geometry === void 0 ? 0 : 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(e, t, i, s) {
    var r, n;
    if (!this._geometry)
      return null;
    let a = s || (n = (r = this._userInstancedBuffersStorage) === null || r === void 0 ? void 0 : r.vertexBuffers[e]) === null || n === void 0 ? void 0 : n.getFloatData(
      this.instances.length + 1,
      // +1 because the master mesh is not included in the instances array
      i || t && this._geometry.meshes.length !== 1
    );
    return a || (a = this._geometry.getVerticesData(e, t, i)), a;
  }
  /**
   * Returns the mesh VertexBuffer object from the requested `kind`
   * @param kind defines which buffer to read from (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 FloatArray or null if the mesh has no vertex buffer for this kind.
   */
  getVertexBuffer(e, t) {
    var i, s;
    return this._geometry ? (s = t || (i = this._userInstancedBuffersStorage) === null || i === void 0 ? void 0 : i.vertexBuffers[e]) !== null && s !== void 0 ? s : this._geometry.getVertexBuffer(e) : null;
  }
  /**
   * 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(e, t) {
    var i;
    return this._geometry ? !t && ((i = this._userInstancedBuffersStorage) === null || i === void 0 ? void 0 : i.vertexBuffers[e]) !== void 0 || this._geometry.isVerticesDataPresent(e) : this._delayInfo ? this._delayInfo.indexOf(e) !== -1 : !1;
  }
  /**
   * 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(e, t) {
    var i;
    if (!this._geometry)
      return this._delayInfo ? this._delayInfo.indexOf(e) !== -1 : !1;
    if (!t) {
      const s = (i = this._userInstancedBuffersStorage) === null || i === void 0 ? void 0 : i.vertexBuffers[e];
      if (s)
        return s.isUpdatable();
    }
    return this._geometry.isVertexBufferUpdatable(e);
  }
  /**
   * 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(e) {
    if (!this._geometry) {
      const i = new Array();
      return this._delayInfo && this._delayInfo.forEach(function(s) {
        i.push(s);
      }), i;
    }
    const t = this._geometry.getVerticesDataKinds();
    if (!e && this._userInstancedBuffersStorage)
      for (const i in this._userInstancedBuffersStorage.vertexBuffers)
        t.indexOf(i) === -1 && t.push(i);
    return t;
  }
  /**
   * Returns a positive integer : the total number of indices in this mesh geometry.
   * @returns the numner of indices or zero if the mesh has no geometry.
   */
  getTotalIndices() {
    return this._geometry ? this._geometry.getTotalIndices() : 0;
  }
  /**
   * 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(e, t) {
    return this._geometry ? this._geometry.getIndices(e, t) : [];
  }
  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(e = !1, t = !1) {
    var i, s, r, n, a, o;
    if (this.delayLoadState === 2 || !super.isReady(e))
      return !1;
    if (!this.subMeshes || this.subMeshes.length === 0 || !e)
      return !0;
    const h = this.getEngine(), c = this.getScene(), u = t || h.getCaps().instancedArrays && (this.instances.length > 0 || this.hasThinInstances);
    this.computeWorldMatrix();
    const d = this.material || c.defaultMaterial;
    if (d) {
      if (d._storeEffectOnSubMeshes)
        for (const f of this.subMeshes) {
          const m = f.getMaterial();
          if (m) {
            if (m._storeEffectOnSubMeshes) {
              if (!m.isReadyForSubMesh(this, f, u))
                return !1;
            } else if (!m.isReady(this, u))
              return !1;
          }
        }
      else if (!d.isReady(this, u))
        return !1;
    }
    const g = h.currentRenderPassId;
    for (const f of this.lightSources) {
      const m = f.getShadowGenerators();
      if (!m)
        continue;
      const b = m.values();
      for (let T = b.next(); T.done !== !0; T = b.next()) {
        const M = T.value;
        if (M && (!(!((i = M.getShadowMap()) === null || i === void 0) && i.renderList) || !((s = M.getShadowMap()) === null || s === void 0) && s.renderList && ((n = (r = M.getShadowMap()) === null || r === void 0 ? void 0 : r.renderList) === null || n === void 0 ? void 0 : n.indexOf(this)) !== -1)) {
          M.getShadowMap() && (h.currentRenderPassId = M.getShadowMap().renderPassId);
          for (const v of this.subMeshes)
            if (!M.isReady(v, u, (o = (a = v.getMaterial()) === null || a === void 0 ? void 0 : a.needAlphaBlendingForMesh(this)) !== null && o !== void 0 ? o : !1))
              return h.currentRenderPassId = g, !1;
          h.currentRenderPassId = g;
        }
      }
    }
    for (const f of this._internalMeshDataInfo._LODLevels)
      if (f.mesh && !f.mesh.isReady(u))
        return !1;
    return !0;
  }
  /**
   * 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() {
    return this._internalMeshDataInfo._areNormalsFrozen = !0, 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() {
    return this._internalMeshDataInfo._areNormalsFrozen = !1, this;
  }
  /**
   * Sets a value overriding the instance count. Only applicable when custom instanced InterleavedVertexBuffer are used rather than InstancedMeshs
   */
  set overridenInstanceCount(e) {
    this._instanceDataStorage.overridenInstanceCount = e;
  }
  // Methods
  /** @internal */
  _preActivate() {
    const e = this._internalMeshDataInfo, t = this.getScene().getRenderId();
    return e._preActivateId === t ? this : (e._preActivateId = t, this._instanceDataStorage.visibleInstances = null, this);
  }
  /**
   * @internal
   */
  _preActivateForIntermediateRendering(e) {
    return this._instanceDataStorage.visibleInstances && (this._instanceDataStorage.visibleInstances.intermediateDefaultRenderId = e), this;
  }
  /**
   * @internal
   */
  _registerInstanceForRenderId(e, t) {
    return this._instanceDataStorage.visibleInstances || (this._instanceDataStorage.visibleInstances = {
      defaultRenderId: t,
      selfDefaultRenderId: this._renderId
    }), this._instanceDataStorage.visibleInstances[t] || (this._instanceDataStorage.previousRenderId !== void 0 && this._instanceDataStorage.isFrozen && (this._instanceDataStorage.visibleInstances[this._instanceDataStorage.previousRenderId] = null), this._instanceDataStorage.previousRenderId = t, this._instanceDataStorage.visibleInstances[t] = new Array()), this._instanceDataStorage.visibleInstances[t].push(e), this;
  }
  _afterComputeWorldMatrix() {
    super._afterComputeWorldMatrix(), this.hasThinInstances && (this.doNotSyncBoundingInfo || this.thinInstanceRefreshBoundingInfo(!1));
  }
  /** @internal */
  _postActivate() {
    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 applySkeleton defines whether to apply the skeleton before computing the bounding info
   * @param applyMorph  defines whether to apply the morph target before computing the bounding info
   * @returns the current mesh
   */
  refreshBoundingInfo(e = !1, t = !1) {
    if (this.hasBoundingInfo && this.getBoundingInfo().isLocked)
      return this;
    const i = this.geometry ? this.geometry.boundingBias : null;
    return this._refreshBoundingInfo(this._getPositionData(e, t), i), this;
  }
  /**
   * @internal
   */
  _createGlobalSubMesh(e) {
    const t = this.getTotalVertices();
    if (!t || !this.getIndices())
      return null;
    if (this.subMeshes && this.subMeshes.length > 0) {
      const i = this.getIndices();
      if (!i)
        return null;
      const s = i.length;
      let r = !1;
      if (e)
        r = !0;
      else
        for (const n of this.subMeshes) {
          if (n.indexStart + n.indexCount > s) {
            r = !0;
            break;
          }
          if (n.verticesStart + n.verticesCount > t) {
            r = !0;
            break;
          }
        }
      if (!r)
        return this.subMeshes[0];
    }
    return this.releaseSubMeshes(), new Ye(0, 0, t, 0, this.getTotalIndices(), this);
  }
  /**
   * This function will subdivide the mesh into multiple submeshes
   * @param count defines the expected number of submeshes
   */
  subdivide(e) {
    if (e < 1)
      return;
    const t = this.getTotalIndices();
    let i = t / e | 0, s = 0;
    for (; i % 3 !== 0; )
      i++;
    this.releaseSubMeshes();
    for (let r = 0; r < e && !(s >= t); r++)
      Ye.CreateFromIndices(0, s, r === e - 1 ? t - s : i, this), s += i;
    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(e, t, i = !1, s) {
    if (this._geometry)
      this._geometry.setVerticesData(e, t, i, s);
    else {
      const r = new q();
      r.set(t, e);
      const n = this.getScene();
      new Ve(Ve.RandomId(), n, r, i, this);
    }
    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(e) {
    this._geometry && this._geometry.removeVerticesData(e);
  }
  /**
   * 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(e, t = !0) {
    const i = this.getVertexBuffer(e);
    !i || i.isUpdatable() === t || this.setVerticesData(e, this.getVerticesData(e), t);
  }
  /**
   * 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(e, t = !0) {
    return this._geometry || (this._geometry = Ve.CreateGeometryForMesh(this)), this._geometry.setVerticesBuffer(e, null, t), 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(e, t, i, s) {
    return this._geometry ? (s ? (this.makeGeometryUnique(), this.updateVerticesData(e, t, i, !1)) : this._geometry.updateVerticesData(e, t, i), this) : 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(e, t = !0) {
    const i = this.getVerticesData(_.PositionKind);
    if (!i)
      return this;
    if (e(i), this.updateVerticesData(_.PositionKind, i, !1, !1), t) {
      const s = this.getIndices(), r = this.getVerticesData(_.NormalKind);
      if (!r)
        return this;
      q.ComputeNormals(i, s, r), this.updateVerticesData(_.NormalKind, r, !1, !1);
    }
    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 e = this._geometry, t = this._geometry.copy(Ve.RandomId());
    return e.releaseForMesh(this, !0), t.applyToMesh(this), this;
  }
  /**
   * 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)
   * @returns the current mesh
   */
  setIndices(e, t = null, i = !1) {
    if (this._geometry)
      this._geometry.setIndices(e, t, i);
    else {
      const s = new q();
      s.indices = e;
      const r = this.getScene();
      new Ve(Ve.RandomId(), r, s, i, this);
    }
    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(e, t, i = !1) {
    return this._geometry ? (this._geometry.updateIndices(e, t, i), this) : this;
  }
  /**
   * Invert the geometry to move from a right handed system to a left handed one.
   * @returns the current mesh
   */
  toLeftHanded() {
    return this._geometry ? (this._geometry.toLeftHanded(), this) : this;
  }
  /**
   * @internal
   */
  _bind(e, t, i, s = !0) {
    if (!this._geometry)
      return this;
    const r = this.getScene().getEngine();
    this.morphTargetManager && this.morphTargetManager.isUsingTextureForTargets && this.morphTargetManager._bind(t);
    let n;
    if (this._unIndexed)
      n = null;
    else
      switch (this._getRenderingFillMode(i)) {
        case I.PointFillMode:
          n = null;
          break;
        case I.WireFrameFillMode:
          n = e._getLinesIndexBuffer(this.getIndices(), r);
          break;
        default:
        case I.TriangleFillMode:
          n = this._geometry.getIndexBuffer();
          break;
      }
    return !s || !this._userInstancedBuffersStorage || this.hasThinInstances ? this._geometry._bind(t, n) : this._geometry._bind(t, n, this._userInstancedBuffersStorage.vertexBuffers, this._userInstancedBuffersStorage.vertexArrayObjects), this;
  }
  /**
   * @internal
   */
  _draw(e, t, i) {
    if (!this._geometry || !this._geometry.getVertexBuffers() || !this._unIndexed && !this._geometry.getIndexBuffer())
      return this;
    this._internalMeshDataInfo._onBeforeDrawObservable && this._internalMeshDataInfo._onBeforeDrawObservable.notifyObservers(this);
    const r = this.getScene().getEngine();
    return this._unIndexed || t == I.PointFillMode ? r.drawArraysType(t, e.verticesStart, e.verticesCount, this.forcedInstanceCount || i) : t == I.WireFrameFillMode ? r.drawElementsType(t, 0, e._linesIndexCount, this.forcedInstanceCount || i) : r.drawElementsType(t, e.indexStart, e.indexCount, this.forcedInstanceCount || i), 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(e) {
    return this.onBeforeRenderObservable.add(e), this;
  }
  /**
   * Disposes a previously registered javascript function called before the rendering
   * @param func defines the function to remove
   * @returns the current mesh
   */
  unregisterBeforeRender(e) {
    return this.onBeforeRenderObservable.removeCallback(e), 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(e) {
    return this.onAfterRenderObservable.add(e), this;
  }
  /**
   * Disposes a previously registered javascript function called after the rendering.
   * @param func defines the function to remove
   * @returns the current mesh
   */
  unregisterAfterRender(e) {
    return this.onAfterRenderObservable.removeCallback(e), this;
  }
  /**
   * @internal
   */
  _getInstancesRenderList(e, t = !1) {
    if (this._instanceDataStorage.isFrozen) {
      if (t)
        return this._instanceDataStorage.batchCacheReplacementModeInFrozenMode.hardwareInstancedRendering[e] = !1, this._instanceDataStorage.batchCacheReplacementModeInFrozenMode.renderSelf[e] = !0, this._instanceDataStorage.batchCacheReplacementModeInFrozenMode;
      if (this._instanceDataStorage.previousBatch)
        return this._instanceDataStorage.previousBatch;
    }
    const i = this.getScene(), s = i._isInIntermediateRendering(), r = s ? this._internalAbstractMeshDataInfo._onlyForInstancesIntermediate : this._internalAbstractMeshDataInfo._onlyForInstances, n = this._instanceDataStorage.batchCache;
    if (n.mustReturn = !1, n.renderSelf[e] = t || !r && this.isEnabled() && this.isVisible, n.visibleInstances[e] = null, this._instanceDataStorage.visibleInstances && !t) {
      const a = this._instanceDataStorage.visibleInstances, o = i.getRenderId(), h = s ? a.intermediateDefaultRenderId : a.defaultRenderId;
      n.visibleInstances[e] = a[o], !n.visibleInstances[e] && h && (n.visibleInstances[e] = a[h]);
    }
    return n.hardwareInstancedRendering[e] = !t && this._instanceDataStorage.hardwareInstancedRendering && n.visibleInstances[e] !== null && n.visibleInstances[e] !== void 0, this._instanceDataStorage.previousBatch = n, n;
  }
  /**
   * @internal
   */
  _renderWithInstances(e, t, i, s, r) {
    var n;
    const a = i.visibleInstances[e._id], o = a ? a.length : 0, h = this._instanceDataStorage, c = h.instancesBufferSize;
    let u = h.instancesBuffer, d = h.instancesPreviousBuffer;
    const f = (o + 1) * 16 * 4;
    for (; h.instancesBufferSize < f; )
      h.instancesBufferSize *= 2;
    (!h.instancesData || c != h.instancesBufferSize) && (h.instancesData = new Float32Array(h.instancesBufferSize / 4)), (this._scene.needsPreviousWorldMatrices && !h.instancesPreviousData || c != h.instancesBufferSize) && (h.instancesPreviousData = new Float32Array(h.instancesBufferSize / 4));
    let m = 0, b = 0;
    const T = i.renderSelf[e._id], M = !u || c !== h.instancesBufferSize || this._scene.needsPreviousWorldMatrices && !h.instancesPreviousBuffer;
    if (!this._instanceDataStorage.manualUpdate && (!h.isFrozen || M)) {
      const v = this.getWorldMatrix();
      if (T && (this._scene.needsPreviousWorldMatrices && (h.masterMeshPreviousWorldMatrix ? (h.masterMeshPreviousWorldMatrix.copyToArray(h.instancesPreviousData, m), h.masterMeshPreviousWorldMatrix.copyFrom(v)) : (h.masterMeshPreviousWorldMatrix = v.clone(), h.masterMeshPreviousWorldMatrix.copyToArray(h.instancesPreviousData, m))), v.copyToArray(h.instancesData, m), m += 16, b++), a) {
        if (U.INSTANCEDMESH_SORT_TRANSPARENT && this._scene.activeCamera && (!((n = e.getMaterial()) === null || n === void 0) && n.needAlphaBlendingForMesh(e.getRenderingMesh()))) {
          const A = this._scene.activeCamera.globalPosition;
          for (let E = 0; E < a.length; E++) {
            const y = a[E];
            y._distanceToCamera = p.Distance(y.getBoundingInfo().boundingSphere.centerWorld, A);
          }
          a.sort((E, y) => E._distanceToCamera > y._distanceToCamera ? -1 : E._distanceToCamera < y._distanceToCamera ? 1 : 0);
        }
        for (let A = 0; A < a.length; A++) {
          const E = a[A], y = E.getWorldMatrix();
          y.copyToArray(h.instancesData, m), this._scene.needsPreviousWorldMatrices && (E._previousWorldMatrix ? (E._previousWorldMatrix.copyToArray(h.instancesPreviousData, m), E._previousWorldMatrix.copyFrom(y)) : (E._previousWorldMatrix = y.clone(), E._previousWorldMatrix.copyToArray(h.instancesPreviousData, m))), m += 16, b++;
        }
      }
    } else
      b = (T ? 1 : 0) + o;
    return M ? (u && u.dispose(), d && d.dispose(), u = new ri(r, h.instancesData, !0, 16, !1, !0), h.instancesBuffer = u, this._userInstancedBuffersStorage || (this._userInstancedBuffersStorage = {
      data: {},
      vertexBuffers: {},
      strides: {},
      sizes: {},
      vertexArrayObjects: this.getEngine().getCaps().vertexArrayObject ? {} : void 0
    }), this._userInstancedBuffersStorage.vertexBuffers.world0 = u.createVertexBuffer("world0", 0, 4), this._userInstancedBuffersStorage.vertexBuffers.world1 = u.createVertexBuffer("world1", 4, 4), this._userInstancedBuffersStorage.vertexBuffers.world2 = u.createVertexBuffer("world2", 8, 4), this._userInstancedBuffersStorage.vertexBuffers.world3 = u.createVertexBuffer("world3", 12, 4), this._scene.needsPreviousWorldMatrices && (d = new ri(r, h.instancesPreviousData, !0, 16, !1, !0), h.instancesPreviousBuffer = d, this._userInstancedBuffersStorage.vertexBuffers.previousWorld0 = d.createVertexBuffer("previousWorld0", 0, 4), this._userInstancedBuffersStorage.vertexBuffers.previousWorld1 = d.createVertexBuffer("previousWorld1", 4, 4), this._userInstancedBuffersStorage.vertexBuffers.previousWorld2 = d.createVertexBuffer("previousWorld2", 8, 4), this._userInstancedBuffersStorage.vertexBuffers.previousWorld3 = d.createVertexBuffer("previousWorld3", 12, 4)), this._invalidateInstanceVertexArrayObject()) : (!this._instanceDataStorage.isFrozen || this._instanceDataStorage.forceMatrixUpdates) && (u.updateDirectly(h.instancesData, 0, b), this._scene.needsPreviousWorldMatrices && (!this._instanceDataStorage.manualUpdate || this._instanceDataStorage.previousManualUpdate) && d.updateDirectly(h.instancesPreviousData, 0, b)), this._processInstancedBuffers(a, T), this.getScene()._activeIndices.addCount(e.indexCount * b, !1), r._currentDrawContext && (r._currentDrawContext.useInstancing = !0), this._bind(e, s, t), this._draw(e, t, b), this._scene.needsPreviousWorldMatrices && !M && this._instanceDataStorage.manualUpdate && (!this._instanceDataStorage.isFrozen || this._instanceDataStorage.forceMatrixUpdates) && !this._instanceDataStorage.previousManualUpdate && d.updateDirectly(h.instancesData, 0, b), r.unbindInstanceAttributes(), this;
  }
  /**
   * @internal
   */
  _renderWithThinInstances(e, t, i, s) {
    var r, n;
    const a = (n = (r = this._thinInstanceDataStorage) === null || r === void 0 ? void 0 : r.instancesCount) !== null && n !== void 0 ? n : 0;
    this.getScene()._activeIndices.addCount(e.indexCount * a, !1), s._currentDrawContext && (s._currentDrawContext.useInstancing = !0), this._bind(e, i, t), this._draw(e, t, a), this._scene.needsPreviousWorldMatrices && !this._thinInstanceDataStorage.previousMatrixData && this._thinInstanceDataStorage.matrixData && (this._thinInstanceDataStorage.previousMatrixBuffer ? this._thinInstanceDataStorage.previousMatrixBuffer.updateDirectly(this._thinInstanceDataStorage.matrixData, 0, a) : this._thinInstanceDataStorage.previousMatrixBuffer = this._thinInstanceCreateMatrixBuffer("previousWorld", this._thinInstanceDataStorage.matrixData, !1)), s.unbindInstanceAttributes();
  }
  /**
   * @internal
   */
  // eslint-disable-next-line @typescript-eslint/no-unused-vars
  _processInstancedBuffers(e, t) {
  }
  /**
   * @internal
   */
  _processRendering(e, t, i, s, r, n, a, o) {
    const h = this.getScene(), c = h.getEngine();
    if (s = this._getRenderingFillMode(s), n && t.getRenderingMesh().hasThinInstances)
      return this._renderWithThinInstances(t, s, i, c), this;
    if (n)
      this._renderWithInstances(t, s, r, i, c);
    else {
      c._currentDrawContext && (c._currentDrawContext.useInstancing = !1);
      let u = 0;
      r.renderSelf[t._id] && (a && a(!1, e.getWorldMatrix(), o), u++, this._draw(t, s, this._instanceDataStorage.overridenInstanceCount));
      const d = r.visibleInstances[t._id];
      if (d) {
        const g = d.length;
        u += g;
        for (let f = 0; f < g; f++) {
          const b = d[f].getWorldMatrix();
          a && a(!0, b, o), this._draw(t, s);
        }
      }
      h._activeIndices.addCount(t.indexCount * u, !1);
    }
    return this;
  }
  /**
   * @internal
   */
  _rebuild(e = !1) {
    if (this._instanceDataStorage.instancesBuffer && (e && this._instanceDataStorage.instancesBuffer.dispose(), this._instanceDataStorage.instancesBuffer = null), this._userInstancedBuffersStorage) {
      for (const t in this._userInstancedBuffersStorage.vertexBuffers) {
        const i = this._userInstancedBuffersStorage.vertexBuffers[t];
        i && (e && i.dispose(), this._userInstancedBuffersStorage.vertexBuffers[t] = null);
      }
      this._userInstancedBuffersStorage.vertexArrayObjects && (this._userInstancedBuffersStorage.vertexArrayObjects = {});
    }
    this._internalMeshDataInfo._effectiveMaterial = null, super._rebuild(e);
  }
  /** @internal */
  _freeze() {
    if (this.subMeshes) {
      for (let e = 0; e < this.subMeshes.length; e++)
        this._getInstancesRenderList(e);
      this._internalMeshDataInfo._effectiveMaterial = null, this._instanceDataStorage.isFrozen = !0;
    }
  }
  /** @internal */
  _unFreeze() {
    this._instanceDataStorage.isFrozen = !1, this._instanceDataStorage.previousBatch = null;
  }
  /**
   * 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(e, t, i) {
    var s, r, n;
    const a = this.getScene();
    if (this._internalAbstractMeshDataInfo._isActiveIntermediate ? this._internalAbstractMeshDataInfo._isActiveIntermediate = !1 : this._internalAbstractMeshDataInfo._isActive = !1, this._checkOcclusionQuery() && !this._occlusionDataStorage.forceRenderingWhenOccluded)
      return this;
    const o = this._getInstancesRenderList(e._id, !!i);
    if (o.mustReturn)
      return this;
    if (!this._geometry || !this._geometry.getVertexBuffers() || !this._unIndexed && !this._geometry.getIndexBuffer())
      return this;
    const h = a.getEngine();
    let c = 0, u = null;
    this.ignoreCameraMaxZ && a.activeCamera && !a._isInIntermediateRendering() && (c = a.activeCamera.maxZ, u = a.activeCamera, a.activeCamera.maxZ = 0, a.updateTransformMatrix(!0)), this._internalMeshDataInfo._onBeforeRenderObservable && this._internalMeshDataInfo._onBeforeRenderObservable.notifyObservers(this);
    const d = e.getRenderingMesh(), g = o.hardwareInstancedRendering[e._id] || d.hasThinInstances || !!this._userInstancedBuffersStorage && !e.getMesh()._internalAbstractMeshDataInfo._actAsRegularMesh, f = this._instanceDataStorage, m = e.getMaterial();
    if (!m)
      return u && (u.maxZ = c, a.updateTransformMatrix(!0)), this;
    if (!f.isFrozen || !this._internalMeshDataInfo._effectiveMaterial || this._internalMeshDataInfo._effectiveMaterial !== m) {
      if (m._storeEffectOnSubMeshes) {
        if (!m.isReadyForSubMesh(this, e, g))
          return u && (u.maxZ = c, a.updateTransformMatrix(!0)), this;
      } else if (!m.isReady(this, g))
        return u && (u.maxZ = c, a.updateTransformMatrix(!0)), this;
      this._internalMeshDataInfo._effectiveMaterial = m;
    } else if (m._storeEffectOnSubMeshes && !(!((s = e.effect) === null || s === void 0) && s._wasPreviouslyReady) || !m._storeEffectOnSubMeshes && !(!((r = m.getEffect()) === null || r === void 0) && r._wasPreviouslyReady))
      return u && (u.maxZ = c, a.updateTransformMatrix(!0)), this;
    t && h.setAlphaMode(this._internalMeshDataInfo._effectiveMaterial.alphaMode);
    let b;
    this._internalMeshDataInfo._effectiveMaterial._storeEffectOnSubMeshes ? b = e._drawWrapper : b = this._internalMeshDataInfo._effectiveMaterial._getDrawWrapper();
    const T = (n = b == null ? void 0 : b.effect) !== null && n !== void 0 ? n : null;
    for (const D of a._beforeRenderingMeshStage)
      D.action(this, e, o, T);
    if (!b || !T)
      return u && (u.maxZ = c, a.updateTransformMatrix(!0)), this;
    const M = i || this;
    let v;
    if (!f.isFrozen && (this._internalMeshDataInfo._effectiveMaterial.backFaceCulling || this.overrideMaterialSideOrientation !== null)) {
      const D = M._getWorldMatrixDeterminant();
      v = this.overrideMaterialSideOrientation, v == null && (v = this._internalMeshDataInfo._effectiveMaterial.sideOrientation), D < 0 && (v = v === I.ClockWiseSideOrientation ? I.CounterClockWiseSideOrientation : I.ClockWiseSideOrientation), f.sideOrientation = v;
    } else
      v = f.sideOrientation;
    const A = this._internalMeshDataInfo._effectiveMaterial._preBind(b, v);
    this._internalMeshDataInfo._effectiveMaterial.forceDepthWrite && h.setDepthWrite(!0);
    const E = this._internalMeshDataInfo._effectiveMaterial, y = E.fillMode;
    this._internalMeshDataInfo._onBeforeBindObservable && this._internalMeshDataInfo._onBeforeBindObservable.notifyObservers(this), g || this._bind(e, T, y, !1);
    const x = M.getWorldMatrix();
    E._storeEffectOnSubMeshes ? E.bindForSubMesh(x, this, e) : E.bind(x, this), !E.backFaceCulling && E.separateCullingPass && (h.setState(!0, E.zOffset, !1, !A, E.cullBackFaces, E.stencil, E.zOffsetUnits), this._processRendering(this, e, T, y, o, g, this._onBeforeDraw, this._internalMeshDataInfo._effectiveMaterial), h.setState(!0, E.zOffset, !1, A, E.cullBackFaces, E.stencil, E.zOffsetUnits), this._internalMeshDataInfo._onBetweenPassObservable && this._internalMeshDataInfo._onBetweenPassObservable.notifyObservers(e)), this._processRendering(this, e, T, y, o, g, this._onBeforeDraw, this._internalMeshDataInfo._effectiveMaterial), this._internalMeshDataInfo._effectiveMaterial.unbind();
    for (const D of a._afterRenderingMeshStage)
      D.action(this, e, o, T);
    return this._internalMeshDataInfo._onAfterRenderObservable && this._internalMeshDataInfo._onAfterRenderObservable.notifyObservers(this), u && (u.maxZ = c, a.updateTransformMatrix(!0)), a.performancePriority === et.Aggressive && !f.isFrozen && this._freeze(), 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() {
    this.isVerticesDataPresent(_.MatricesWeightsKind) && (this.isVerticesDataPresent(_.MatricesWeightsExtraKind) ? this._normalizeSkinWeightsAndExtra() : this._normalizeSkinFourWeights());
  }
  // faster 4 weight version.
  _normalizeSkinFourWeights() {
    const e = this.getVerticesData(_.MatricesWeightsKind), t = e.length;
    for (let i = 0; i < t; i += 4) {
      const s = e[i] + e[i + 1] + e[i + 2] + e[i + 3];
      if (s === 0)
        e[i] = 1;
      else {
        const r = 1 / s;
        e[i] *= r, e[i + 1] *= r, e[i + 2] *= r, e[i + 3] *= r;
      }
    }
    this.setVerticesData(_.MatricesWeightsKind, e);
  }
  // handle special case of extra verts.  (in theory gltf can handle 12 influences)
  _normalizeSkinWeightsAndExtra() {
    const e = this.getVerticesData(_.MatricesWeightsExtraKind), t = this.getVerticesData(_.MatricesWeightsKind), i = t.length;
    for (let s = 0; s < i; s += 4) {
      let r = t[s] + t[s + 1] + t[s + 2] + t[s + 3];
      if (r += e[s] + e[s + 1] + e[s + 2] + e[s + 3], r === 0)
        t[s] = 1;
      else {
        const n = 1 / r;
        t[s] *= n, t[s + 1] *= n, t[s + 2] *= n, t[s + 3] *= n, e[s] *= n, e[s + 1] *= n, e[s + 2] *= n, e[s + 3] *= n;
      }
    }
    this.setVerticesData(_.MatricesWeightsKind, t), this.setVerticesData(_.MatricesWeightsKind, e);
  }
  /**
   * 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 e = this.getVerticesData(_.MatricesWeightsExtraKind), t = this.getVerticesData(_.MatricesWeightsKind);
    if (t === null || this.skeleton == null)
      return { skinned: !1, valid: !0, report: "not skinned" };
    const i = t.length;
    let s = 0, r = 0, n = 0, a = 0;
    const o = e === null ? 4 : 8, h = new Array();
    for (let b = 0; b <= o; b++)
      h[b] = 0;
    const c = 1e-3;
    for (let b = 0; b < i; b += 4) {
      let T = t[b], M = T, v = M === 0 ? 0 : 1;
      for (let A = 1; A < o; A++) {
        const E = A < 4 ? t[b + A] : e[b + A - 4];
        E > T && s++, E !== 0 && v++, M += E, T = E;
      }
      if (h[v]++, v > n && (n = v), M === 0)
        r++;
      else {
        const A = 1 / M;
        let E = 0;
        for (let y = 0; y < o; y++)
          y < 4 ? E += Math.abs(t[b + y] - t[b + y] * A) : E += Math.abs(e[b + y - 4] - e[b + y - 4] * A);
        E > c && a++;
      }
    }
    const u = this.skeleton.bones.length, d = this.getVerticesData(_.MatricesIndicesKind), g = this.getVerticesData(_.MatricesIndicesExtraKind);
    let f = 0;
    for (let b = 0; b < i; b += 4)
      for (let T = 0; T < o; T++) {
        const M = T < 4 ? d[b + T] : g[b + T - 4];
        (M >= u || M < 0) && f++;
      }
    const m = "Number of Weights = " + i / 4 + `
Maximum influences = ` + n + `
Missing Weights = ` + r + `
Not Sorted = ` + s + `
Not Normalized = ` + a + `
WeightCounts = [` + h + `]
Number of bones = ` + u + `
Bad Bone Indices = ` + f;
    return { skinned: !0, valid: r === 0 && a === 0 && f === 0, report: m };
  }
  /** @internal */
  _checkDelayState() {
    const e = this.getScene();
    return this._geometry ? this._geometry.load(e) : this.delayLoadState === 4 && (this.delayLoadState = 2, this._queueLoad(e)), this;
  }
  _queueLoad(e) {
    e.addPendingData(this);
    const t = this.delayLoadingFile.indexOf(".babylonbinarymeshdata") !== -1;
    return k.LoadFile(this.delayLoadingFile, (i) => {
      i instanceof ArrayBuffer ? this._delayLoadingFunction(i, this) : this._delayLoadingFunction(JSON.parse(i), this), this.instances.forEach((s) => {
        s.refreshBoundingInfo(), s._syncSubMeshes();
      }), this.delayLoadState = 1, e.removePendingData(this);
    }, () => {
    }, e.offlineProvider, t), 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(e) {
    return this.delayLoadState === 2 || !super.isInFrustum(e) ? !1 : (this._checkDelayState(), !0);
  }
  /**
   * 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(e) {
    const t = this.getScene().materials;
    let i;
    for (i = t.length - 1; i > -1; i--)
      if (t[i].id === e)
        return this.material = t[i], this;
    const s = this.getScene().multiMaterials;
    for (i = s.length - 1; i > -1; i--)
      if (s[i].id === e)
        return this.material = s[i], 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 e = new Array();
    return this.material && e.push(this.material), this.skeleton && e.push(this.skeleton), e;
  }
  /**
   * 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(e) {
    if (!this.isVerticesDataPresent(_.PositionKind))
      return this;
    const t = this.subMeshes.splice(0);
    this._resetPointsArrayCache();
    let i = this.getVerticesData(_.PositionKind);
    const s = p.Zero();
    let r;
    for (r = 0; r < i.length; r += 3)
      p.TransformCoordinatesFromFloatsToRef(i[r], i[r + 1], i[r + 2], e, s).toArray(i, r);
    if (this.setVerticesData(_.PositionKind, i, this.getVertexBuffer(_.PositionKind).isUpdatable()), this.isVerticesDataPresent(_.NormalKind)) {
      for (i = this.getVerticesData(_.NormalKind), r = 0; r < i.length; r += 3)
        p.TransformNormalFromFloatsToRef(i[r], i[r + 1], i[r + 2], e, s).normalize().toArray(i, r);
      this.setVerticesData(_.NormalKind, i, this.getVertexBuffer(_.NormalKind).isUpdatable());
    }
    return e.determinant() < 0 && this.flipFaces(), this.releaseSubMeshes(), this.subMeshes = t, 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
   * @returns the current mesh
   */
  bakeCurrentTransformIntoVertices(e = !0) {
    return this.bakeTransformIntoVertices(this.computeWorldMatrix(!0)), this.resetLocalMatrix(e), this;
  }
  // Cache
  /** @internal */
  get _positions() {
    return this._internalAbstractMeshDataInfo._positions ? this._internalAbstractMeshDataInfo._positions : this._geometry ? this._geometry._positions : null;
  }
  /** @internal */
  _resetPointsArrayCache() {
    return this._geometry && this._geometry._resetPointsArrayCache(), this;
  }
  /** @internal */
  _generatePointsArray() {
    return this._geometry ? this._geometry._generatePointsArray() : !1;
  }
  /**
   * 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`)
   * @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(e = "", t = null, i, s = !0) {
    return new U(e, this.getScene(), t, this, i, s);
  }
  /**
   * 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(e, t = !1) {
    this.morphTargetManager = null, this._geometry && this._geometry.releaseForMesh(this, !0);
    const i = this._internalMeshDataInfo;
    if (i._onBeforeDrawObservable && i._onBeforeDrawObservable.clear(), i._onBeforeBindObservable && i._onBeforeBindObservable.clear(), i._onBeforeRenderObservable && i._onBeforeRenderObservable.clear(), i._onAfterRenderObservable && i._onAfterRenderObservable.clear(), i._onBetweenPassObservable && i._onBetweenPassObservable.clear(), this._scene.useClonedMeshMap) {
      if (i.meshMap)
        for (const s in i.meshMap) {
          const r = i.meshMap[s];
          r && (r._internalMeshDataInfo._source = null, i.meshMap[s] = void 0);
        }
      i._source && i._source._internalMeshDataInfo.meshMap && (i._source._internalMeshDataInfo.meshMap[this.uniqueId] = void 0);
    } else {
      const s = this.getScene().meshes;
      for (const r of s) {
        const n = r;
        n._internalMeshDataInfo && n._internalMeshDataInfo._source && n._internalMeshDataInfo._source === this && (n._internalMeshDataInfo._source = null);
      }
    }
    i._source = null, this._instanceDataStorage.visibleInstances = {}, this._disposeInstanceSpecificData(), this._disposeThinInstanceSpecificData(), this._internalMeshDataInfo._checkReadinessObserver && this._scene.onBeforeRenderObservable.remove(this._internalMeshDataInfo._checkReadinessObserver), super.dispose(e, t);
  }
  /** @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.
   * @returns the Mesh.
   */
  applyDisplacementMap(e, t, i, s, r, n, a = !1) {
    const o = this.getScene(), h = (c) => {
      const u = c.width, d = c.height, f = this.getEngine().createCanvas(u, d).getContext("2d");
      f.drawImage(c, 0, 0);
      const m = f.getImageData(0, 0, u, d).data;
      this.applyDisplacementMapFromBuffer(m, u, d, t, i, r, n, a), s && s(this);
    };
    return k.LoadImage(e, h, () => {
    }, o.offlineProvider), 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(e, t, i, s, r, n, a, o = !1) {
    if (!this.isVerticesDataPresent(_.PositionKind) || !this.isVerticesDataPresent(_.NormalKind) || !this.isVerticesDataPresent(_.UVKind))
      return S.Warn("Cannot call applyDisplacementMap: Given mesh is not complete. Position, Normal or UV are missing"), this;
    const h = this.getVerticesData(_.PositionKind, !0, !0), c = this.getVerticesData(_.NormalKind), u = this.getVerticesData(_.UVKind);
    let d = p.Zero();
    const g = p.Zero(), f = le.Zero();
    n = n || le.Zero(), a = a || new le(1, 1);
    for (let m = 0; m < h.length; m += 3) {
      p.FromArrayToRef(h, m, d), p.FromArrayToRef(c, m, g), le.FromArrayToRef(u, m / 3 * 2, f);
      const b = Math.abs(f.x * a.x + n.x % 1) * (t - 1) % t | 0, T = Math.abs(f.y * a.y + n.y % 1) * (i - 1) % i | 0, M = (b + T * t) * 4, v = e[M] / 255, A = e[M + 1] / 255, E = e[M + 2] / 255, y = v * 0.3 + A * 0.59 + E * 0.11;
      g.normalize(), g.scaleInPlace(s + (r - s) * y), d = d.add(g), d.toArray(h, m);
    }
    return q.ComputeNormals(h, this.getIndices(), c), o ? (this.setVerticesData(_.PositionKind, h), this.setVerticesData(_.NormalKind, c), this.setVerticesData(_.UVKind, u)) : (this.updateVerticesData(_.PositionKind, h), this.updateVerticesData(_.NormalKind, c)), 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() {
    const e = this.getVerticesDataKinds(), t = {}, i = {}, s = {};
    let r = !1, n, a;
    for (n = 0; n < e.length; n++) {
      a = e[n];
      const b = this.getVertexBuffer(a), T = b.getData();
      if (!((T instanceof Array || T instanceof Float32Array) && T.length === 0)) {
        if (a === _.NormalKind) {
          r = b.isUpdatable(), e.splice(n, 1), n--;
          continue;
        }
        t[a] = b, i[a] = this.getVerticesData(a), s[a] = [];
      }
    }
    const o = this.subMeshes.slice(0), h = this.getIndices(), c = this.getTotalIndices();
    let u;
    for (u = 0; u < c; u++) {
      const b = h[u];
      for (n = 0; n < e.length; n++) {
        if (a = e[n], !t[a])
          continue;
        const T = t[a].getStrideSize();
        for (let M = 0; M < T; M++)
          s[a].push(i[a][b * T + M]);
      }
    }
    const d = [], g = s[_.PositionKind], f = this.getScene().useRightHandedSystem;
    let m;
    for (f ? m = this.overrideMaterialSideOrientation === 1 : m = this.overrideMaterialSideOrientation === 0, u = 0; u < c; u += 3) {
      h[u] = u, h[u + 1] = u + 1, h[u + 2] = u + 2;
      const b = p.FromArray(g, u * 3), T = p.FromArray(g, (u + 1) * 3), M = p.FromArray(g, (u + 2) * 3), v = b.subtract(T), A = M.subtract(T), E = p.Normalize(p.Cross(v, A));
      m && E.scaleInPlace(-1);
      for (let y = 0; y < 3; y++)
        d.push(E.x), d.push(E.y), d.push(E.z);
    }
    for (this.setIndices(h), this.setVerticesData(_.NormalKind, d, r), n = 0; n < e.length; n++)
      a = e[n], s[a] && this.setVerticesData(a, s[a], t[a].isUpdatable());
    this.releaseSubMeshes();
    for (let b = 0; b < o.length; b++) {
      const T = o[b];
      Ye.AddToMesh(T.materialIndex, T.indexStart, T.indexCount, T.indexStart, T.indexCount, this);
    }
    return this.synchronizeInstances(), this;
  }
  /**
   * 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() {
    const e = this.getVerticesDataKinds(), t = {}, i = {}, s = {};
    let r, n;
    for (r = 0; r < e.length; r++) {
      n = e[r];
      const u = this.getVertexBuffer(n);
      t[n] = u, i[n] = t[n].getData(), s[n] = [];
    }
    const a = this.subMeshes.slice(0), o = this.getIndices(), h = this.getTotalIndices();
    let c;
    for (c = 0; c < h; c++) {
      const u = o[c];
      for (r = 0; r < e.length; r++) {
        n = e[r];
        const d = t[n].getStrideSize();
        for (let g = 0; g < d; g++)
          s[n].push(i[n][u * d + g]);
      }
    }
    for (c = 0; c < h; c += 3)
      o[c] = c, o[c + 1] = c + 1, o[c + 2] = c + 2;
    for (this.setIndices(o), r = 0; r < e.length; r++)
      n = e[r], this.setVerticesData(n, s[n], t[n].isUpdatable(), t[n].getStrideSize());
    this.releaseSubMeshes();
    for (let u = 0; u < a.length; u++) {
      const d = a[u];
      Ye.AddToMesh(d.materialIndex, d.indexStart, d.indexCount, d.indexStart, d.indexCount, this);
    }
    return this._unIndexed = !0, this.synchronizeInstances(), this;
  }
  /**
   * 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(e = !1) {
    const t = q.ExtractFromMesh(this);
    let i;
    if (e && this.isVerticesDataPresent(_.NormalKind) && t.normals)
      for (i = 0; i < t.normals.length; i++)
        t.normals[i] *= -1;
    if (t.indices) {
      let s;
      for (i = 0; i < t.indices.length; i += 3)
        s = t.indices[i + 1], t.indices[i + 1] = t.indices[i + 2], t.indices[i + 2] = s;
    }
    return t.applyToMesh(this, this.isVertexBufferUpdatable(_.PositionKind)), 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(e = 1) {
    const t = q.ExtractFromMesh(this), i = t.indices && !Array.isArray(t.indices) && Array.from ? Array.from(t.indices) : t.indices, s = t.positions && !Array.isArray(t.positions) && Array.from ? Array.from(t.positions) : t.positions, r = t.uvs && !Array.isArray(t.uvs) && Array.from ? Array.from(t.uvs) : t.uvs, n = t.normals && !Array.isArray(t.normals) && Array.from ? Array.from(t.normals) : t.normals;
    if (!i || !s)
      S.Warn("Couldn't increase number of vertices : VertexData must contain at least indices and positions");
    else {
      t.indices = i, t.positions = s, r && (t.uvs = r), n && (t.normals = n);
      const a = e + 1, o = new Array();
      for (let E = 0; E < a + 1; E++)
        o[E] = new Array();
      let h, c;
      const u = new p(0, 0, 0), d = new p(0, 0, 0), g = new le(0, 0), f = new Array(), m = new Array(), b = new Array();
      let T, M = s.length, v;
      r && (v = r.length);
      let A;
      n && (A = n.length);
      for (let E = 0; E < i.length; E += 3) {
        m[0] = i[E], m[1] = i[E + 1], m[2] = i[E + 2];
        for (let y = 0; y < 3; y++)
          if (h = m[y], c = m[(y + 1) % 3], b[h] === void 0 && b[c] === void 0 ? (b[h] = new Array(), b[c] = new Array()) : (b[h] === void 0 && (b[h] = new Array()), b[c] === void 0 && (b[c] = new Array())), b[h][c] === void 0 && b[c][h] === void 0) {
            b[h][c] = [], u.x = (s[3 * c] - s[3 * h]) / a, u.y = (s[3 * c + 1] - s[3 * h + 1]) / a, u.z = (s[3 * c + 2] - s[3 * h + 2]) / a, n && (d.x = (n[3 * c] - n[3 * h]) / a, d.y = (n[3 * c + 1] - n[3 * h + 1]) / a, d.z = (n[3 * c + 2] - n[3 * h + 2]) / a), r && (g.x = (r[2 * c] - r[2 * h]) / a, g.y = (r[2 * c + 1] - r[2 * h + 1]) / a), b[h][c].push(h);
            for (let x = 1; x < a; x++)
              b[h][c].push(s.length / 3), s[M++] = s[3 * h] + x * u.x, s[M++] = s[3 * h + 1] + x * u.y, s[M++] = s[3 * h + 2] + x * u.z, n && (n[A++] = n[3 * h] + x * d.x, n[A++] = n[3 * h + 1] + x * d.y, n[A++] = n[3 * h + 2] + x * d.z), r && (r[v++] = r[2 * h] + x * g.x, r[v++] = r[2 * h + 1] + x * g.y);
            b[h][c].push(c), b[c][h] = new Array(), T = b[h][c].length;
            for (let x = 0; x < T; x++)
              b[c][h][x] = b[h][c][T - 1 - x];
          }
        o[0][0] = i[E], o[1][0] = b[i[E]][i[E + 1]][1], o[1][1] = b[i[E]][i[E + 2]][1];
        for (let y = 2; y < a; y++) {
          o[y][0] = b[i[E]][i[E + 1]][y], o[y][y] = b[i[E]][i[E + 2]][y], u.x = (s[3 * o[y][y]] - s[3 * o[y][0]]) / y, u.y = (s[3 * o[y][y] + 1] - s[3 * o[y][0] + 1]) / y, u.z = (s[3 * o[y][y] + 2] - s[3 * o[y][0] + 2]) / y, n && (d.x = (n[3 * o[y][y]] - n[3 * o[y][0]]) / y, d.y = (n[3 * o[y][y] + 1] - n[3 * o[y][0] + 1]) / y, d.z = (n[3 * o[y][y] + 2] - n[3 * o[y][0] + 2]) / y), r && (g.x = (r[2 * o[y][y]] - r[2 * o[y][0]]) / y, g.y = (r[2 * o[y][y] + 1] - r[2 * o[y][0] + 1]) / y);
          for (let x = 1; x < y; x++)
            o[y][x] = s.length / 3, s[M++] = s[3 * o[y][0]] + x * u.x, s[M++] = s[3 * o[y][0] + 1] + x * u.y, s[M++] = s[3 * o[y][0] + 2] + x * u.z, n && (n[A++] = n[3 * o[y][0]] + x * d.x, n[A++] = n[3 * o[y][0] + 1] + x * d.y, n[A++] = n[3 * o[y][0] + 2] + x * d.z), r && (r[v++] = r[2 * o[y][0]] + x * g.x, r[v++] = r[2 * o[y][0] + 1] + x * g.y);
        }
        o[a] = b[i[E + 1]][i[E + 2]], f.push(o[0][0], o[1][0], o[1][1]);
        for (let y = 1; y < a; y++) {
          let x;
          for (x = 0; x < y; x++)
            f.push(o[y][x], o[y + 1][x], o[y + 1][x + 1]), f.push(o[y][x], o[y + 1][x + 1], o[y][x + 1]);
          f.push(o[y][x], o[y + 1][x], o[y + 1][x + 1]);
        }
      }
      t.indices = f, t.applyToMesh(this, this.isVertexBufferUpdatable(_.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 e = q.ExtractFromMesh(this), t = e.uvs, i = e.indices, s = e.positions, r = e.colors, n = e.matricesIndices, a = e.matricesWeights, o = e.matricesIndicesExtra, h = e.matricesWeightsExtra;
    if (i === void 0 || s === void 0 || i === null || s === null)
      S.Warn("VertexData contains empty entries");
    else {
      const c = new Array(), u = new Array(), d = new Array(), g = new Array(), f = new Array(), m = new Array(), b = new Array(), T = new Array();
      let M = new Array(), v = 0;
      const A = {};
      let E, y;
      for (let D = 0; D < i.length; D += 3) {
        y = [i[D], i[D + 1], i[D + 2]], M = new Array();
        for (let V = 0; V < 3; V++) {
          M[V] = "";
          for (let W = 0; W < 3; W++)
            Math.abs(s[3 * y[V] + W]) < 1e-8 && (s[3 * y[V] + W] = 0), M[V] += s[3 * y[V] + W] + "|";
        }
        if (!(M[0] == M[1] || M[0] == M[2] || M[1] == M[2]))
          for (let V = 0; V < 3; V++) {
            if (E = A[M[V]], E === void 0) {
              A[M[V]] = v, E = v++;
              for (let W = 0; W < 3; W++)
                c.push(s[3 * y[V] + W]);
              if (r != null)
                for (let W = 0; W < 4; W++)
                  g.push(r[4 * y[V] + W]);
              if (t != null)
                for (let W = 0; W < 2; W++)
                  d.push(t[2 * y[V] + W]);
              if (n != null)
                for (let W = 0; W < 4; W++)
                  f.push(n[4 * y[V] + W]);
              if (a != null)
                for (let W = 0; W < 4; W++)
                  m.push(a[4 * y[V] + W]);
              if (o != null)
                for (let W = 0; W < 4; W++)
                  b.push(o[4 * y[V] + W]);
              if (h != null)
                for (let W = 0; W < 4; W++)
                  T.push(h[4 * y[V] + W]);
            }
            u.push(E);
          }
      }
      const x = new Array();
      q.ComputeNormals(c, u, x), e.positions = c, e.indices = u, e.normals = x, t != null && (e.uvs = d), r != null && (e.colors = g), n != null && (e.matricesIndices = f), a != null && (e.matricesWeights = m), o != null && (e.matricesIndicesExtra = b), a != null && (e.matricesWeightsExtra = T), e.applyToMesh(this, this.isVertexBufferUpdatable(_.PositionKind));
    }
  }
  // Instances
  /**
   * @internal
   */
  // eslint-disable-next-line @typescript-eslint/no-unused-vars, @typescript-eslint/naming-convention
  static _instancedMeshFactory(e, t) {
    throw Y("InstancedMesh");
  }
  /**
   * @internal
   */
  // eslint-disable-next-line @typescript-eslint/no-unused-vars
  static _PhysicsImpostorParser(e, t, i) {
    throw Y("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(e) {
    return U._instancedMeshFactory(e, this);
  }
  /**
   * 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 e = 0; e < this.instances.length; e++)
      this.instances[e]._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(e) {
    const t = this.getIndices(), i = this.getVerticesData(_.PositionKind);
    if (!i || !t)
      return this;
    const s = new Array();
    for (let n = 0; n < i.length; n = n + 3)
      s.push(p.FromArray(i, n));
    const r = new Array();
    return si.SyncAsyncForLoop(s.length, 40, (n) => {
      const a = s.length - 1 - n, o = s[a];
      for (let h = 0; h < a; ++h) {
        const c = s[h];
        if (o.equals(c)) {
          r[a] = h;
          break;
        }
      }
    }, () => {
      for (let a = 0; a < t.length; ++a)
        t[a] = r[t[a]] || t[a];
      const n = this.subMeshes.slice(0);
      this.setIndices(t), this.subMeshes = n, e && e(this);
    }), this;
  }
  /**
   * Serialize current mesh
   * @param serializationObject defines the object which will receive the serialization data
   */
  serialize(e = {}) {
    e.name = this.name, e.id = this.id, e.uniqueId = this.uniqueId, e.type = this.getClassName(), re && re.HasTags(this) && (e.tags = re.GetTags(this)), e.position = this.position.asArray(), this.rotationQuaternion ? e.rotationQuaternion = this.rotationQuaternion.asArray() : this.rotation && (e.rotation = this.rotation.asArray()), e.scaling = this.scaling.asArray(), this._postMultiplyPivotMatrix ? e.pivotMatrix = this.getPivotMatrix().asArray() : e.localMatrix = this.getPivotMatrix().asArray(), e.isEnabled = this.isEnabled(!1), e.isVisible = this.isVisible, e.infiniteDistance = this.infiniteDistance, e.pickable = this.isPickable, e.receiveShadows = this.receiveShadows, e.billboardMode = this.billboardMode, e.visibility = this.visibility, e.checkCollisions = this.checkCollisions, e.isBlocker = this.isBlocker, e.overrideMaterialSideOrientation = this.overrideMaterialSideOrientation, this.parent && this.parent._serializeAsParent(e), e.isUnIndexed = this.isUnIndexed;
    const t = this._geometry;
    if (t && this.subMeshes) {
      e.geometryUniqueId = t.uniqueId, e.geometryId = t.id, e.subMeshes = [];
      for (let i = 0; i < this.subMeshes.length; i++) {
        const s = this.subMeshes[i];
        e.subMeshes.push({
          materialIndex: s.materialIndex,
          verticesStart: s.verticesStart,
          verticesCount: s.verticesCount,
          indexStart: s.indexStart,
          indexCount: s.indexCount
        });
      }
    }
    if (this.material ? this.material.doNotSerialize || (e.materialUniqueId = this.material.uniqueId, e.materialId = this.material.id) : (this.material = null, e.materialUniqueId = this._scene.defaultMaterial.uniqueId, e.materialId = this._scene.defaultMaterial.id), this.morphTargetManager && (e.morphTargetManagerId = this.morphTargetManager.uniqueId), this.skeleton && (e.skeletonId = this.skeleton.id, e.numBoneInfluencers = this.numBoneInfluencers), this.getScene()._getComponent(K.NAME_PHYSICSENGINE)) {
      const i = this.getPhysicsImpostor();
      i && (e.physicsMass = i.getParam("mass"), e.physicsFriction = i.getParam("friction"), e.physicsRestitution = i.getParam("mass"), e.physicsImpostor = i.type);
    }
    this.metadata && (e.metadata = this.metadata), e.instances = [];
    for (let i = 0; i < this.instances.length; i++) {
      const s = this.instances[i];
      if (s.doNotSerialize)
        continue;
      const r = {
        name: s.name,
        id: s.id,
        isEnabled: s.isEnabled(!1),
        isVisible: s.isVisible,
        isPickable: s.isPickable,
        checkCollisions: s.checkCollisions,
        position: s.position.asArray(),
        scaling: s.scaling.asArray()
      };
      if (s.parent && s.parent._serializeAsParent(r), s.rotationQuaternion ? r.rotationQuaternion = s.rotationQuaternion.asArray() : s.rotation && (r.rotation = s.rotation.asArray()), this.getScene()._getComponent(K.NAME_PHYSICSENGINE)) {
        const n = s.getPhysicsImpostor();
        n && (r.physicsMass = n.getParam("mass"), r.physicsFriction = n.getParam("friction"), r.physicsRestitution = n.getParam("mass"), r.physicsImpostor = n.type);
      }
      s.metadata && (r.metadata = s.metadata), s.actionManager && (r.actions = s.actionManager.serialize(s.name)), e.instances.push(r), he.AppendSerializedAnimations(s, r), r.ranges = s.serializeAnimationRanges();
    }
    if (this._thinInstanceDataStorage.instancesCount && this._thinInstanceDataStorage.matrixData && (e.thinInstances = {
      instancesCount: this._thinInstanceDataStorage.instancesCount,
      matrixData: Array.from(this._thinInstanceDataStorage.matrixData),
      matrixBufferSize: this._thinInstanceDataStorage.matrixBufferSize,
      enablePicking: this.thinInstanceEnablePicking
    }, this._userThinInstanceBuffersStorage)) {
      const i = {
        data: {},
        sizes: {},
        strides: {}
      };
      for (const s in this._userThinInstanceBuffersStorage.data)
        i.data[s] = Array.from(this._userThinInstanceBuffersStorage.data[s]), i.sizes[s] = this._userThinInstanceBuffersStorage.sizes[s], i.strides[s] = this._userThinInstanceBuffersStorage.strides[s];
      e.thinInstances.userThinInstance = i;
    }
    return he.AppendSerializedAnimations(this, e), e.ranges = this.serializeAnimationRanges(), e.layerMask = this.layerMask, e.alphaIndex = this.alphaIndex, e.hasVertexAlpha = this.hasVertexAlpha, e.overlayAlpha = this.overlayAlpha, e.overlayColor = this.overlayColor.asArray(), e.renderOverlay = this.renderOverlay, e.applyFog = this.applyFog, this.actionManager && (e.actions = this.actionManager.serialize(this.name)), e;
  }
  /** @internal */
  _syncGeometryWithMorphTargetManager() {
    if (!this.geometry)
      return;
    this._markSubMeshesAsAttributesDirty();
    const e = this._internalAbstractMeshDataInfo._morphTargetManager;
    if (e && e.vertexCount) {
      if (e.vertexCount !== this.getTotalVertices()) {
        S.Error("Mesh is incompatible with morph targets. Targets and mesh must all have the same vertices count."), this.morphTargetManager = null;
        return;
      }
      if (e.isUsingTextureForTargets)
        return;
      for (let t = 0; t < e.numInfluencers; t++) {
        const i = e.getActiveTarget(t), s = i.getPositions();
        if (!s) {
          S.Error("Invalid morph target. Target must have positions.");
          return;
        }
        this.geometry.setVerticesData(_.PositionKind + t, s, !1, 3);
        const r = i.getNormals();
        r && this.geometry.setVerticesData(_.NormalKind + t, r, !1, 3);
        const n = i.getTangents();
        n && this.geometry.setVerticesData(_.TangentKind + t, n, !1, 3);
        const a = i.getUVs();
        a && this.geometry.setVerticesData(_.UVKind + "_" + t, a, !1, 2);
      }
    } else {
      let t = 0;
      for (; this.geometry.isVerticesDataPresent(_.PositionKind + t); )
        this.geometry.removeVerticesData(_.PositionKind + t), this.geometry.isVerticesDataPresent(_.NormalKind + t) && this.geometry.removeVerticesData(_.NormalKind + t), this.geometry.isVerticesDataPresent(_.TangentKind + t) && this.geometry.removeVerticesData(_.TangentKind + t), this.geometry.isVerticesDataPresent(_.UVKind + t) && this.geometry.removeVerticesData(_.UVKind + "_" + t), t++;
    }
  }
  /**
   * 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(e, t, i) {
    let s;
    if (e.type && e.type === "LinesMesh" ? s = U._LinesMeshParser(e, t) : e.type && e.type === "GroundMesh" ? s = U._GroundMeshParser(e, t) : e.type && e.type === "GoldbergMesh" ? s = U._GoldbergMeshParser(e, t) : s = new U(e.name, t), s.id = e.id, s._waitingParsedUniqueId = e.uniqueId, re && re.AddTagsTo(s, e.tags), s.position = p.FromArray(e.position), e.metadata !== void 0 && (s.metadata = e.metadata), e.rotationQuaternion ? s.rotationQuaternion = X.FromArray(e.rotationQuaternion) : e.rotation && (s.rotation = p.FromArray(e.rotation)), s.scaling = p.FromArray(e.scaling), e.localMatrix ? s.setPreTransformMatrix(R.FromArray(e.localMatrix)) : e.pivotMatrix && s.setPivotMatrix(R.FromArray(e.pivotMatrix)), s.setEnabled(e.isEnabled), s.isVisible = e.isVisible, s.infiniteDistance = e.infiniteDistance, s.showBoundingBox = e.showBoundingBox, s.showSubMeshesBoundingBox = e.showSubMeshesBoundingBox, e.applyFog !== void 0 && (s.applyFog = e.applyFog), e.pickable !== void 0 && (s.isPickable = e.pickable), e.alphaIndex !== void 0 && (s.alphaIndex = e.alphaIndex), s.receiveShadows = e.receiveShadows, e.billboardMode !== void 0 && (s.billboardMode = e.billboardMode), e.visibility !== void 0 && (s.visibility = e.visibility), s.checkCollisions = e.checkCollisions, s.overrideMaterialSideOrientation = e.overrideMaterialSideOrientation, e.isBlocker !== void 0 && (s.isBlocker = e.isBlocker), s._shouldGenerateFlatShading = e.useFlatShading, e.freezeWorldMatrix && (s._waitingData.freezeWorldMatrix = e.freezeWorldMatrix), e.parentId !== void 0 && (s._waitingParentId = e.parentId), e.parentInstanceIndex !== void 0 && (s._waitingParentInstanceIndex = e.parentInstanceIndex), e.actions !== void 0 && (s._waitingData.actions = e.actions), e.overlayAlpha !== void 0 && (s.overlayAlpha = e.overlayAlpha), e.overlayColor !== void 0 && (s.overlayColor = te.FromArray(e.overlayColor)), e.renderOverlay !== void 0 && (s.renderOverlay = e.renderOverlay), s.isUnIndexed = !!e.isUnIndexed, s.hasVertexAlpha = e.hasVertexAlpha, e.delayLoadingFile ? (s.delayLoadState = 4, s.delayLoadingFile = i + e.delayLoadingFile, s.buildBoundingInfo(p.FromArray(e.boundingBoxMinimum), p.FromArray(e.boundingBoxMaximum)), e._binaryInfo && (s._binaryInfo = e._binaryInfo), s._delayInfo = [], e.hasUVs && s._delayInfo.push(_.UVKind), e.hasUVs2 && s._delayInfo.push(_.UV2Kind), e.hasUVs3 && s._delayInfo.push(_.UV3Kind), e.hasUVs4 && s._delayInfo.push(_.UV4Kind), e.hasUVs5 && s._delayInfo.push(_.UV5Kind), e.hasUVs6 && s._delayInfo.push(_.UV6Kind), e.hasColors && s._delayInfo.push(_.ColorKind), e.hasMatricesIndices && s._delayInfo.push(_.MatricesIndicesKind), e.hasMatricesWeights && s._delayInfo.push(_.MatricesWeightsKind), s._delayLoadingFunction = Ve._ImportGeometry, pe.ForceFullSceneLoadingForIncremental && s._checkDelayState()) : Ve._ImportGeometry(e, s), e.materialUniqueId ? s._waitingMaterialId = e.materialUniqueId : e.materialId && (s._waitingMaterialId = e.materialId), e.morphTargetManagerId > -1 && (s.morphTargetManager = t.getMorphTargetManagerById(e.morphTargetManagerId)), e.skeletonId !== void 0 && e.skeletonId !== null && (s.skeleton = t.getLastSkeletonById(e.skeletonId), e.numBoneInfluencers && (s.numBoneInfluencers = e.numBoneInfluencers)), e.animations) {
      for (let r = 0; r < e.animations.length; r++) {
        const n = e.animations[r], a = ii("BABYLON.Animation");
        a && s.animations.push(a.Parse(n));
      }
      Ne.ParseAnimationRanges(s, e, t);
    }
    if (e.autoAnimate && t.beginAnimation(s, e.autoAnimateFrom, e.autoAnimateTo, e.autoAnimateLoop, e.autoAnimateSpeed || 1), e.layerMask && !isNaN(e.layerMask) ? s.layerMask = Math.abs(parseInt(e.layerMask)) : s.layerMask = 268435455, e.physicsImpostor && U._PhysicsImpostorParser(t, s, e), e.lodMeshIds && (s._waitingData.lods = {
      ids: e.lodMeshIds,
      distances: e.lodDistances ? e.lodDistances : null,
      coverages: e.lodCoverages ? e.lodCoverages : null
    }), e.instances)
      for (let r = 0; r < e.instances.length; r++) {
        const n = e.instances[r], a = s.createInstance(n.name);
        if (n.id && (a.id = n.id), re && (n.tags ? re.AddTagsTo(a, n.tags) : re.AddTagsTo(a, e.tags)), a.position = p.FromArray(n.position), n.metadata !== void 0 && (a.metadata = n.metadata), n.parentId !== void 0 && (a._waitingParentId = n.parentId), n.parentInstanceIndex !== void 0 && (a._waitingParentInstanceIndex = n.parentInstanceIndex), n.isEnabled !== void 0 && n.isEnabled !== null && a.setEnabled(n.isEnabled), n.isVisible !== void 0 && n.isVisible !== null && (a.isVisible = n.isVisible), n.isPickable !== void 0 && n.isPickable !== null && (a.isPickable = n.isPickable), n.rotationQuaternion ? a.rotationQuaternion = X.FromArray(n.rotationQuaternion) : n.rotation && (a.rotation = p.FromArray(n.rotation)), a.scaling = p.FromArray(n.scaling), n.checkCollisions != null && n.checkCollisions != null && (a.checkCollisions = n.checkCollisions), n.pickable != null && n.pickable != null && (a.isPickable = n.pickable), n.showBoundingBox != null && n.showBoundingBox != null && (a.showBoundingBox = n.showBoundingBox), n.showSubMeshesBoundingBox != null && n.showSubMeshesBoundingBox != null && (a.showSubMeshesBoundingBox = n.showSubMeshesBoundingBox), n.alphaIndex != null && n.showSubMeshesBoundingBox != null && (a.alphaIndex = n.alphaIndex), n.physicsImpostor && U._PhysicsImpostorParser(t, a, n), n.actions !== void 0 && (a._waitingData.actions = n.actions), n.animations) {
          for (let o = 0; o < n.animations.length; o++) {
            const h = n.animations[o], c = ii("BABYLON.Animation");
            c && a.animations.push(c.Parse(h));
          }
          Ne.ParseAnimationRanges(a, n, t), n.autoAnimate && t.beginAnimation(a, n.autoAnimateFrom, n.autoAnimateTo, n.autoAnimateLoop, n.autoAnimateSpeed || 1);
        }
      }
    if (e.thinInstances) {
      const r = e.thinInstances;
      if (s.thinInstanceEnablePicking = !!r.enablePicking, r.matrixData ? (s.thinInstanceSetBuffer("matrix", new Float32Array(r.matrixData), 16, !1), s._thinInstanceDataStorage.matrixBufferSize = r.matrixBufferSize, s._thinInstanceDataStorage.instancesCount = r.instancesCount) : s._thinInstanceDataStorage.matrixBufferSize = r.matrixBufferSize, e.thinInstances.userThinInstance) {
        const n = e.thinInstances.userThinInstance;
        for (const a in n.data)
          s.thinInstanceSetBuffer(a, new Float32Array(n.data[a]), n.strides[a], !1), s._userThinInstanceBuffersStorage.sizes[a] = n.sizes[a];
      }
    }
    return s;
  }
  // 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 e = this._internalMeshDataInfo;
    if (!e._sourcePositions) {
      const t = this.getVerticesData(_.PositionKind);
      if (!t)
        return e._sourcePositions;
      e._sourcePositions = new Float32Array(t), this.isVertexBufferUpdatable(_.PositionKind) || this.setVerticesData(_.PositionKind, t, !0);
    }
    return e._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 e = this._internalMeshDataInfo;
    if (!e._sourceNormals) {
      const t = this.getVerticesData(_.NormalKind);
      if (!t)
        return e._sourceNormals;
      e._sourceNormals = new Float32Array(t), this.isVertexBufferUpdatable(_.NormalKind) || this.setVerticesData(_.NormalKind, t, !0);
    }
    return e._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(e) {
    if (!this.geometry)
      return this;
    if (this.geometry._softwareSkinningFrameId == this.getScene().getFrameId())
      return this;
    if (this.geometry._softwareSkinningFrameId = this.getScene().getFrameId(), !this.isVerticesDataPresent(_.PositionKind))
      return this;
    if (!this.isVerticesDataPresent(_.MatricesIndicesKind))
      return this;
    if (!this.isVerticesDataPresent(_.MatricesWeightsKind))
      return this;
    const t = this.isVerticesDataPresent(_.NormalKind), i = this._internalMeshDataInfo;
    if (!i._sourcePositions) {
      const T = this.subMeshes.slice();
      this.setPositionsForCPUSkinning(), this.subMeshes = T;
    }
    t && !i._sourceNormals && this.setNormalsForCPUSkinning();
    let s = this.getVerticesData(_.PositionKind);
    if (!s)
      return this;
    s instanceof Float32Array || (s = new Float32Array(s));
    let r = this.getVerticesData(_.NormalKind);
    if (t) {
      if (!r)
        return this;
      r instanceof Float32Array || (r = new Float32Array(r));
    }
    const n = this.getVerticesData(_.MatricesIndicesKind), a = this.getVerticesData(_.MatricesWeightsKind);
    if (!a || !n)
      return this;
    const o = this.numBoneInfluencers > 4, h = o ? this.getVerticesData(_.MatricesIndicesExtraKind) : null, c = o ? this.getVerticesData(_.MatricesWeightsExtraKind) : null, u = e.getTransformMatrices(this), d = p.Zero(), g = new R(), f = new R();
    let m = 0, b;
    for (let T = 0; T < s.length; T += 3, m += 4) {
      let M;
      for (b = 0; b < 4; b++)
        M = a[m + b], M > 0 && (R.FromFloat32ArrayToRefScaled(u, Math.floor(n[m + b] * 16), M, f), g.addToSelf(f));
      if (o)
        for (b = 0; b < 4; b++)
          M = c[m + b], M > 0 && (R.FromFloat32ArrayToRefScaled(u, Math.floor(h[m + b] * 16), M, f), g.addToSelf(f));
      p.TransformCoordinatesFromFloatsToRef(i._sourcePositions[T], i._sourcePositions[T + 1], i._sourcePositions[T + 2], g, d), d.toArray(s, T), t && (p.TransformNormalFromFloatsToRef(i._sourceNormals[T], i._sourceNormals[T + 1], i._sourceNormals[T + 2], g, d), d.toArray(r, T)), g.reset();
    }
    return this.updateVerticesData(_.PositionKind, s), t && this.updateVerticesData(_.NormalKind, r), 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(e) {
    let t = null, i = null;
    return e.forEach(function(s) {
      const n = s.getBoundingInfo().boundingBox;
      !t || !i ? (t = n.minimumWorld, i = n.maximumWorld) : (t.minimizeInPlace(n.minimumWorld), i.maximizeInPlace(n.maximumWorld));
    }), !t || !i ? {
      min: p.Zero(),
      max: p.Zero()
    } : {
      min: t,
      max: i
    };
  }
  /**
   * 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(e) {
    const t = e instanceof Array ? U.MinMax(e) : e;
    return p.Center(t.min, t.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(e, t = !0, i, s, r, n) {
    return Ui(U._MergeMeshesCoroutine(e, t, i, s, r, n, !1));
  }
  /**
   * 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 MergeMeshesAsync(e, t = !0, i, s, r, n) {
    return pr(U._MergeMeshesCoroutine(e, t, i, s, r, n, !0), gr());
  }
  static *_MergeMeshesCoroutine(e, t = !0, i, s, r, n, a) {
    if (e = e.filter(Boolean), e.length === 0)
      return null;
    let o;
    if (!i) {
      let x = 0;
      for (o = 0; o < e.length; o++)
        if (x += e[o].getTotalVertices(), x >= 65536)
          return S.Warn("Cannot merge meshes because resulting mesh will have more than 65536 vertices. Please use allow32BitsIndices = true to use 32 bits indices"), null;
    }
    n && (r = !1);
    const h = new Array(), c = new Array(), u = new Array(), d = e[0].overrideMaterialSideOrientation;
    for (o = 0; o < e.length; o++) {
      const x = e[o];
      if (x.isAnInstance)
        return S.Warn("Cannot merge instance meshes."), null;
      if (d !== x.overrideMaterialSideOrientation)
        return S.Warn("Cannot merge meshes with different overrideMaterialSideOrientation values."), null;
      if (r && u.push(x.getTotalIndices()), n)
        if (x.material) {
          const D = x.material;
          if (D instanceof Lt) {
            for (let V = 0; V < D.subMaterials.length; V++)
              h.indexOf(D.subMaterials[V]) < 0 && h.push(D.subMaterials[V]);
            for (let V = 0; V < x.subMeshes.length; V++)
              c.push(h.indexOf(D.subMaterials[x.subMeshes[V].materialIndex])), u.push(x.subMeshes[V].indexCount);
          } else {
            h.indexOf(D) < 0 && h.push(D);
            for (let V = 0; V < x.subMeshes.length; V++)
              c.push(h.indexOf(D)), u.push(x.subMeshes[V].indexCount);
          }
        } else
          for (let D = 0; D < x.subMeshes.length; D++)
            c.push(0), u.push(x.subMeshes[D].indexCount);
    }
    const g = e[0], f = (x) => {
      const D = x.computeWorldMatrix(!0);
      return { vertexData: q.ExtractFromMesh(x, !1, !1), transform: D };
    }, { vertexData: m, transform: b } = f(g);
    a && (yield);
    const T = new Array(e.length - 1);
    for (let x = 1; x < e.length; x++)
      T[x - 1] = f(e[x]), a && (yield);
    const M = m._mergeCoroutine(b, T, i, a, !t);
    let v = M.next();
    for (; !v.done; )
      a && (yield), v = M.next();
    const A = v.value;
    s || (s = new U(g.name + "_merged", g.getScene()));
    const E = A._applyToCoroutine(s, void 0, a);
    let y = E.next();
    for (; !y.done; )
      a && (yield), y = E.next();
    if (s.checkCollisions = g.checkCollisions, s.overrideMaterialSideOrientation = g.overrideMaterialSideOrientation, t)
      for (o = 0; o < e.length; o++)
        e[o].dispose();
    if (r || n) {
      s.releaseSubMeshes(), o = 0;
      let x = 0;
      for (; o < u.length; )
        Ye.CreateFromIndices(0, x, u[o], s, void 0, !1), x += u[o], o++;
      for (const D of s.subMeshes)
        D.refreshBoundingInfo();
      s.computeWorldMatrix(!0);
    }
    if (n) {
      const x = new Lt(g.name + "_merged", g.getScene());
      x.subMaterials = h;
      for (let D = 0; D < s.subMeshes.length; D++)
        s.subMeshes[D].materialIndex = c[D];
      s.material = x;
    } else
      s.material = g.material;
    return s;
  }
  /**
   * @internal
   */
  addInstance(e) {
    e._indexInSourceMeshInstanceArray = this.instances.length, this.instances.push(e);
  }
  /**
   * @internal
   */
  removeInstance(e) {
    const t = e._indexInSourceMeshInstanceArray;
    if (t != -1) {
      if (t !== this.instances.length - 1) {
        const i = this.instances[this.instances.length - 1];
        this.instances[t] = i, i._indexInSourceMeshInstanceArray = t;
      }
      e._indexInSourceMeshInstanceArray = -1, this.instances.pop();
    }
  }
  /** @internal */
  _shouldConvertRHS() {
    return this.overrideMaterialSideOrientation === I.CounterClockWiseSideOrientation;
  }
  /** @internal */
  _getRenderingFillMode(e) {
    var t;
    const i = this.getScene();
    return i.forcePointsCloud ? I.PointFillMode : i.forceWireframe ? I.WireFrameFillMode : (t = this.overrideRenderingFillMode) !== null && t !== void 0 ? t : e;
  }
}
U.FRONTSIDE = q.FRONTSIDE;
U.BACKSIDE = q.BACKSIDE;
U.DOUBLESIDE = q.DOUBLESIDE;
U.DEFAULTSIDE = q.DEFAULTSIDE;
U.NO_CAP = 0;
U.CAP_START = 1;
U.CAP_END = 2;
U.CAP_ALL = 3;
U.NO_FLIP = 0;
U.FLIP_TILE = 1;
U.ROTATE_TILE = 2;
U.FLIP_ROW = 3;
U.ROTATE_ROW = 4;
U.FLIP_N_ROTATE_TILE = 5;
U.FLIP_N_ROTATE_ROW = 6;
U.CENTER = 0;
U.LEFT = 1;
U.RIGHT = 2;
U.TOP = 3;
U.BOTTOM = 4;
U.INSTANCEDMESH_SORT_TRANSPARENT = !1;
U._GroundMeshParser = (l, e) => {
  throw Y("GroundMesh");
};
U._GoldbergMeshParser = (l, e) => {
  throw Y("GoldbergMesh");
};
U._LinesMeshParser = (l, e) => {
  throw Y("LinesMesh");
};
dt("BABYLON.Mesh", U);
U.prototype.setMaterialByID = function(l) {
  return this.setMaterialById(l);
};
U.CreateDisc = U.CreateDisc || (() => {
  throw new Error("Import MeshBuilder to populate this function");
});
U.CreateBox = U.CreateBox || (() => {
  throw new Error("Import MeshBuilder to populate this function");
});
U.CreateSphere = U.CreateSphere || (() => {
  throw new Error("Import MeshBuilder to populate this function");
});
U.CreateCylinder = U.CreateCylinder || (() => {
  throw new Error("Import MeshBuilder to populate this function");
});
U.CreateTorusKnot = U.CreateTorusKnot || (() => {
  throw new Error("Import MeshBuilder to populate this function");
});
U.CreateTorus = U.CreateTorus || (() => {
  throw new Error("Import MeshBuilder to populate this function");
});
U.CreatePlane = U.CreatePlane || (() => {
  throw new Error("Import MeshBuilder to populate this function");
});
U.CreateGround = U.CreateGround || (() => {
  throw new Error("Import MeshBuilder to populate this function");
});
U.CreateTiledGround = U.CreateTiledGround || (() => {
  throw new Error("Import MeshBuilder to populate this function");
});
U.CreateGroundFromHeightMap = U.CreateGroundFromHeightMap || (() => {
  throw new Error("Import MeshBuilder to populate this function");
});
U.CreateTube = U.CreateTube || (() => {
  throw new Error("Import MeshBuilder to populate this function");
});
U.CreatePolyhedron = U.CreatePolyhedron || (() => {
  throw new Error("Import MeshBuilder to populate this function");
});
U.CreateIcoSphere = U.CreateIcoSphere || (() => {
  throw new Error("Import MeshBuilder to populate this function");
});
U.CreateDecal = U.CreateDecal || (() => {
  throw new Error("Import MeshBuilder to populate this function");
});
U.CreateCapsule = U.CreateCapsule || (() => {
  throw new Error("Import MeshBuilder to populate this function");
});
U.ExtendToGoldberg = U.ExtendToGoldberg || (() => {
  throw new Error("Import MeshBuilder to populate this function");
});
var Ir = function(l, e, t) {
  for (var i in e)
    if (l.name === e[i])
      return t.push(l.id), !0;
  return l.parentId && t.indexOf(l.parentId) !== -1 ? (t.push(l.id), !0) : !1;
}, Qt = function(l, e) {
  return l + " of " + (e ? e.file + " from " + e.name + " version: " + e.version + ", exporter version: " + e.exporter_version : "unknown");
};
j.RegisterPlugin({
  name: "babylon.js",
  extensions: ".json",
  canDirectLoad: function(l) {
    return l.indexOf("json") !== -1, !0;
  },
  importMesh: function(l, e, t, i, s, r, n, a) {
    var o = "importMesh has failed JSON parse";
    try {
      var h = JSON.parse(t);
      h.physicsEnabled = !1, h == null || h.meshes.map((M) => delete M.physicsImpostor), o = "";
      var c = j.loggingLevel === j.DETAILED_LOGGING;
      l ? Array.isArray(l) || (l = [l]) : l = null;
      var u = new Array();
      if (h.meshes !== void 0 && h.meshes !== null) {
        var d, g;
        for (d = 0, g = h.meshes.length; d < g; d++) {
          var f = h.meshes[d];
          if (l === null || Ir(f, l, u)) {
            l !== null && delete l[l.indexOf(f.name)];
            var m = U.Parse(f, e, i);
            s.push(m), o += `
	Mesh ` + m.toString(c);
          }
        }
        var b;
        for (d = 0, g = e.meshes.length; d < g; d++)
          b = e.meshes[d], b._waitingParentId && (b.parent = e.getLastEntryByID(b._waitingParentId), b._waitingParentId = null), b.computeWorldMatrix(!0);
      }
      return !0;
    } catch (M) {
      var T = Qt("importMesh", h ? h.producer : "Unknown") + o;
      if (a)
        a(T, M);
      else
        throw S.Log(T), M;
    } finally {
      o !== null && j.loggingLevel !== j.NO_LOGGING && S.Log(Qt("importMesh", h ? h.producer : "Unknown") + (j.loggingLevel !== j.MINIMAL_LOGGING ? o : ""));
    }
    return !1;
  },
  load: function(l, e, t, i) {
    var s = "importScene has failed JSON parse";
    try {
      var r = JSON.parse(e);
      s = "", r.clearColor !== void 0 && r.clearColor !== null && (l.clearColor = Color4.FromArray(r.clearColor));
      var n = loadAssetContainer(l, e, t, i, !0);
      return !!n;
    } catch (o) {
      var a = Qt("importScene", r ? r.producer : "Unknown") + s;
      if (i)
        i(a, o);
      else
        throw S.Log(a), o;
    } finally {
      s !== null && j.loggingLevel !== j.NO_LOGGING && S.Log(Qt("importScene", r ? r.producer : "Unknown") + (j.loggingLevel !== j.MINIMAL_LOGGING ? s : ""));
    }
    return !1;
  },
  loadAssetContainer: function(l, e, t, i) {
    var s = loadAssetContainer(l, e, t, i);
    return s;
  }
});
U._instancedMeshFactory = (l, e) => {
  const t = new Cr(l, e);
  if (e.instancedBuffers) {
    t.instancedBuffers = {};
    for (const i in e.instancedBuffers)
      t.instancedBuffers[i] = e.instancedBuffers[i];
  }
  return t;
};
class Cr extends Ge {
  /**
   * Creates a new InstancedMesh object from the mesh source.
   * @param name defines the name of the instance
   * @param source the mesh to create the instance from
   */
  constructor(e, t) {
    super(e, t.getScene()), this._indexInSourceMeshInstanceArray = -1, this._distanceToCamera = 0, t.addInstance(this), this._sourceMesh = t, this._unIndexed = t._unIndexed, this.position.copyFrom(t.position), this.rotation.copyFrom(t.rotation), this.scaling.copyFrom(t.scaling), t.rotationQuaternion && (this.rotationQuaternion = t.rotationQuaternion.clone()), this.animations = t.animations.slice();
    for (const i of t.getAnimationRanges())
      i != null && this.createAnimationRange(i.name, i.from, i.to);
    this.infiniteDistance = t.infiniteDistance, this.setPivotMatrix(t.getPivotMatrix()), this.refreshBoundingInfo(!0, !0), this._syncSubMeshes();
  }
  /**
   * Returns the string "InstancedMesh".
   */
  getClassName() {
    return "InstancedMesh";
  }
  /** Gets the list of lights affecting that mesh */
  get lightSources() {
    return this._sourceMesh._lightSources;
  }
  _resyncLightSources() {
  }
  _resyncLightSource() {
  }
  _removeLightSource() {
  }
  // Methods
  /**
   * If the source mesh receives shadows
   */
  get receiveShadows() {
    return this._sourceMesh.receiveShadows;
  }
  set receiveShadows(e) {
    var t;
    ((t = this._sourceMesh) === null || t === void 0 ? void 0 : t.receiveShadows) !== e && k.Warn("Setting receiveShadows on an instanced mesh has no effect");
  }
  /**
   * The material of the source mesh
   */
  get material() {
    return this._sourceMesh.material;
  }
  set material(e) {
    var t;
    ((t = this._sourceMesh) === null || t === void 0 ? void 0 : t.material) !== e && k.Warn("Setting material on an instanced mesh has no effect");
  }
  /**
   * Visibility of the source mesh
   */
  get visibility() {
    return this._sourceMesh.visibility;
  }
  set visibility(e) {
    var t;
    ((t = this._sourceMesh) === null || t === void 0 ? void 0 : t.visibility) !== e && k.Warn("Setting visibility on an instanced mesh has no effect");
  }
  /**
   * Skeleton of the source mesh
   */
  get skeleton() {
    return this._sourceMesh.skeleton;
  }
  set skeleton(e) {
    var t;
    ((t = this._sourceMesh) === null || t === void 0 ? void 0 : t.skeleton) !== e && k.Warn("Setting skeleton on an instanced mesh has no effect");
  }
  /**
   * Rendering ground id of the source mesh
   */
  get renderingGroupId() {
    return this._sourceMesh.renderingGroupId;
  }
  set renderingGroupId(e) {
    !this._sourceMesh || e === this._sourceMesh.renderingGroupId || S.Warn("Note - setting renderingGroupId of an instanced mesh has no effect on the scene");
  }
  /**
   * Returns the total number of vertices (integer).
   */
  getTotalVertices() {
    return this._sourceMesh ? this._sourceMesh.getTotalVertices() : 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 this._sourceMesh.getTotalIndices();
  }
  /**
   * The source mesh of the instance
   */
  get sourceMesh() {
    return this._sourceMesh;
  }
  /**
   * 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(e) {
    return this._sourceMesh.createInstance(e);
  }
  /**
   * 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 {boolean} is it ready
   */
  isReady(e = !1) {
    return this._sourceMesh.isReady(e, !0);
  }
  /**
   * Returns an array of integers or a typed array (Int32Array, Uint32Array, Uint16Array) populated with the mesh indices.
   * @param kind kind of verticies to retrieve (eg. positions, normals, uvs, etc.)
   * @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 forcing the copy of the buffer no matter what the value of copyWhenShared is
   * @returns a float array or a Float32Array of the requested kind of data : positions, normals, uvs, etc.
   */
  getVerticesData(e, t, i) {
    return this._sourceMesh.getVerticesData(e, t, i);
  }
  /**
   * 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.
   * The `data` are either a numeric array either a Float32Array.
   * The parameter `updatable` is passed as is to the underlying Geometry object constructor (if initially none) or updater.
   * The parameter `stride` is an optional positive integer, it is usually automatically deducted from the `kind` (3 for positions or normals, 2 for UV, etc).
   * 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.
   *
   * 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
   *
   * Returns the Mesh.
   * @param kind
   * @param data
   * @param updatable
   * @param stride
   */
  setVerticesData(e, t, i, s) {
    return this.sourceMesh && this.sourceMesh.setVerticesData(e, t, i, s), this.sourceMesh;
  }
  /**
   * 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.
   * The `data` are either a numeric array either a Float32Array.
   * No new underlying VertexBuffer object is created.
   * If the `kind` is the `PositionKind` and if `updateExtends` is true, the mesh BoundingInfo is renewed, so the bounding box and sphere, and the mesh World Matrix is recomputed.
   * If the parameter `makeItUnique` is true, a new global geometry is created from this positions and is set to the mesh.
   *
   * 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
   *
   * Returns the Mesh.
   * @param kind
   * @param data
   * @param updateExtends
   * @param makeItUnique
   */
  updateVerticesData(e, t, i, s) {
    return this.sourceMesh && this.sourceMesh.updateVerticesData(e, t, i, s), this.sourceMesh;
  }
  /**
   * Sets the mesh indices.
   * Expects an array populated with integers or a typed array (Int32Array, Uint32Array, Uint16Array).
   * If the mesh has no geometry, a new Geometry object is created and set to the mesh.
   * This method creates a new index buffer each call.
   * Returns the Mesh.
   * @param indices
   * @param totalVertices
   */
  setIndices(e, t = null) {
    return this.sourceMesh && this.sourceMesh.setIndices(e, t), this.sourceMesh;
  }
  /**
   * Boolean : True if the mesh owns the requested kind of data.
   * @param kind
   */
  isVerticesDataPresent(e) {
    return this._sourceMesh.isVerticesDataPresent(e);
  }
  /**
   * Returns an array of indices (IndicesArray).
   */
  getIndices() {
    return this._sourceMesh.getIndices();
  }
  get _positions() {
    return this._sourceMesh._positions;
  }
  /**
   * 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 applySkeleton defines whether to apply the skeleton before computing the bounding info
   * @param applyMorph  defines whether to apply the morph target before computing the bounding info
   * @returns the current mesh
   */
  refreshBoundingInfo(e = !1, t = !1) {
    if (this.hasBoundingInfo && this.getBoundingInfo().isLocked)
      return this;
    const i = this._sourceMesh.geometry ? this._sourceMesh.geometry.boundingBias : null;
    return this._refreshBoundingInfo(this._sourceMesh._getPositionData(e, t), i), this;
  }
  /** @internal */
  _preActivate() {
    return this._currentLOD && this._currentLOD._preActivate(), this;
  }
  /**
   * @internal
   */
  _activate(e, t) {
    if (super._activate(e, t), this._sourceMesh.subMeshes || S.Warn("Instances should only be created for meshes with geometry."), this._currentLOD) {
      if (this._currentLOD._getWorldMatrixDeterminant() >= 0 != this._getWorldMatrixDeterminant() >= 0)
        return this._internalAbstractMeshDataInfo._actAsRegularMesh = !0, !0;
      if (this._internalAbstractMeshDataInfo._actAsRegularMesh = !1, this._currentLOD._registerInstanceForRenderId(this, e), t) {
        if (!this._currentLOD._internalAbstractMeshDataInfo._isActiveIntermediate)
          return this._currentLOD._internalAbstractMeshDataInfo._onlyForInstancesIntermediate = !0, !0;
      } else if (!this._currentLOD._internalAbstractMeshDataInfo._isActive)
        return this._currentLOD._internalAbstractMeshDataInfo._onlyForInstances = !0, !0;
    }
    return !1;
  }
  /** @internal */
  _postActivate() {
    this._sourceMesh.edgesShareWithInstances && this._sourceMesh._edgesRenderer && this._sourceMesh._edgesRenderer.isEnabled && this._sourceMesh._renderingGroup ? (this._sourceMesh._renderingGroup._edgesRenderers.pushNoDuplicate(this._sourceMesh._edgesRenderer), this._sourceMesh._edgesRenderer.customInstances.push(this.getWorldMatrix())) : this._edgesRenderer && this._edgesRenderer.isEnabled && this._sourceMesh._renderingGroup && this._sourceMesh._renderingGroup._edgesRenderers.push(this._edgesRenderer);
  }
  getWorldMatrix() {
    if (this._currentLOD && this._currentLOD.billboardMode !== z.BILLBOARDMODE_NONE && this._currentLOD._masterMesh !== this) {
      this._billboardWorldMatrix || (this._billboardWorldMatrix = new R());
      const e = this._currentLOD._masterMesh;
      return this._currentLOD._masterMesh = this, C.Vector3[7].copyFrom(this._currentLOD.position), this._currentLOD.position.set(0, 0, 0), this._billboardWorldMatrix.copyFrom(this._currentLOD.computeWorldMatrix(!0)), this._currentLOD.position.copyFrom(C.Vector3[7]), this._currentLOD._masterMesh = e, this._billboardWorldMatrix;
    }
    return super.getWorldMatrix();
  }
  get isAnInstance() {
    return !0;
  }
  /**
   * Returns the current associated LOD AbstractMesh.
   * @param camera
   */
  getLOD(e) {
    if (!e)
      return this;
    const t = this.sourceMesh.getLODLevels();
    if (!t || t.length === 0)
      this._currentLOD = this.sourceMesh;
    else {
      const i = this.getBoundingInfo();
      this._currentLOD = this.sourceMesh.getLOD(e, i.boundingSphere);
    }
    return this._currentLOD;
  }
  /**
   * @internal
   */
  _preActivateForIntermediateRendering(e) {
    return this.sourceMesh._preActivateForIntermediateRendering(e);
  }
  /** @internal */
  _syncSubMeshes() {
    if (this.releaseSubMeshes(), this._sourceMesh.subMeshes)
      for (let e = 0; e < this._sourceMesh.subMeshes.length; e++)
        this._sourceMesh.subMeshes[e].clone(this, this._sourceMesh);
    return this;
  }
  /** @internal */
  _generatePointsArray() {
    return this._sourceMesh._generatePointsArray();
  }
  /** @internal */
  _updateBoundingInfo() {
    return this.hasBoundingInfo ? this.getBoundingInfo().update(this.worldMatrixFromCache) : this.buildBoundingInfo(this.absolutePosition, this.absolutePosition, this.worldMatrixFromCache), this._updateSubMeshesBoundingInfo(this.worldMatrixFromCache), this;
  }
  /**
   * Creates a new InstancedMesh from the current mesh.
   *
   * Returns the clone.
   * @param name the cloned mesh name
   * @param newParent the optional Node to parent the clone to.
   * @param doNotCloneChildren if `true` the model children aren't cloned.
   * @param newSourceMesh if set this mesh will be used as the source mesh instead of ths instance's one
   * @returns the clone
   */
  clone(e, t = null, i, s) {
    const r = (s || this._sourceMesh).createInstance(e);
    if (Ci.DeepCopy(this, r, [
      "name",
      "subMeshes",
      "uniqueId",
      "parent",
      "lightSources",
      "receiveShadows",
      "material",
      "visibility",
      "skeleton",
      "sourceMesh",
      "isAnInstance",
      "facetNb",
      "isFacetDataEnabled",
      "isBlocked",
      "useBones",
      "hasInstances",
      "collider",
      "edgesRenderer",
      "forward",
      "up",
      "right",
      "absolutePosition",
      "absoluteScaling",
      "absoluteRotationQuaternion",
      "isWorldMatrixFrozen",
      "nonUniformScaling",
      "behaviors",
      "worldMatrixFromCache",
      "hasThinInstances",
      "hasBoundingInfo"
    ], []), this.refreshBoundingInfo(), t && (r.parent = t), !i)
      for (let n = 0; n < this.getScene().meshes.length; n++) {
        const a = this.getScene().meshes[n];
        a.parent === this && a.clone(a.name, r);
      }
    return r.computeWorldMatrix(!0), this.onClonedObservable.notifyObservers(r), r;
  }
  /**
   * Disposes the InstancedMesh.
   * Returns nothing.
   * @param doNotRecurse
   * @param disposeMaterialAndTextures
   */
  dispose(e, t = !1) {
    this._sourceMesh.removeInstance(this), super.dispose(e, t);
  }
  /**
   * @internal
   */
  _serializeAsParent(e) {
    super._serializeAsParent(e), e.parentId = this._sourceMesh.uniqueId, e.parentInstanceIndex = this._indexInSourceMeshInstanceArray;
  }
  /**
   * 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 options.newSourcedMesh newSourcedMesh the new source mesh for the instance (or clone)
   * @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(e = null, t, i) {
    const s = this.clone("Clone of " + (this.name || this.id), e || this.parent, !0, t && t.newSourcedMesh);
    s && i && i(this, s);
    for (const r of this.getChildTransformNodes(!0))
      r.instantiateHierarchy(s, t, i);
    return s;
  }
}
U.prototype.registerInstancedBuffer = function(l, e) {
  var t, i;
  if ((i = (t = this._userInstancedBuffersStorage) === null || t === void 0 ? void 0 : t.vertexBuffers[l]) === null || i === void 0 || i.dispose(), !this.instancedBuffers) {
    this.instancedBuffers = {};
    for (const s of this.instances)
      s.instancedBuffers = {};
    this._userInstancedBuffersStorage || (this._userInstancedBuffersStorage = {
      data: {},
      vertexBuffers: {},
      strides: {},
      sizes: {},
      vertexArrayObjects: this.getEngine().getCaps().vertexArrayObject ? {} : void 0
    });
  }
  this.instancedBuffers[l] = null, this._userInstancedBuffersStorage.strides[l] = e, this._userInstancedBuffersStorage.sizes[l] = e * 32, this._userInstancedBuffersStorage.data[l] = new Float32Array(this._userInstancedBuffersStorage.sizes[l]), this._userInstancedBuffersStorage.vertexBuffers[l] = new _(this.getEngine(), this._userInstancedBuffersStorage.data[l], l, !0, !1, e, !0);
  for (const s of this.instances)
    s.instancedBuffers[l] = null;
  this._invalidateInstanceVertexArrayObject(), this._markSubMeshesAsAttributesDirty();
};
U.prototype._processInstancedBuffers = function(l, e) {
  const t = l ? l.length : 0;
  for (const i in this.instancedBuffers) {
    let s = this._userInstancedBuffersStorage.sizes[i];
    const r = this._userInstancedBuffersStorage.strides[i], n = (t + 1) * r;
    for (; s < n; )
      s *= 2;
    this._userInstancedBuffersStorage.data[i].length != s && (this._userInstancedBuffersStorage.data[i] = new Float32Array(s), this._userInstancedBuffersStorage.sizes[i] = s, this._userInstancedBuffersStorage.vertexBuffers[i] && (this._userInstancedBuffersStorage.vertexBuffers[i].dispose(), this._userInstancedBuffersStorage.vertexBuffers[i] = null));
    const a = this._userInstancedBuffersStorage.data[i];
    let o = 0;
    if (e) {
      const h = this.instancedBuffers[i];
      h.toArray ? h.toArray(a, o) : h.copyToArray ? h.copyToArray(a, o) : a[o] = h, o += r;
    }
    for (let h = 0; h < t; h++) {
      const u = l[h].instancedBuffers[i];
      u.toArray ? u.toArray(a, o) : u.copyToArray ? u.copyToArray(a, o) : a[o] = u, o += r;
    }
    this._userInstancedBuffersStorage.vertexBuffers[i] ? this._userInstancedBuffersStorage.vertexBuffers[i].updateDirectly(a, 0) : (this._userInstancedBuffersStorage.vertexBuffers[i] = new _(this.getEngine(), this._userInstancedBuffersStorage.data[i], i, !0, !1, r, !0), this._invalidateInstanceVertexArrayObject());
  }
};
U.prototype._invalidateInstanceVertexArrayObject = function() {
  if (!(!this._userInstancedBuffersStorage || this._userInstancedBuffersStorage.vertexArrayObjects === void 0)) {
    for (const l in this._userInstancedBuffersStorage.vertexArrayObjects)
      this.getEngine().releaseVertexArrayObject(this._userInstancedBuffersStorage.vertexArrayObjects[l]);
    this._userInstancedBuffersStorage.vertexArrayObjects = {};
  }
};
U.prototype._disposeInstanceSpecificData = function() {
  for (this._instanceDataStorage.instancesBuffer && (this._instanceDataStorage.instancesBuffer.dispose(), this._instanceDataStorage.instancesBuffer = null); this.instances.length; )
    this.instances[0].dispose();
  for (const l in this.instancedBuffers)
    this._userInstancedBuffersStorage.vertexBuffers[l] && this._userInstancedBuffersStorage.vertexBuffers[l].dispose();
  this._invalidateInstanceVertexArrayObject(), this.instancedBuffers = {};
};
const Pr = {
  assetPath: "",
  enableShadows: !1,
  groupId: null,
  id: null,
  lights: [],
  rollId: null,
  scene: null
}, Ze = class Ze {
  constructor(e, t) {
    // mesh = null
    Ut(this, "value", 0);
    Ut(this, "asleep", !1);
    this.config = { ...Pr, ...e }, this.id = this.config.id !== void 0 ? this.config.id : Date.now(), this.sides = this.config.sides, this.dieType = this.config.dieType, this.comboKey = `${this.config.theme}_${this.config.dieType}`, this.scene = t, this.createInstance();
  }
  createInstance() {
    const e = `${this.config.meshName}_${this.dieType}_${this.config.theme}${this.config.colorSuffix}`, t = `${e}-instance-${this.id}`, i = this.scene.getMeshByName(e), s = i.createInstance(t);
    if (this.config.colorSuffix.length > 0) {
      const r = te.FromHexString(this.config.themeColor);
      s.instancedBuffers.customColor = r;
    }
    s.metadata = i.metadata, s.position.y = -100, s.scaling = new p(
      s.scaling.x * this.config.scale,
      s.scaling.y * this.config.scale,
      s.scaling.z * this.config.scale
    ), this.config.enableShadows && this.config.lights.directional.shadowGenerator.addShadowCaster(s), this.mesh = s;
  }
  // TODO: add themeOptions for colored materials, must ensure theme and themeOptions are unique somehow
  static async loadDie(e, t) {
    const { sides: i, theme: s = "default", meshName: r, colorSuffix: n } = e;
    e.dieType || (e.dieType = Number.isInteger(i) ? `d${i}` : i);
    const a = r + "_" + e.dieType, o = a + "_" + s + n;
    let h = t.getMeshByName(o);
    return h || (h = t.getMeshByName(a).clone(o)), h.material || (h.material = t.getMaterialByName(s + n), n.length > 0 && h.registerInstancedBuffer("customColor", 3)), e;
  }
  // load all the dice models
  static async loadModels(e, t) {
    const { meshFilePath: i, meshName: s, scale: r, d4FaceDown: n = !0 } = e;
    let a = !1, o = !1;
    const h = await fetch(`${i}`).then((c) => {
      if (c.ok) {
        const u = c.headers.get("content-type");
        if (u && u.indexOf("application/json") !== -1)
          return c.json();
        if (c.type && c.type === "basic")
          return c.json();
        throw new Error(`Incorrect contentType: ${u}. Expected "application/json" or "basic"`);
      } else
        throw new Error(`Unable to load 3D mesh file: '${i}'. Request rejected with status ${c.status}: ${c.statusText}`);
    }).catch((c) => console.error(c));
    if (h)
      return j.ImportMeshAsync(null, null, "data:" + JSON.stringify(h), t).then((c) => {
        if (c.meshes.forEach((u) => {
          u.name === "__root__" && u.dispose(), u.name.includes("collider") && (u.scaling = new p(
            u.scaling.x * 0.9,
            u.scaling.y * 0.9,
            u.scaling.z * 0.9
          )), a || (a = u.name === "d100"), o || (o = u.name === "d10"), u.setEnabled(!1), u.freezeNormals(), u.freezeWorldMatrix(), u.isPickable = !1, u.doNotSyncBoundingInfo = !0, u.name = s + "_" + u.name, u.metadata = {
            baseScale: u.scaling
          };
        }), !a && o && (t.getMeshByName(s + "_d10").clone(s + "_d100"), t.getMeshByName(s + "_d10_collider").clone(s + "_d100_collider"), h.colliderFaceMap && (h.colliderFaceMap.d100 = Ts(h.colliderFaceMap.d10), Object.values(h.colliderFaceMap.d100).forEach((u, d) => {
          h.colliderFaceMap.d100[d] = u * (u === 10 ? 0 : 10);
        }))), !h.colliderFaceMap)
          throw new Error(`'colliderFaceMap' data not found in ${i}. Without the colliderFaceMap data dice values can not be resolved.`);
        t.themeData[s] = {}, t.themeData[s].colliderFaceMap = h.colliderFaceMap, t.themeData[s].d4FaceDown = n;
      }).catch((c) => console.error(c)), h.meshes.filter((c) => c.name.includes("collider"));
  }
  updateConfig(e) {
    this.config = { ...this.config, ...e };
  }
  static setVector3(e, t, i) {
    return Ze.vector3.set(e, t, i);
  }
  static getVector3() {
    return Ze.vector3;
  }
  static async getRollResult(e, t) {
    const i = (s = e) => new Promise((r, n) => {
      const a = e.config.parentMesh || e.config.meshName, o = t.themeData[a].colliderFaceMap, h = t.themeData[a].d4FaceDown;
      if (!o[s.dieType])
        throw new Error(`No colliderFaceMap data for ${s.dieType}`);
      const c = t.getMeshByName(`${a}_${s.dieType}_collider`).createInstance(`${a}_${s.dieType}-hitbox-${s.id}`);
      c.isPickable = !0, c.isVisible = !0, c.setEnabled(!0), c.position = s.mesh.position, c.rotationQuaternion = s.mesh.rotationQuaternion;
      let u = Ze.setVector3(0, 1, 0);
      s.dieType === "d4" && h && (u = Ze.setVector3(0, -1, 0)), Ze.ray.direction = u, Ze.ray.origin = e.mesh.position;
      const d = t.pickWithRay(Ze.ray);
      return c.dispose(), s.value = o[s.dieType][d.faceId], s.value === void 0 && (console.error(`colliderFaceMap Error: No value found for ${s.dieType} mesh face ${d.faceId}`), s.value = 0), r(s.value);
    }).catch((r) => console.error(r));
    return e.mesh ? await i() : e.value;
  }
};
Ut(Ze, "ray", new ie(p.Zero(), p.Zero(), 1)), Ut(Ze, "vector3", p.Zero());
let is = Ze;
export {
  Br as $,
  ci as A,
  Pi as B,
  Oe as C,
  is as D,
  P as E,
  Be as F,
  ii as G,
  k as H,
  $t as I,
  $s as J,
  Se as K,
  me as L,
  U as M,
  Ne as N,
  w as O,
  $e as P,
  X as Q,
  Ys as R,
  Q as S,
  C as T,
  O as U,
  p as V,
  Gi as W,
  sr as X,
  We as Y,
  Ce as Z,
  F as _,
  J as a,
  Bt as a0,
  kr as a1,
  Nr as a2,
  Ur as a3,
  qe as a4,
  Li as a5,
  K as a6,
  q as a7,
  de as a8,
  I as a9,
  mt as aa,
  ae as ab,
  Or as ac,
  z as ad,
  R as b,
  Z as c,
  le as d,
  ye as e,
  B as f,
  Lr as g,
  te as h,
  us as i,
  he as j,
  wr as k,
  Fr as l,
  tr as m,
  Rt as n,
  ns as o,
  vs as p,
  Y as q,
  dt as r,
  Ht as s,
  De as t,
  se as u,
  It as v,
  S as w,
  ge as x,
  oi as y,
  _ as z
};
//# sourceMappingURL=Dice.js.map
