const pc = window.pc;
import { HardwareType as S, OsType as b, XrHeadsetType as R, ScreenOrientationType as A, BillboardAxisAlignment as k } from "./types.mjs";
import { resolveAssetPath as Y, getViverseConfig as I } from "./config.mjs";
const J = (n, t, e) => {
  n[t] = e;
}, Ft = (n, t, e) => {
  n[t] = e;
};
function tt(n) {
  return n && n.__esModule && Object.prototype.hasOwnProperty.call(n, "default") ? n.default : n;
}
var O = { exports: {} }, B;
function et() {
  return B || (B = 1, (function(n) {
    var t = Object.prototype.hasOwnProperty, e = "~";
    function i() {
    }
    Object.create && (i.prototype = /* @__PURE__ */ Object.create(null), new i().__proto__ || (e = !1));
    function s(h, a, c) {
      this.fn = h, this.context = a, this.once = c || !1;
    }
    function r(h, a, c, p, d) {
      if (typeof c != "function")
        throw new TypeError("The listener must be a function");
      var g = new s(c, p || h, d), _ = e ? e + a : a;
      return h._events[_] ? h._events[_].fn ? h._events[_] = [h._events[_], g] : h._events[_].push(g) : (h._events[_] = g, h._eventsCount++), h;
    }
    function o(h, a) {
      --h._eventsCount === 0 ? h._events = new i() : delete h._events[a];
    }
    function l() {
      this._events = new i(), this._eventsCount = 0;
    }
    l.prototype.eventNames = function() {
      var a = [], c, p;
      if (this._eventsCount === 0) return a;
      for (p in c = this._events)
        t.call(c, p) && a.push(e ? p.slice(1) : p);
      return Object.getOwnPropertySymbols ? a.concat(Object.getOwnPropertySymbols(c)) : a;
    }, l.prototype.listeners = function(a) {
      var c = e ? e + a : a, p = this._events[c];
      if (!p) return [];
      if (p.fn) return [p.fn];
      for (var d = 0, g = p.length, _ = new Array(g); d < g; d++)
        _[d] = p[d].fn;
      return _;
    }, l.prototype.listenerCount = function(a) {
      var c = e ? e + a : a, p = this._events[c];
      return p ? p.fn ? 1 : p.length : 0;
    }, l.prototype.emit = function(a, c, p, d, g, _) {
      var m = e ? e + a : a;
      if (!this._events[m]) return !1;
      var u = this._events[m], y = arguments.length, E, f;
      if (u.fn) {
        switch (u.once && this.removeListener(a, u.fn, void 0, !0), y) {
          case 1:
            return u.fn.call(u.context), !0;
          case 2:
            return u.fn.call(u.context, c), !0;
          case 3:
            return u.fn.call(u.context, c, p), !0;
          case 4:
            return u.fn.call(u.context, c, p, d), !0;
          case 5:
            return u.fn.call(u.context, c, p, d, g), !0;
          case 6:
            return u.fn.call(u.context, c, p, d, g, _), !0;
        }
        for (f = 1, E = new Array(y - 1); f < y; f++)
          E[f - 1] = arguments[f];
        u.fn.apply(u.context, E);
      } else {
        var Q = u.length, T;
        for (f = 0; f < Q; f++)
          switch (u[f].once && this.removeListener(a, u[f].fn, void 0, !0), y) {
            case 1:
              u[f].fn.call(u[f].context);
              break;
            case 2:
              u[f].fn.call(u[f].context, c);
              break;
            case 3:
              u[f].fn.call(u[f].context, c, p);
              break;
            case 4:
              u[f].fn.call(u[f].context, c, p, d);
              break;
            default:
              if (!E) for (T = 1, E = new Array(y - 1); T < y; T++)
                E[T - 1] = arguments[T];
              u[f].fn.apply(u[f].context, E);
          }
      }
      return !0;
    }, l.prototype.on = function(a, c, p) {
      return r(this, a, c, p, !1);
    }, l.prototype.once = function(a, c, p) {
      return r(this, a, c, p, !0);
    }, l.prototype.removeListener = function(a, c, p, d) {
      var g = e ? e + a : a;
      if (!this._events[g]) return this;
      if (!c)
        return o(this, g), this;
      var _ = this._events[g];
      if (_.fn)
        _.fn === c && (!d || _.once) && (!p || _.context === p) && o(this, g);
      else {
        for (var m = 0, u = [], y = _.length; m < y; m++)
          (_[m].fn !== c || d && !_[m].once || p && _[m].context !== p) && u.push(_[m]);
        u.length ? this._events[g] = u.length === 1 ? u[0] : u : o(this, g);
      }
      return this;
    }, l.prototype.removeAllListeners = function(a) {
      var c;
      return a ? (c = e ? e + a : a, this._events[c] && o(this, c)) : (this._events = new i(), this._eventsCount = 0), this;
    }, l.prototype.off = l.prototype.removeListener, l.prototype.addListener = l.prototype.on, l.prefixed = e, l.EventEmitter = l, n.exports = l;
  })(O)), O.exports;
}
var it = et();
const q = /* @__PURE__ */ tt(it), C = new URLSearchParams(location.search);
function Ut(n) {
  return C.get(n);
}
function $t(n, t) {
  C.set(n, t);
}
function Ht(n) {
  C.delete(n);
}
function x(n) {
  return C.has(n);
}
function Wt() {
  return C;
}
class st {
  _viverseApp;
  hardware;
  os;
  xrHeadset;
  _screenOrientation;
  constructor(t) {
    this._viverseApp = t, this.hardware = this._detectHardware(), this.os = this._detectOs(), this.xrHeadset = this._detectXrHeadset(), this._screenOrientation = this._detectScreenOrientation(), window.addEventListener("resize", this._onScreenResize.bind(this));
  }
  get screenOrientation() {
    return this._screenOrientation;
  }
  _detectHardware() {
    return this._isMobileVR() ? S.Headset : this._isMobile() ? S.Mobile : window.matchMedia("(pointer: fine)").matches ? S.Desktop : S.Unknown;
  }
  _detectOs() {
    return this._isIOS() ? b.Ios : this._isAndroid() ? b.Android : this._isMacOS() ? b.Macos : this._isWindows() ? b.Windows : this._isLinux() ? b.Linux : b.Unknown;
  }
  _detectXrHeadset() {
    return this._isVive() ? R.Vive : this._isVisionPro() ? R.VisionPro : this._isOculus() ? R.Oculus : null;
  }
  _detectScreenOrientation() {
    return window.screen && window.screen.orientation ? window.screen.orientation.angle === 0 || window.screen.orientation.angle === 180 ? A.Portrait : A.Landscape : window.innerWidth > window.innerHeight ? A.Landscape : A.Portrait;
  }
  _onScreenResize() {
    const t = this._detectScreenOrientation();
    this._screenOrientation !== t && (this._screenOrientation = t, this._viverseApp.emit("device-info:orientation-changed", this._screenOrientation));
  }
  /**
   * VR Browser Detection
   */
  _isOculusBrowser() {
    return /(OculusBrowser)/i.test(window.navigator.userAgent);
  }
  _isViveBrowser() {
    return /(VIVEBrowser)/i.test(window.navigator.userAgent);
  }
  _isFirefoxReality() {
    return /(Mobile VR)/i.test(window.navigator.userAgent);
  }
  // VR Device Detection
  _isVive() {
    return this._isViveBrowser() || this._isFirefoxReality();
  }
  _isOculus() {
    return this._isOculusBrowser() && !this._isViveBrowser();
  }
  _isVisionPro() {
    return window.navigator.userAgent.includes("iPad") && "xr" in window.navigator;
  }
  _isTablet() {
    const t = window.navigator.userAgent;
    return /ipad|Nexus (7|9)|xoom|sch-i800|playbook|tablet|kindle/i.test(t);
  }
  _isR7() {
    return /R7 Build/.test(window.navigator.userAgent);
  }
  /**
   * Operating System Detection
   */
  _isIOS() {
    const t = navigator.userAgent.includes("Macintosh") && "ontouchend" in document;
    return /iPad|iPhone|iPod/.test(window.navigator.userAgent) || t;
  }
  _isLinux() {
    return /Linux|X11|Ubuntu|Fedora|Debian|CentOS|RedHat/i.test(window.navigator.userAgent);
  }
  _isWindows() {
    const t = window.navigator.userAgent, e = window.navigator.platform;
    return /Windows/i.test(t) || /Win32|Win64/i.test(e);
  }
  _isAndroid() {
    return /Android/.test(window.navigator.userAgent);
  }
  _isMacOS() {
    return /Macintosh|MacIntel|MacPPC|Mac68K/i.test(window.navigator.userAgent);
  }
  // private _isMobileApp(): boolean {
  //   return window.navigator.userAgent.indexOf('ViverseApp') > -1;
  // }
  _isMobileVR() {
    return x("forceVR") || this._isFirefoxReality() || this._isOculusBrowser() || this._isViveBrowser() || this._isVisionPro();
  }
  _isMobile() {
    const t = window.navigator.userAgent;
    let e = !1;
    return (/(android|bb\d+|meego).+mobile|avantgo|bada\/|blackberry|blazer|compal|elaine|fennec|hiptop|iemobile|ip(hone|od)|iris|kindle|lge |maemo|midp|mmp|mobile.+firefox|netfront|opera m(ob|in)i|palm( os)?|phone|p(ixi|re)\/|plucker|pocket|psp|series(4|6)0|symbian|treo|up\.(browser|link)|vodafone|wap|windows ce|xda|xiino/i.test(
      t
    ) || /1207|6310|6590|3gso|4thp|50[1-6]i|770s|802s|a wa|abac|ac(er|oo|s-)|ai(ko|rn)|al(av|ca|co)|amoi|an(ex|ny|yw)|aptu|ar(ch|go)|as(te|us)|attw|au(di|-m|r |s )|avan|be(ck|ll|nq)|bi(lb|rd)|bl(ac|az)|br(e|v)w|bumb|bw-(n|u)|c55\/|capi|ccwa|cdm-|cell|chtm|cldc|cmd-|co(mp|nd)|craw|da(it|ll|ng)|dbte|dc-s|devi|dica|dmob|do(c|p)o|ds(12|-d)|el(49|ai)|em(l2|ul)|er(ic|k0)|esl8|ez([4-7]0|os|wa|ze)|fetc|fly(-|_)|g1 u|g560|gene|gf-5|g-mo|go(\.w|od)|gr(ad|un)|haie|hcit|hd-(m|p|t)|hei-|hi(pt|ta)|hp( i|ip)|hs-c|ht(c(-| |_|a|g|p|s|t)|tp)|hu(aw|tc)|i-(20|go|ma)|i230|iac( |-|\/)|ibro|idea|ig01|ikom|im1k|inno|ipaq|iris|ja(t|v)a|jbro|jemu|jigs|kddi|keji|kgt( |\/)|klon|kpt |kwc-|kyo(c|k)|le(no|xi)|lg( g|\/(k|l|u)|50|54|-[a-w])|libw|lynx|m1-w|m3ga|m50\/|ma(te|ui|xo)|mc(01|21|ca)|m-cr|me(rc|ri)|mi(o8|oa|ts)|mmef|mo(01|02|bi|de|do|t(-| |o|v)|zz)|mt(50|p1|v )|mwbp|mywa|n10[0-2]|n20[2-3]|n30(0|2)|n50(0|2|5)|n7(0(0|1)|10)|ne((c|m)-|on|tf|wf|wg|wt)|nok(6|i)|nzph|o2im|op(ti|wv)|oran|owg1|p800|pan(a|d|t)|pdxg|pg(13|-([1-8]|c))|phil|pire|pl(ay|uc)|pn-2|po(ck|rt|se)|prox|psio|pt-g|qa-a|qc(07|12|21|32|60|-[2-7]|i-)|qtek|r380|r600|raks|rim9|ro(ve|zo)|s55\/|sa(ge|ma|mm|ms|ny|va)|sc(01|h-|oo|p-)|sdk\/|se(c(-|0|1)|47|mc|nd|ri)|sgh-|shar|sie(-|m)|sk-0|sl(45|id)|sm(al|ar|b3|it|t5)|so(ft|ny)|sp(01|h-|v-|v )|sy(01|mb)|t2(18|50)|t6(00|10|18)|ta(gt|lk)|tcl-|tdg-|tel(i|m)|tim-|t-mo|to(pl|sh)|ts(70|m-|m3|m5)|tx-9|up(\.b|g1|si)|utst|v400|v750|veri|vi(rg|te)|vk(40|5[0-3]|-v)|vm40|voda|vulc|vx(52|53|60|61|70|80|81|83|85|98)|w3c(-| )|webc|whit|wi(g |nc|nw)|wmlb|wonu|x700|yas-|your|zeto|zte-/i.test(
      t.substr(0, 4)
    )) && (e = !0), (this._isIOS() || this._isTablet() || this._isR7()) && (e = !0), e;
  }
}
const z = (n) => {
  let t;
  const e = /* @__PURE__ */ new Set(), i = (a, c) => {
    const p = typeof a == "function" ? a(t) : a;
    if (!Object.is(p, t)) {
      const d = t;
      t = c ?? (typeof p != "object" || p === null) ? p : Object.assign({}, t, p), e.forEach((g) => g(t, d));
    }
  }, s = () => t, l = { setState: i, getState: s, getInitialState: () => h, subscribe: (a) => (e.add(a), () => e.delete(a)) }, h = t = n(i, s, l);
  return l;
}, P = (n) => n ? z(n) : z, nt = (n) => (t, e, i) => {
  const s = i.subscribe;
  return i.subscribe = (o, l, h) => {
    let a = o;
    if (l) {
      const c = h?.equalityFn || Object.is;
      let p = o(i.getState());
      a = (d) => {
        const g = o(d);
        if (!c(p, g)) {
          const _ = p;
          l(p = g, _);
        }
      }, h?.fireImmediately && l(p, p);
    }
    return s(a);
  }, n(t, e, i);
}, V = nt, rt = () => P()(
  V((n) => ({
    setProfile: (t) => {
      n(() => ({ ...t }));
    }
  }))
), at = () => P()(
  V((n) => ({
    isArSupported: !1,
    isVrSupported: !1,
    setArSupported: (t) => {
      n(() => ({ isArSupported: t }));
    },
    setVrSupported: (t) => {
      n(() => ({ isVrSupported: t }));
    }
  }))
), ot = () => P()(
  V((n) => ({
    vrmMtoonShading: !0,
    setPreference: (t) => {
      n(() => ({ ...t }));
    }
  }))
);
class ct {
  _messageType = "player";
  _viverseApp;
  _store;
  _unsubscribes = [];
  _syncInterval = 3e3;
  _lastSyncTime = 0;
  constructor(t, e) {
    this._viverseApp = t, this._store = e, this._subscribeToStore();
  }
  _subscribeToStore() {
    this._unsubscribes.push(
      this._store.subscribe(
        (t) => t.displayName,
        () => this._send()
      )
    ), this._unsubscribes.push(
      this._store.subscribe(
        (t) => t.snapshot,
        () => this._send()
      )
    ), this._unsubscribes.push(
      this._store.subscribe(
        (t) => t.fullBodySnapshot,
        () => this._send()
      )
    );
  }
  _isEmptyObject(t) {
    for (const e in t) return !1;
    return !0;
  }
  _send() {
    const t = this._gatherPayload();
    if (!t || this._isEmptyObject(t)) return;
    const e = {
      type: this._messageType,
      data: { profile: t }
    };
    this._viverseApp.emit("multiplayer:send-system-message", e);
  }
  _gatherPayload() {
    const { displayName: t, snapshot: e, fullBodySnapshot: i } = this._store.getState(), s = {};
    return t && (s.displayName = t), e && (s.snapshot = e), i && (s.fullBodySnapshot = i), Object.keys(s).length > 0 ? s : null;
  }
  update(t) {
    this._lastSyncTime += t * 1e3, this._lastSyncTime >= this._syncInterval && (this._lastSyncTime = 0, this._send());
  }
  destroy() {
    this._unsubscribes.forEach((t) => t()), this._unsubscribes = [];
  }
}
class lt {
  profile = rt();
  capability = at();
  preference = ot();
  _pcApp;
  _profileSender;
  constructor(t) {
    this._pcApp = t.pcApp, this._profileSender = new ct(t, this.profile), this._pcApp.on("update", this._update, this);
  }
  _update(t) {
    this._profileSender.update(t);
  }
  destroy() {
    this._profileSender.destroy(), this._pcApp.off("update", this._update, this);
  }
}
const ht = (n, t) => {
  const i = n.halfExtents, s = n.center.y - t.y, r = Math.max(s + i.y, i.y * 2), o = Math.min(i.z + 0.1, i.y / 2);
  return {
    capsuleHeight: r,
    capsuleRadius: o
  };
};
function Yt(n, t) {
  n.collision || n.addComponent("collision", {
    type: "capsule"
  });
  const e = n.getPosition(), { capsuleHeight: i, capsuleRadius: s } = ht(t, e);
  n.collision && (n.collision.height = i, n.collision.radius = s, n.collision.linearOffset = new pc.Vec3(0, i / 2, 0));
}
function qt(n, t) {
  return t = t || new pc.BoundingBox(), n.findComponents("render").forEach((i, s) => {
    i.meshInstances.forEach((o, l) => {
      s === 0 && l === 0 ? t.copy(o.aabb) : t.add(o.aabb);
    });
  }), t;
}
class pt {
  /** Whether logging is enabled */
  get canLog() {
    return x("debug");
  }
  /** Whether warning logs are enabled */
  get canWarn() {
    return !0;
  }
  /** Whether error logs are enabled */
  get canError() {
    return !0;
  }
  /** Whether info logs are enabled */
  get canInfo() {
    return x("debug");
  }
  /** Whether timing logs are enabled */
  get canTime() {
    return x("debug");
  }
  /** Whether timing end logs are enabled */
  get canTimeEnd() {
    return x("debug");
  }
  /**
   * Logs debug information to the console if enabled.
   * @param args - Arguments to log
   */
  log(...t) {
    this.canLog && console.log("VIVERSE DEBUGGER:", ...t);
  }
  /**
   * Logs a warning to the console.
   * @param args - Arguments to log
   */
  warn(...t) {
    this.canWarn && console.warn("VIVERSE DEBUGGER:", ...t);
  }
  /**
   * Logs an error to the console.
   * @param args - Arguments to log
   */
  error(...t) {
    this.canError && console.error("VIVERSE DEBUGGER:", ...t);
  }
  /**
   * Logs informational messages to the console if enabled.
   * @param args - Arguments to log
   */
  info(...t) {
    this.canInfo && console.info(...t);
  }
  /**
   * Starts a console timer with the given label if enabled.
   * @param args - Timer label
   */
  time(...t) {
    this.canTime && console.time(...t);
  }
  /**
   * Ends a console timer with the given label if enabled.
   * @param args - Timer label
   */
  timeEnd(...t) {
    this.canTimeEnd && console.timeEnd(...t);
  }
}
const v = new pt();
async function ut(n, t, e, i) {
  if (!n) throw new Error(`loadAsset: pcApp is required to load ${t}`);
  let s = n.assets.find(t, i);
  return s || (s = new pc.Asset(t, i, {
    url: e
  }), n.assets.add(s)), s.resource ? s : new Promise((r, o) => {
    s.ready(() => r(s)), s.once("load", () => r(s)), s.once("error", (l) => o(new Error(`Failed to load ${t}: ${l}`))), n.assets.load(s);
  });
}
async function j(n, t, e, i, s) {
  const r = Y(i, e + t);
  return ut(n, t, r, s);
}
async function jt(n, t, e, i = "") {
  if (!n) throw new Error(`loadFontAsset: pcApp is required to load ${t}`);
  let s = n.assets.find(t, "font");
  if (s) return s;
  const r = await j(n, `${t}.json`, e, i, "json");
  if (!r.resource)
    throw new Error(`loadFontAsset: Failed to load font data for ${t}`);
  return s = new pc.Asset(`${t}`, "font", {
    url: Y(i, `${e}${t}.png`)
  }), n.assets.add(s), s.data = r.resource, s;
}
function Xt(n, t) {
  return n.length !== t.length ? !1 : [...n].sort().every((e, i) => e === [...t].sort()[i]);
}
function Kt(n, t) {
  const e = [];
  return n.forEach((i) => {
    const s = t.get(i);
    s && e.push(s);
  }), e;
}
let F = 100;
function dt(n) {
  let t = F + 1;
  const e = n.scene.layers.layerList;
  for (; e.find((i) => i.id === t); )
    t++;
  return F = t, t;
}
function _t(n, t, e = {}) {
  const i = dt(n), s = new pc.Layer({
    id: i,
    name: t,
    ...e
  });
  return n.scene.layers.push(s), s;
}
function Zt(n, t, e = {}) {
  const i = n.scene.layers.getLayerByName(t);
  return i || _t(n, t, e);
}
class L {
  static _applications = /* @__PURE__ */ new Map();
  static _nameCounter = 0;
  static _defaultId = "";
  static setDefaultApplication(t) {
    this._defaultId = t;
  }
  static registerApplication(t) {
    this._nameCounter++;
    const e = `viverse-app-${this._nameCounter}`;
    return this._applications.size > 0 && v.warn(`Multiple applications registered. Default application is replaced with ${e}`), this.setDefaultApplication(e), this._applications.set(e, t), e;
  }
  static getApplication(t) {
    const e = t ?? this._defaultId;
    return this._applications.get(e) ?? null;
  }
  static unregisterApplication(t) {
    this._applications.delete(t);
  }
}
class gt {
  _viverseApp;
  _core = null;
  _playSdk = null;
  _loadPromise = null;
  _isLoaded = !1;
  constructor(t) {
    this._viverseApp = t;
  }
  get core() {
    return this._core;
  }
  get playSdk() {
    return this._playSdk;
  }
  get isLoaded() {
    return this._isLoaded;
  }
  _loadSdkScript() {
    return new Promise((t, e) => {
      if (window.viverse)
        return t();
      const { viverseSdkUrl: i } = I(), s = document.createElement("script");
      s.src = i, s.async = !0, s.onload = () => {
        v.log("VIVERSE SDK script loaded successfully."), t();
      }, s.onerror = () => {
        const r = "Failed to load VIVERSE SDK script.";
        v.error(r), e(new Error(r));
      }, document.head.appendChild(s);
    });
  }
  async _initialize() {
    await this._loadSdkScript();
    const t = window.viverse;
    return this._core = t, this._isLoaded = !0, t;
  }
  async load() {
    return this._core ? this._core : (this._loadPromise || (this._loadPromise = (async () => {
      const t = await this._initialize();
      return this._loadPromise = null, this._viverseApp.emit("sdk:script-loaded", t), t;
    })()), this._loadPromise);
  }
  createPlaySdk() {
    if (this._playSdk) return this._playSdk;
    if (!this._core)
      throw new Error("VIVERSE SDK core is not loaded.");
    const t = new this._core.play();
    return this._playSdk = t, t;
  }
  destroy() {
    this._isLoaded = !1, delete window.viverseAuthSdkClient;
  }
}
class Qt extends q {
  id;
  appId = null;
  pcApp;
  context;
  sdk;
  systems = {};
  deviceInfo;
  _options;
  constructor(t, e, i) {
    if (super(), !e || e.length === 0)
      throw new Error("ViverseApp systems are required.");
    this.pcApp = t, this.appId = i?.appId ?? null, this.deviceInfo = new st(this), this.context = new lt(this), this.id = L.registerApplication(this), this.sdk = new gt(this), this._options = {
      ...this._createDefaultOptions(),
      ...i
    }, this._setupTextureHandler(), this._setupContextState(), this._initSystems(e), this._bindListeners();
  }
  static getApplication(t) {
    return L.getApplication(t);
  }
  async start() {
    const t = [];
    for (const e in this.systems) {
      const i = e, s = this.systems[i];
      s && (s.dependencies && s.dependencies.forEach((r) => {
        if (!this.systems[r.name])
          throw new Error(
            `System ${e} depends on system ${r.name} which is not initialized. Reason: ${r.reason}`
          );
      }), t.push(
        Promise.resolve(s.start()).then(() => {
          this.emit("system:start", s.name, s);
        })
      ));
    }
    this.pcApp.fire("viverse-app:before-start", this), await Promise.all(t), this.emit("start"), this.pcApp.fire("viverse-app:start", this);
  }
  _createDefaultOptions() {
    return {
      disableContextMenu: !0,
      vrmMtoonShading: !0
    };
  }
  _initSystems(t) {
    t.forEach((e) => {
      const { System: i, name: s, options: r } = e;
      if (!i || typeof i != "function")
        throw new Error("System class is not specified or is not a valid constructor.");
      if (i.systemName !== s)
        throw new Error(`System class mismatch: expected ${s}, got ${i.systemName}`);
      const o = new i(this, r);
      J(this.systems, o.name, o), this.emit("system:added", o.name, o);
    });
  }
  _setXrSupportState(t, e) {
    t === "immersive-vr" ? this.context.capability.getState().setVrSupported(e) : t === "immersive-ar" && this.context.capability.getState().setArSupported(e);
  }
  _bindListeners() {
    this._bindXrSupportListener(), this._bindContextMenuListener();
  }
  _unbindListeners() {
    this._unbindXrSupportListener(), this._unbindContextMenuListener();
  }
  _bindXrSupportListener() {
    if (!(this.pcApp && this.pcApp.xr)) return;
    const { setArSupported: t, setVrSupported: e } = this.context.capability.getState();
    t(this.pcApp.xr.isAvailable("immersive-ar")), e(this.pcApp.xr.isAvailable("immersive-vr")), this.pcApp.xr.on("available", this._setXrSupportState, this);
  }
  _unbindXrSupportListener() {
    this.pcApp && this.pcApp.xr && this.pcApp.xr.off("available", this._setXrSupportState, this);
  }
  _bindContextMenuListener() {
    this._options.disableContextMenu && this.pcApp.graphicsDevice.canvas.addEventListener("contextmenu", this._onContextMenu);
  }
  _unbindContextMenuListener() {
    this._options.disableContextMenu && this.pcApp.graphicsDevice.canvas.removeEventListener("contextmenu", this._onContextMenu);
  }
  _onContextMenu(t) {
    t.preventDefault();
  }
  _setupTextureHandler() {
    const t = this.pcApp.loader.getHandler("texture");
    t && "crossOrigin" in t && (t.crossOrigin = "anonymous");
  }
  _setupContextState() {
    const { setPreference: t } = this.context.preference.getState();
    t({ vrmMtoonShading: this._options.vrmMtoonShading ?? !0 });
  }
  destroy() {
    L.unregisterApplication(this.id), this.context.destroy(), this._unbindListeners(), Object.values(this.systems).forEach((t) => {
      t.destroy && t.destroy(), delete this.systems[t.name];
    });
  }
}
class Jt {
  /**
   * The unique name of this module
   * @hidden
   */
  static moduleName;
  system;
  name;
  viverseApp;
  pcApp;
  constructor(t) {
    this.system = t, this.viverseApp = t.viverseApp, this.pcApp = t.pcApp, this.name = this.constructor.moduleName;
  }
}
class te extends q {
  /**
   * The unique name of this system
   * @hidden
   */
  static systemName;
  pcApp;
  viverseApp;
  name;
  dependencies = [];
  store;
  constructor(t) {
    if (super(), this.pcApp = t.pcApp, this.viverseApp = t, this.name = this.constructor.systemName, !this.pcApp)
      throw new Error("pcApp is not correctly set.");
    if (!this.viverseApp)
      throw new Error("ViverseApp is not initialized.");
  }
  /** @hidden */
  destroy() {
    this.removeAllListeners();
  }
}
const ft = async (n) => new Promise((t, e) => {
  const i = I(), s = `${i.viverseAvatarDomain}${n}`;
  if (!i.viverseAvatarDomain) {
    e(new Error("viverseAvatarDomain is not defined in the configuration."));
    return;
  }
  fetch(s).then((r) => r.json()).then((r) => {
    t(r);
  }).catch((r) => {
    e(r);
  });
}), mt = async () => await ft(
  '/items/publicAvatar?filter={"status":{"_eq":"published"}}'
), ee = async () => {
  const n = await mt(), t = Math.floor(Math.random() * n.data.length), e = n.data[t], s = I().viverseAvatarDomain;
  if (!s)
    throw new Error("viverseAvatarDomain is not defined in the configuration.");
  return {
    id: e.id,
    avatarUrl: `${s}/assets/${e.model}`,
    headIconUrl: `${s}/assets/${e.head_icon}`,
    snapshotUrl: `${s}/assets/${e.snapshot}`,
    gender: e.gender
  };
}, ie = () => `Guest ${((i) => (s) => [...Array(s)].reduce((r) => {
  const o = Math.floor(Math.random() * i.length);
  return r += i.charAt(o);
}, ""))("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789")(6)}`, se = (n) => {
  const t = n.systems.localPlayer?.playerEntity;
  return new Promise((e) => {
    t ? e(t) : n.once("player:ready", (i) => {
      e(i);
    });
  });
};
function ne(n, t, e = "FallbackGripBone") {
  const i = new pc.Entity(e);
  return i.reparent(n), yt(i, t), i;
}
function yt(n, t) {
  if (t) {
    const { y: e, z: i } = t.halfExtents;
    n.setLocalPosition(0, e, (i + 0.25) * -1);
  } else
    n.setLocalPosition(0, 1, 1);
}
class re extends pc.Script {
  static scriptName = "uvScroll";
  /**
   * @attribute
   * @title Speed
   * @description Animates material UV coordinates by scrolling them continuously at specified speed.
   * @type {pc.Vec2}
   */
  speed = new pc.Vec2(0.1, 0.1);
  _offset = new pc.Vec2();
  _materials = [];
  constructor(t) {
    super(t);
  }
  initialize() {
    this.entity.findComponents("render").forEach((e) => {
      e.material && this._materials.push(e.material), e.meshInstances.forEach((i) => {
        i.material && this._materials.push(i.material);
      });
    });
  }
  update(t) {
    this._offset.x += this.speed.x * t, this._offset.y += this.speed.y * t, this._offset.x = this._offset.x % 1, this._offset.y = this._offset.y % 1;
    const { x: e, y: i } = this._offset;
    this._materials.forEach((s) => {
      s instanceof pc.StandardMaterial && (s.diffuseDetailMapOffset.set(e, i), s.diffuseMapOffset.set(e, i), s.emissiveMapOffset.set(e, i), s.opacityMapOffset.set(e, i)), s.update();
    });
  }
}
class Et extends pc.Script {
  static scriptName = "billboard";
  /**
   * @attribute
   * @title Target Entity
   * @description The entity to which this billboard will look at.
   * Only one of `targetEntity` or `targetPosition` should be set.
   * If both are set, `targetEntity` will take precedence.
   * @type {pc.Entity}
   */
  targetEntity = null;
  /**
   * @attribute
   * @title Position Vector
   * @description The position vector to which this billboard will look at.
   * Only one of `targetEntity` or `targetPosition` should be set.
   * @type {pc.Vec3}
   */
  targetPosition = null;
  /**
   * @attribute
   * @title Axis Alignment
   * @description Which axes the billboard rotation should lock.
   * @type {BillboardAxisAlignment}
   */
  axisAlignment = k.None;
  /**
   * @attribute
   * @title RotateLocal
   * @description The local rotation of the billboard.
   * @type {pc.Vec3}
   */
  rotateLocal = null;
  _position = new pc.Vec3();
  _lookTarget = new pc.Vec3();
  constructor(t) {
    super(t), this.entity.on("billboard:set-target", this.setTargetEntity, this), this.on("destroy", () => {
      this.entity.off("billboard:set-target", this.setTargetEntity, this);
    });
  }
  initialize() {
  }
  /**
   * Sets the target entity for the billboard.
   * @param entity The entity to which this billboard will look at
   */
  setTargetEntity(t) {
    this.targetEntity = t;
  }
  _applyBillboard(t) {
    this._position.copy(this.entity.getPosition()), this.axisAlignment === k.X ? this._lookTarget.set(this._position.x, t.y, t.z) : this.axisAlignment === k.Y ? this._lookTarget.set(t.x, this._position.y, t.z) : this.axisAlignment === k.Z ? this._lookTarget.set(t.x, t.y, this._position.z) : this._lookTarget.copy(t), this.entity.lookAt(this._lookTarget), this.rotateLocal && this.entity.rotateLocal(this.rotateLocal);
  }
  update() {
    if (this.targetEntity) {
      this._applyBillboard(this.targetEntity.getPosition());
      return;
    }
    if (this.targetPosition) {
      this._applyBillboard(this.targetPosition);
      return;
    }
  }
}
class ae extends pc.Script {
  static scriptName = "entityStateEmitter";
  initialize() {
    this._handleStateChange(!0), this.on("state", this._handleStateChange, this);
  }
  _onEnabled() {
    this.entity.fire("state:enabled");
  }
  _onDisabled() {
    this.entity.fire("state:disabled");
  }
  _handleStateChange(t) {
    this.entity.fire("state:changed", t), t ? this._onEnabled() : this._onDisabled();
  }
}
class X extends pc.Script {
  static scriptName = "uiSpriteAnim";
  fps = 15;
  delay = 0;
  loop = !0;
  sizeRatio = 1;
  _frameCount = 0;
  _interval = 0;
  _timer = 0;
  _isComplete = !1;
  _pivot = new pc.Vec2(0.5, 0.5);
  initialize() {
    this._frameCount = this.entity.element?.sprite?.frameKeys.length ?? 0, this._interval = this.fps > 0 ? 1 / this.fps : 0, this.restart();
  }
  update(t) {
    if (this._isComplete || this._interval <= 0 || !this.entity.element?.sprite || (this._timer += t, this._timer <= this._interval)) return;
    let e = this.entity.element.spriteFrame + 1;
    if (e >= this._frameCount)
      if (this.loop)
        e = 0;
      else {
        this._isComplete = !0;
        return;
      }
    this._applyFrame(e), this._timer -= this._interval;
  }
  restart() {
    this._isComplete = !1, this._timer = -this.delay, this._applyFrame(0);
  }
  _applyFrame(t) {
    if (!this.entity.element?.sprite) return;
    this.entity.element.spriteFrame = t;
    const e = this.entity.element.sprite.frameKeys[t], s = this.entity.element.sprite.atlas.frames[e];
    s && (this.entity.element.width = s.rect.z * this.sizeRatio, this.entity.element.height = s.rect.w * this.sizeRatio, this.entity.element.pivot = this._pivot.copy(s.pivot));
  }
}
class vt {
  _conditions;
  constructor(t) {
    this._conditions = /* @__PURE__ */ new Map(), t && this.registerConditions(t);
  }
  registerConditions(t) {
    Object.entries(t).forEach(([e, i]) => {
      const s = e, r = i;
      this.registerCondition(s, r);
    });
  }
  registerCondition(t, e) {
    this._conditions.set(t, e), this._checkConditions();
  }
  deregisterCondition(t) {
    this._conditions.delete(t), this._checkConditions();
  }
  updateCondition(t, e) {
    this._conditions.set(t, e), this._checkConditions();
  }
  isPassed() {
    for (const t of this._conditions.values())
      if (!t) return !1;
    return !0;
  }
  triggerConditionsCheck() {
    this._checkConditions();
  }
  _checkConditions() {
    const t = this.isPassed();
    this.onConditionsUpdated(t);
  }
  clearConditions() {
    this._conditions.clear();
  }
}
const wt = 20, U = 0.05, bt = {
  nearClip: 0.1,
  smoothSpeed: 10,
  instantOpacityThreshold: 0.5
};
class oe {
  _config;
  _currentOpacity = 1;
  _expandedHalfExtents = new pc.Vec3();
  _cameraDiff = new pc.Vec3();
  _cachedRenderComponents = [];
  _lastCachedEntity = null;
  _avatar = null;
  _originalMaterials = /* @__PURE__ */ new WeakMap();
  _originalMeshInstanceMaterials = /* @__PURE__ */ new WeakMap();
  _clonedMaterials = /* @__PURE__ */ new Set();
  constructor(t) {
    this._config = {
      ...bt,
      ...t
    };
  }
  get currentOpacity() {
    return this._currentOpacity;
  }
  setAvatar(t) {
    this._reset();
    const e = this._avatar?.entity;
    e && this._unbindEntityEvents(e), this._avatar = t;
    const i = this._avatar.entity;
    if (!i)
      throw new Error("Avatar Entity must be activated and exist when setAvatar is called.");
    this._bindEntityEvents(i), this._applyOpacityToEntity(i, this._currentOpacity);
  }
  refreshMaterialCache(t) {
    const e = t.findComponents("render");
    this._cachedRenderComponents = e, this._lastCachedEntity = t;
    const i = new Set(this._clonedMaterials), s = (r, o) => {
      const l = r.material;
      if (!l) return;
      const h = this._clonedMaterials.has(l), a = o.get(r);
      h ? i.delete(l) : l !== a && o.set(r, l);
    };
    e.forEach((r) => {
      s(r, this._originalMaterials), r.meshInstances?.forEach((o) => {
        s(o, this._originalMeshInstanceMaterials);
      });
    }), i.forEach((r) => {
      r.destroy(), this._clonedMaterials.delete(r);
    }), this._applyOpacityToEntity(t, this._currentOpacity);
  }
  getOpacityFromDistance(t, e) {
    for (let i = 0; i <= wt; i++) {
      const s = i * U, r = 1 + i * U, o = this._expandedHalfExtents;
      o.copy(e.halfExtents).addScalar(this._config.nearClip * r);
      const l = this._cameraDiff;
      l.copy(t).sub(e.center);
      const h = Math.abs(l.x) <= o.x, a = Math.abs(l.y) <= o.y, c = Math.abs(l.z) <= o.z;
      if (h && a && c)
        return s;
    }
    return 1;
  }
  _applyOpacityToRenders(t, e) {
    const i = this._originalMaterials.get(t);
    i && this._applyOpacityToMaterial(t, i, e), t.meshInstances?.forEach((s) => {
      const r = this._originalMeshInstanceMaterials.get(s);
      r && this._applyOpacityToMaterial(s, r, e);
    });
  }
  _applyOpacityToMaterial(t, e, i) {
    if (i === 1) {
      this._restoreOriginalMaterial(t, e);
      return;
    }
    const s = this._getClonedMaterial(t, e);
    this._setOpacityDither(s, i);
  }
  _restoreOriginalMaterial(t, e) {
    const i = t.material;
    i !== e && (t.material = e, this._clonedMaterials.has(i) && (i.destroy(), this._clonedMaterials.delete(i)));
  }
  _getClonedMaterial(t, e) {
    const i = t.material;
    if (i !== e)
      return i;
    const s = e.clone();
    this._clonedMaterials.add(s), s.name = `${e.name}_OpacityClone`, s.defaultBlendType = e.blendType, s.defaultDepthWrite = e.depthWrite, s.defaultAlphaTest = e.alphaTest;
    const r = e instanceof pc.StandardMaterial ? e.opacity : 1;
    return s.defaultOpacity = r, t.material = s, s;
  }
  _reset() {
    this._clonedMaterials.forEach((t) => t.destroy()), this._clonedMaterials.clear(), this._originalMaterials = /* @__PURE__ */ new WeakMap(), this._originalMeshInstanceMaterials = /* @__PURE__ */ new WeakMap(), this._cachedRenderComponents = [], this._lastCachedEntity = null;
  }
  _bindEntityEvents(t) {
    t.on("vrm-mtoon:materials-changed", this._onMaterialsChanged, this);
  }
  _unbindEntityEvents(t) {
    t.off("vrm-mtoon:materials-changed", this._onMaterialsChanged, this);
  }
  _onMaterialsChanged() {
    const t = this._avatar?.entity;
    if (!t) {
      v.warn("AvatarOpacityRenderer: No avatar entity found during materials changed.");
      return;
    }
    this.refreshMaterialCache(t);
  }
  _setOpacityDither(t, e) {
    t.defaultOpacity !== 0 && (t.blendType = pc.BLEND_NONE, t.depthWrite = !0, t.opacityDither = pc.DITHER_BAYER8, t.alphaTest = 0.01, t.opacity = Math.min(e, t.defaultOpacity ?? 1), t.update());
  }
  _storeOriginalMaterials(t) {
    t.material && !this._originalMaterials.has(t) && this._originalMaterials.set(t, t.material), t.meshInstances?.forEach((e) => {
      e.material && !this._originalMeshInstanceMaterials.has(e) && this._originalMeshInstanceMaterials.set(e, e.material);
    });
  }
  _getAllRenderComponents(t) {
    if (this._lastCachedEntity === t && this._cachedRenderComponents)
      return this._cachedRenderComponents;
    const e = t.findComponents("render");
    return this._lastCachedEntity = t, this._cachedRenderComponents = e, e.forEach((i) => this._storeOriginalMaterials(i)), e;
  }
  _applyOpacityToEntity(t, e) {
    this._getAllRenderComponents(t).forEach((s) => this._applyOpacityToRenders(s, e));
  }
  _shouldSkipTransition(t) {
    return Math.abs(t - this.currentOpacity) > this._config.instantOpacityThreshold;
  }
  updateOpacity(t, e) {
    const i = this._avatar?.entity;
    if (!i) return;
    if (this._shouldSkipTransition(e)) {
      this._currentOpacity = e, this._applyOpacityToEntity(i, this._currentOpacity);
      return;
    }
    if (Math.abs(e - this._currentOpacity) > 0.01) {
      const r = this._config.smoothSpeed * t, o = pc.math.lerp(this._currentOpacity, e, r);
      this._currentOpacity = o, this._applyOpacityToEntity(i, this._currentOpacity);
    } else e !== this._currentOpacity && (this._currentOpacity = e, this._applyOpacityToEntity(i, this._currentOpacity));
  }
}
class M {
  static _sharedAudioContext = null;
  _target;
  _analyser = null;
  _source = null;
  _dataArray = null;
  _isTalking = !1;
  _talkThreshold = 0.01;
  // Adjust sensitivity as needed
  _currentStream = null;
  constructor(t) {
    this._target = t;
  }
  update() {
    if (this._analyser && this._dataArray) {
      this._analyser.getByteFrequencyData(this._dataArray);
      let t = 0;
      for (let r = 0; r < this._dataArray.length; r++)
        t += this._dataArray[r];
      const s = t / this._dataArray.length / 255 > this._talkThreshold;
      this._isTalking !== s && (this._isTalking = s, this._handleTalkingStateChange(s));
    }
  }
  setStream(t) {
    this._currentStream !== t && (this._currentStream = t, this._cleanup(), t && this._setupAudioAnalysis(t));
  }
  _getAudioContext() {
    return M._sharedAudioContext || (M._sharedAudioContext = new window.AudioContext()), M._sharedAudioContext;
  }
  _setupAudioAnalysis(t) {
    try {
      const e = this._getAudioContext();
      e.state === "suspended" && e.resume(), this._analyser = e.createAnalyser(), this._analyser.fftSize = 256, this._dataArray = new Uint8Array(this._analyser.frequencyBinCount), this._source = e.createMediaStreamSource(t), this._source.connect(this._analyser);
    } catch (e) {
      console.error("AudioProcessor: Failed to setup audio analysis", e);
    }
  }
  _handleTalkingStateChange(t) {
    this._target.onTalkingStateChanged(t);
  }
  _cleanup() {
    this._source && (this._source.disconnect(), this._source = null);
  }
  destroy() {
    this._cleanup();
  }
}
const Tt = (n, t, e, i, s, r) => {
  const o = Math.PI / 180;
  i - t - 2 * r < 0 && (r = (i - t) / 2), s - e - 2 * r < 0 && (r = (s - e) / 2), n.beginPath(), n.moveTo(t + r, e), n.lineTo(i - r, e), n.arc(i - r, e + r, r, o * 270, o * 360, !1), n.lineTo(i, s - r), n.arc(i - r, s - r, r, o * 0, o * 90, !1), n.lineTo(t + r, s), n.arc(t + r, s - r, r, o * 90, o * 180, !1), n.lineTo(t, e + r), n.arc(t + r, e + r, r, o * 180, o * 270, !1), n.closePath();
};
class xt {
  _graphicsDevice;
  // Resources
  _backgroundCanvas;
  _textCanvas;
  _backgroundTexture;
  _textTexture;
  _backgroundMaterial;
  _textMaterial;
  constructor(t) {
    this._graphicsDevice = t, this._backgroundCanvas = null, this._textCanvas = null, this._backgroundTexture = null, this._textTexture = null, this._backgroundMaterial = null, this._textMaterial = null;
  }
  hasResources() {
    return this._backgroundCanvas && this._textCanvas;
  }
  createResources() {
    if (this.hasResources()) return this.getMaterials();
    this._backgroundCanvas = document.createElement("canvas"), this._textCanvas = document.createElement("canvas");
    const t = new pc.Texture(this._graphicsDevice, {
      format: pc.PIXELFORMAT_R8_G8_B8
    });
    t.setSource(this._backgroundCanvas), t.minFilter = pc.FILTER_LINEAR_MIPMAP_LINEAR, t.magFilter = pc.FILTER_LINEAR, t.addressU = pc.ADDRESS_CLAMP_TO_EDGE, t.addressV = pc.ADDRESS_CLAMP_TO_EDGE, this._backgroundTexture = t;
    const e = new pc.Texture(this._graphicsDevice, {
      format: pc.PIXELFORMAT_R8_G8_B8
    });
    e.setSource(this._textCanvas), e.minFilter = pc.FILTER_LINEAR_MIPMAP_LINEAR, e.magFilter = pc.FILTER_LINEAR, e.addressU = pc.ADDRESS_CLAMP_TO_EDGE, e.addressV = pc.ADDRESS_CLAMP_TO_EDGE, this._textTexture = e;
    const i = this._createBaseMaterial(this._backgroundTexture);
    i.opacity = 0.4, i.update(), this._backgroundMaterial = i;
    const s = this._createBaseMaterial(this._textTexture);
    return s.emissiveMap = this._textTexture, s.emissive.copy(pc.Color.WHITE), s.diffuse.copy(pc.Color.BLACK), s.update(), this._textMaterial = s, this.getMaterials();
  }
  _createBaseMaterial(t) {
    const e = new pc.StandardMaterial();
    return e.opacityMap = t, e.opacityMapChannel = "r", e.blendType = pc.BLEND_PREMULTIPLIED, e.depthWrite = !1, e.useLighting = !1, e.useSkybox = !1, e.useFog = !1, e.useTonemap = !1, e;
  }
  destroyResources() {
    this._backgroundCanvas && (this._backgroundCanvas.remove(), this._backgroundCanvas = null), this._textCanvas && (this._textCanvas.remove(), this._textCanvas = null), this._backgroundTexture && (this._backgroundTexture.destroy(), this._backgroundTexture = null), this._textTexture && (this._textTexture.destroy(), this._textTexture = null), this._backgroundMaterial && (this._backgroundMaterial.destroy(), this._backgroundMaterial = null), this._textMaterial && (this._textMaterial.destroy(), this._textMaterial = null);
  }
  getMaterials() {
    return {
      background: this._backgroundMaterial,
      text: this._textMaterial
    };
  }
  setBackgroundColor(t, e) {
    this._backgroundMaterial && (this._backgroundMaterial.emissive.fromString(t), e !== void 0 && (this._backgroundMaterial.opacity = e), this._backgroundMaterial.update());
  }
  setTextColor(t, e) {
    this._textMaterial && (this._textMaterial.emissive.fromString(t), e !== void 0 && (this._textMaterial.opacity = e), this._textMaterial.update());
  }
  renderBackground(t) {
    if (!this._backgroundCanvas || !this._backgroundTexture) return;
    const e = this._backgroundCanvas.getContext("2d");
    if (!e) return;
    const i = Math.max(window.innerWidth, window.innerHeight), s = Math.min(Math.max(1.5, i / 250), 4);
    if (this._backgroundCanvas.width = t.background.width * s, this._backgroundCanvas.height = t.background.height * s, this._backgroundCanvas.width === 0 || this._backgroundCanvas.height === 0)
      return;
    const r = e.canvas.width, o = e.canvas.height;
    e.clearRect(0, 0, r, o), e.fillStyle = "#ffffff", e.roundRect ? e.roundRect(0, 0, r, o, 22 * s) : Tt(e, 0, 0, r, o, 22 * s), e.fill(), e.stroke(), this._backgroundTexture.upload();
  }
  renderText(t, e, i, s) {
    if (!this._textCanvas || !this._textTexture) return;
    const r = this._textCanvas.getContext("2d");
    if (!r) return;
    const o = Math.max(window.innerWidth, window.innerHeight), l = Math.min(Math.max(1.5, o / 200), 4);
    if (this._textCanvas.width = t.text.width * l, this._textCanvas.height = t.text.height * l, this._textCanvas.width === 0 || this._textCanvas.height === 0)
      return;
    const h = r.canvas.width, a = r.canvas.height;
    r.clearRect(0, 0, h, a), r.fillStyle = "#ffffff", r.font = `${i * l}px ${s}`, r.textAlign = "center";
    const c = r.measureText(e), p = c.fontBoundingBoxAscent + c.fontBoundingBoxDescent, d = a / 2 + (c.fontBoundingBoxAscent - p / 2);
    r.fillText(e, h / 2, d), this._textTexture.upload();
  }
  renderNameTag(t, e, i, s) {
    this.renderBackground(t), this.renderText(t, e, i, s);
  }
}
const Ct = {
  inDisplayRange: !0
};
class St extends vt {
  _entity = null;
  _displayDistance = 15;
  constructor(t) {
    super(Ct), this._entity = t;
  }
  onConditionsUpdated(t) {
    this._entity && (this._entity.enabled = t);
  }
  canDisplayByDistance(t) {
    const e = t <= this._displayDistance;
    return this.updateCondition("inDisplayRange", e), e;
  }
}
const w = 5e-3, $ = 18, K = {
  background: {
    paddingVertical: 4,
    paddingHorizontal: 12
  },
  gap: {
    horizontal: 6,
    vertical: 4
  }
}, D = {
  talking: {
    width: 15,
    height: 12
  }
};
new Array(100).fill(100);
class N {
  static createBaseEntities(t = "") {
    const e = new pc.Entity(t), i = K, s = new pc.Entity(`ScreenOf_${t}`);
    s.addComponent("screen", {
      screenSpace: !1,
      // 3D space
      referenceResolution: [1, 1]
    });
    const r = new pc.Entity(`ContainerColumnGroupOf_${t}`);
    r.addComponent("layoutgroup", {
      orientation: pc.ORIENTATION_VERTICAL,
      alignment: [0.5, 0],
      spacing: [0, 0.05]
    }), r.addComponent("element", {
      type: pc.ELEMENTTYPE_GROUP,
      anchor: [0.5, 0.5, 0.5, 0.5],
      pivot: [0.5, 0],
      width: 0,
      height: 0,
      layers: [pc.LAYERID_WORLD]
    });
    const o = new pc.Entity(`ContainerRowGroupOf_${t}`);
    o.addComponent("layoutgroup", {
      orientation: pc.ORIENTATION_HORIZONTAL,
      alignment: [0.5, 0.5],
      spacing: [0.05, 0]
    }), o.addComponent("element", {
      type: pc.ELEMENTTYPE_GROUP,
      anchor: [0.5, 0.5, 0.5, 0.5],
      pivot: [0.5, 0.5],
      width: 0,
      height: 0,
      layers: [pc.LAYERID_WORLD]
    });
    const l = new pc.Entity(`NameTagGroupOf_${t}`);
    l.addComponent("element", {
      type: pc.ELEMENTTYPE_GROUP,
      anchor: [0.5, 0.5, 0.5, 0.5],
      pivot: [0.5, 0.5],
      width: 0,
      height: 0,
      layers: [pc.LAYERID_WORLD]
    });
    const h = new pc.Entity(`NameTagColumnGroupOf_${t}`);
    h.addComponent("layoutgroup", {
      orientation: pc.ORIENTATION_VERTICAL,
      alignment: [0.5, 0.5],
      spacing: [0, i.gap.vertical * w]
    }), h.addComponent("element", {
      type: pc.ELEMENTTYPE_GROUP,
      anchor: [0.5, 0.5, 0.5, 0.5],
      pivot: [0.5, 0.5],
      width: 0,
      height: 0,
      layers: [pc.LAYERID_WORLD]
    });
    const a = new pc.Entity(`NameTagRowGroupOf_${t}`);
    return a.addComponent("layoutgroup", {
      orientation: pc.ORIENTATION_HORIZONTAL,
      alignment: [0.5, 0.5],
      spacing: [i.gap.horizontal * w, 0]
    }), a.addComponent("element", {
      type: pc.ELEMENTTYPE_GROUP,
      anchor: [0.5, 0.5, 0.5, 0.5],
      pivot: [0.5, 0.5],
      width: 0,
      height: 0,
      layers: [pc.LAYERID_WORLD]
    }), {
      rootEntity: e,
      screenEntity: s,
      containerColumnGroup: r,
      containerRowGroup: o,
      nameTagGroup: l,
      nameTagColumnGroup: h,
      nameTagRowGroup: a
    };
  }
  static createTextEntity(t = "") {
    const e = new pc.Entity(`TextOf_${t}`);
    return e.addComponent("element", {
      type: pc.ELEMENTTYPE_IMAGE,
      anchor: [0.5, 0.5, 0.5, 0.5],
      pivot: [0.5, 0.5],
      width: 0,
      height: 0,
      layers: [pc.LAYERID_WORLD]
    }), e;
  }
  static createBackgroundEntity(t = "") {
    const e = new pc.Entity(`BackgroundOf_${t}`);
    if (e.addComponent("element", {
      type: pc.ELEMENTTYPE_IMAGE,
      anchor: [0.5, 0.5, 0.5, 0.5],
      pivot: [0.5, 0.5],
      width: 0,
      height: 0,
      layers: [pc.LAYERID_WORLD]
    }), e.element) {
      const i = e.element?._image?._renderable, s = 0.2;
      i && (i.meshInstance.calculateSortDistance = (r, o, l) => {
        const { x: h, y: a, z: c } = o, { x: p, y: d, z: g } = l, _ = r.aabb.center;
        return (_.x - h) * p + (_.y - a) * d + (_.z - c) * g + s;
      });
    }
    return e;
  }
  static createSpeakingEntity(t = "") {
    const e = new pc.Entity(`SpeakingOf_${t}`);
    return e.setLocalScale(0.01, 0.01, 0.01), e.addComponent("element", {
      type: pc.ELEMENTTYPE_IMAGE,
      anchor: [0.5, 0.5, 0.5, 0.5],
      pivot: [0.5, 0.5],
      width: 20,
      // Default size, adjust as needed or make proportional
      height: 20,
      opacity: 0,
      // Hidden by default
      layers: [pc.LAYERID_WORLD]
    }), e;
  }
}
const At = (n) => {
  if (!n || !n.element || !n.layoutgroup)
    return { width: 0, height: 0 };
  const t = n.layoutgroup, e = t.orientation === pc.ORIENTATION_HORIZONTAL;
  let i = 0, s = 0, r = 0, o = 0;
  for (let a = 0; a < n.children.length; a++) {
    const c = n.children[a];
    if (c.element) {
      const p = c.element.width, d = c.element.height;
      e ? (i += p, o = Math.max(o, d)) : (s += d, r = Math.max(r, p));
    }
  }
  const l = t.spacing, h = n.children.filter((a) => {
    const c = a;
    return c.enabled && c.element && c.element.enabled;
  }).length;
  return h > 1 && (e ? i += l.x * (h - 1) : s += l.y * (h - 1)), {
    width: e ? i : r,
    height: e ? o : s
  };
}, kt = (n) => {
  if (!n || !n.element)
    return { width: 0, height: 0 };
  let t = 0, e = 0;
  for (let i = 0; i < n.children.length; i++) {
    const s = n.children[i];
    if (s.element) {
      const r = s.element.width, o = s.element.height;
      t = Math.max(t, r), e = Math.max(e, o);
    }
  }
  return {
    width: t,
    height: e
  };
};
class G {
  _applyElementSizeRatio(t, e) {
    !t || !e || (t.width = e.width * w, t.height = e.height * w);
  }
}
class Mt extends G {
  screenEntity;
  containerColumnGroup;
  containerRowGroup;
  nameTagGroup;
  nameTagColumnGroup;
  nameTagRowGroup;
  backgroundEntity;
  textEntity;
  constructor(t, e) {
    super();
    const i = N.createBaseEntities(t);
    this.screenEntity = i.screenEntity, this.containerColumnGroup = i.containerColumnGroup, this.containerRowGroup = i.containerRowGroup, this.nameTagGroup = i.nameTagGroup, this.nameTagColumnGroup = i.nameTagColumnGroup, this.nameTagRowGroup = i.nameTagRowGroup, this.backgroundEntity = N.createBackgroundEntity(t), this.textEntity = N.createTextEntity(t), this._setupMaterials(e.materials), this._assembleBaseEntities(e.rootEntity);
  }
  _assembleBaseEntities(t) {
    this.screenEntity.addChild(this.containerColumnGroup), this.containerColumnGroup.addChild(this.containerRowGroup), this.containerRowGroup.addChild(this.nameTagGroup), this.nameTagGroup.addChild(this.backgroundEntity), this.nameTagGroup.addChild(this.nameTagColumnGroup), this.nameTagColumnGroup.addChild(this.nameTagRowGroup), t.addChild(this.screenEntity);
  }
  assembleContentEntities() {
    this.nameTagRowGroup.addChild(this.textEntity);
  }
  updateElementSize(t) {
    this._applyElementSizeRatio(this.backgroundEntity.element, t.background), this._applyElementSizeRatio(this.textEntity.element, t.text), this._finalizeLayoutSize();
  }
  getEntities() {
    return {
      screenEntity: this.screenEntity,
      containerColumnGroup: this.containerColumnGroup,
      containerRowGroup: this.containerRowGroup,
      nameTagGroup: this.nameTagGroup,
      nameTagColumnGroup: this.nameTagColumnGroup,
      nameTagRowGroup: this.nameTagRowGroup,
      backgroundEntity: this.backgroundEntity,
      textEntity: this.textEntity
    };
  }
  _setupMaterials(t) {
    const { background: e, text: i } = t;
    if (!e || !i) {
      v.warn("NameTag: Background or text material is not provided.");
      return;
    }
    const s = this.backgroundEntity;
    s?.element && (s.element.material = e);
    const r = this.textEntity;
    r?.element && (r.element.material = i);
  }
  _finalizeLayoutSize() {
    [
      this.nameTagRowGroup,
      this.nameTagColumnGroup,
      this.nameTagGroup,
      this.containerRowGroup,
      this.containerColumnGroup
    ].forEach((e) => {
      if (e && e.element) {
        const i = e.layoutgroup ? At(e) : kt(e);
        e.element.width = i.width, e.element.height = i.height;
      }
    });
  }
}
class Rt {
  /**
   * Create the basic DOM nodes for the name tag
   * In order to get background and text nodes for size calculation
   */
  static createBaseDomNodes(t, e, i, s = !0) {
    const r = K, o = document.createElement("div"), l = document.createElement("div"), h = document.createElement("div"), a = document.createElement("div"), c = document.createElement("span");
    l.style.display = "inline-flex", l.style.flexDirection = "row";
    const p = s ? `${r.background.paddingVertical}px ${r.background.paddingHorizontal}px` : "0px";
    l.style.padding = p, h.style.display = "inline-flex", h.style.flexDirection = "row", h.style.alignItems = "center", h.style.gap = `0px ${r.gap.horizontal}px`, h.style.backgroundColor = "orange", a.style.display = "inline-flex", a.style.flexDirection = "column", a.style.alignItems = "center";
    const d = s ? `${r.gap.vertical}px 0px` : "0px";
    return a.style.gap = d, c.style.fontSize = `${e}px`, c.style.fontFamily = i, c.innerHTML = t, o.append(l), l.append(a), a.append(h), h.append(c), {
      wrapper: o,
      background: l,
      horizontal: h,
      vertical: a,
      text: c
    };
  }
}
class Ot {
  createBaseDomNodes(t, e, i, s) {
    return Rt.createBaseDomNodes(t, e, i, s);
  }
  measureDomNodeSize(t) {
    document.body.append(t.wrapper);
    const e = {};
    return Object.entries(t).forEach(([i, s]) => {
      s instanceof HTMLElement && (e[i] = {
        width: s.offsetWidth,
        height: s.offsetHeight
      });
    }), t.wrapper && t.wrapper.parentNode && t.wrapper.remove(), e;
  }
}
class Lt {
  _isSetUp = !1;
  _entity;
  _pcApp;
  _ui = null;
  _billboardTarget = new pc.Vec3();
  _displayVerifier;
  _measurer;
  _renderer;
  _text = "";
  _fontSize = 16;
  _fontFamily = "Roboto, Arial, sans-serif";
  constructor(t, e) {
    this._pcApp = t, this._renderer = new xt(t.graphicsDevice), this._measurer = new Ot();
    const { text: i, entityName: s } = e || {};
    i && (this._text = i);
    const r = s || "NameTag";
    this._entity = new pc.Entity(r), this._displayVerifier = new St(this._entity);
  }
  /**
   * Factory method to create and initialize a NameTag instance.
   *
   * @remarks This method is called internally and should not be invoked directly.
   * @param this The class of the NameTag to create
   * @param pcApp  The PlayCanvas application instance
   * @param options  Optional configuration options for the NameTag
   * @returns
   * @hidden
   */
  static async create(t, e) {
    const i = new this(t, e);
    return await i._loadDependencies(), i._createStructure(), i;
  }
  get entity() {
    return this._entity;
  }
  get isSetUp() {
    return this._isSetUp;
  }
  setup(t) {
    if (this._isSetUp) {
      v.warn("NameTag: Already set up. Skipping setup.");
      return;
    }
    this._isSetUp = !0, this._updateNameTag(), t.addChild(this._entity), this._registerScripts();
  }
  updateLocalPosition(t, e, i) {
    this._entity.setLocalPosition(t, e, i);
  }
  updateLocalScale(t, e, i) {
    this._entity.setLocalScale(t, e, i);
  }
  setText(t) {
    this._text !== t && (this._text = t, this._updateNameTag());
  }
  setBackgroundColor(t, e) {
    this._renderer.setBackgroundColor(t, e);
  }
  setTextColor(t, e) {
    this._renderer.setTextColor(t, e);
  }
  updateViewPosition(t) {
    const e = this._entity.getPosition().distance(t);
    this._displayVerifier.canDisplayByDistance(e), this._billboardTarget.copy(t);
  }
  updateDisplayCondition(t, e) {
    this._displayVerifier.updateCondition(t, e);
  }
  _createStructure() {
    this._createEntities(), this._assembleContentEntities(), this._bindEvents();
  }
  _createEntities() {
    const t = {
      pcApp: this._pcApp,
      rootEntity: this._entity,
      setBackgroundColor: (i, s) => this.setBackgroundColor(i, s),
      setTextColor: (i) => this.setTextColor(i)
    }, e = this._renderer.createResources();
    return this._ui = new Mt(this._entity.name, { ...t, materials: e }), t;
  }
  _assembleContentEntities() {
    this._ui?.assembleContentEntities();
  }
  _updateEntityVisibility() {
  }
  _bindEvents() {
  }
  _unbindEvents() {
  }
  async _loadDependencies() {
  }
  _hasContent() {
    return this._text.trim().length > 0;
  }
  _createDomNodes() {
    const t = this._hasContent();
    return this._measurer.createBaseDomNodes(
      this._text,
      this._fontSize,
      this._fontFamily,
      t
    );
  }
  _updateElementSize(t) {
    this._ui?.updateElementSize(t);
  }
  setSpeaking(t) {
  }
  _registerScripts() {
    if (this._entity.script || this._entity.addComponent("script"), this._entity.script) {
      const t = this._ui?.screenEntity;
      t && t.setLocalEulerAngles(0, 180, 0), this._entity.script.create(Et, {
        properties: {
          targetPosition: this._billboardTarget
        }
      });
    }
  }
  _updateNameTag() {
    if (!this._renderer.hasResources()) return;
    this._updateEntityVisibility();
    const e = this._createDomNodes(), i = this._measurer.measureDomNodeSize(e);
    this._renderer.renderNameTag(i, this._text, this._fontSize, this._fontFamily), this._updateElementSize(i);
  }
  /** @hidden */
  destroy() {
    this._renderer.destroyResources(), this._unbindEvents();
  }
}
const H = (n, t) => n.length <= t ? n : n.slice(0, t) + "...";
class Z {
  static createTriggerEntity(t = "") {
    const e = new pc.Entity(`TriggerOf_${t}`);
    return e.addComponent("button"), e.addComponent("element", {
      type: pc.ELEMENTTYPE_IMAGE,
      anchor: [0.5, 0.5, 0.5, 0.5],
      pivot: [0.5, 0.5],
      width: 0,
      height: 0,
      opacity: 0,
      useInput: !0,
      layers: [pc.LAYERID_WORLD]
    }), e;
  }
  static createTalkingEntity(t = "") {
    const e = new pc.Entity(`TalkingOf_${t}`);
    return e.addComponent("element", {
      type: pc.ELEMENTTYPE_IMAGE,
      anchor: [0.5, 0.5, 0.5, 0.5],
      pivot: [0.5, 0.5],
      width: D.talking.width * w,
      height: D.talking.height * w,
      layers: [pc.LAYERID_WORLD]
    }), e;
  }
}
class Nt extends G {
  triggerEntity;
  _context;
  constructor(t, e) {
    super(), this.triggerEntity = Z.createTriggerEntity(t), this._context = e, this._bindButtonEvents();
  }
  get isClickable() {
    return !!this._context.onNameTagClick;
  }
  assembleContentEntities(t) {
    t.nameTagGroup.addChild(this.triggerEntity);
  }
  updateElementSize(t) {
    this._applyElementSizeRatio(this.triggerEntity.element, t.background);
  }
  _bindButtonEvents() {
    this.isClickable && (this.triggerEntity.element && (this.triggerEntity.element.on("mouseenter", this._onNameTagMouseEnter, this), this.triggerEntity.element.on("mouseleave", this._onNameTagMouseLeave, this), this.triggerEntity.element.on("mousedown", this._onNameTagPressed, this), this.triggerEntity.element.on("touchstart", this._onNameTagPressed, this), this.triggerEntity.element.on("mouseup", this._onNameTagReleased, this), this.triggerEntity.element.on("touchend", this._onNameTagReleased, this)), this.triggerEntity.button && this.triggerEntity.button.on("click", this._onNameTagClicked, this));
  }
  _unbindButtonEvents() {
    this.isClickable && (this.triggerEntity.element && (this.triggerEntity.element.off("mouseenter", this._onNameTagMouseEnter, this), this.triggerEntity.element.off("mouseleave", this._onNameTagMouseLeave, this), this.triggerEntity.element.off("mousedown", this._onNameTagPressed, this), this.triggerEntity.element.off("touchstart", this._onNameTagPressed, this), this.triggerEntity.element.off("mouseup", this._onNameTagReleased, this), this.triggerEntity.element.off("touchend", this._onNameTagReleased, this)), this.triggerEntity.button && this.triggerEntity.button.off("click", this._onNameTagClicked, this));
  }
  _onNameTagMouseEnter() {
    this._context.setBackgroundColor("#364356", 1);
  }
  _onNameTagMouseLeave() {
    this._context.setBackgroundColor("#000000", 0.4);
  }
  _onNameTagPressed() {
    this._context.setTextColor("#6E7C8E");
  }
  _onNameTagReleased() {
    this._context.setTextColor("#FFFFFF");
  }
  _onNameTagClicked() {
    this._context.onNameTagClick?.();
  }
  destroy() {
    this._unbindButtonEvents();
  }
}
const Dt = "player-name-tag-talking-sprite", W = X.scriptName, It = ["0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "10"];
class Pt {
  _pcApp;
  _entity;
  constructor(t, e) {
    this._pcApp = t, this._entity = e;
  }
  async initialize() {
    if (!this._entity.element) return;
    const t = await this._getOrCreateSpriteAsset();
    this._entity.element.spriteAsset = t.id, this._entity.element.spriteFrame = 0, this._entity.script || this._entity.addComponent("script"), this._entity.script && (this._entity.script.has(W) || this._entity.script.create(X, {
      properties: {
        fps: 10,
        delay: 0,
        loop: !0,
        sizeRatio: w
      }
    }));
  }
  destroy() {
    this._entity.script?.destroy(W);
  }
  async _getOrCreateSpriteAsset() {
    const t = await j(
      this._pcApp,
      "talking-sheet.png",
      "/textures/name-tag/",
      "core",
      "texture"
    ), e = new pc.TextureAtlas();
    e.texture = t.resource, e.frames = {
      0: {
        rect: new pc.Vec4(1, 29, 15, 12),
        pivot: new pc.Vec2(0.5, 0.5),
        border: new pc.Vec4(0, 0, 0, 0)
      },
      1: {
        rect: new pc.Vec4(18, 29, 15, 12),
        pivot: new pc.Vec2(0.5, 0.5),
        border: new pc.Vec4(0, 0, 0, 0)
      },
      2: {
        rect: new pc.Vec4(35, 29, 15, 12),
        pivot: new pc.Vec2(0.5, 0.5),
        border: new pc.Vec4(0, 0, 0, 0)
      },
      3: {
        rect: new pc.Vec4(1, 15, 15, 12),
        pivot: new pc.Vec2(0.5, 0.5),
        border: new pc.Vec4(0, 0, 0, 0)
      },
      4: {
        rect: new pc.Vec4(18, 15, 15, 12),
        pivot: new pc.Vec2(0.5, 0.5),
        border: new pc.Vec4(0, 0, 0, 0)
      },
      5: {
        rect: new pc.Vec4(35, 15, 15, 12),
        pivot: new pc.Vec2(0.5, 0.5),
        border: new pc.Vec4(0, 0, 0, 0)
      },
      6: {
        rect: new pc.Vec4(1, 1, 15, 12),
        pivot: new pc.Vec2(0.5, 0.5),
        border: new pc.Vec4(0, 0, 0, 0)
      },
      7: {
        rect: new pc.Vec4(18, 1, 15, 12),
        pivot: new pc.Vec2(0.5, 0.5),
        border: new pc.Vec4(0, 0, 0, 0)
      },
      8: {
        rect: new pc.Vec4(35, 1, 15, 12),
        pivot: new pc.Vec2(0.5, 0.5),
        border: new pc.Vec4(0, 0, 0, 0)
      },
      9: {
        rect: new pc.Vec4(52, 29, 15, 12),
        pivot: new pc.Vec2(0.5, 0.5),
        border: new pc.Vec4(0, 0, 0, 0)
      },
      10: {
        rect: new pc.Vec4(52, 15, 15, 12),
        pivot: new pc.Vec2(0.5, 0.5),
        border: new pc.Vec4(0, 0, 0, 0)
      }
    };
    const i = new pc.Sprite(this._pcApp.graphicsDevice, {
      pixelsPerUnit: 100,
      renderMode: pc.SPRITE_RENDERMODE_SIMPLE,
      atlas: e,
      frameKeys: It
    }), s = `${Dt}_${this._entity.getGuid()}`, r = new pc.Asset(s, "sprite");
    return r.resource = i, this._pcApp.assets.add(r), r;
  }
}
class Vt extends G {
  talkingEntity;
  _talkingSprite;
  constructor(t, e) {
    super(), this.talkingEntity = Z.createTalkingEntity(t), this._talkingSprite = new Pt(e.pcApp, this.talkingEntity), this._initialize();
  }
  async _initialize() {
    try {
      await this._talkingSprite.initialize();
    } catch (t) {
      v.error("Failed to initialize TalkingSprite:", t);
    }
  }
  assembleContentEntities(t) {
    t.nameTagRowGroup.addChild(t.textEntity), t.nameTagRowGroup.addChild(this.talkingEntity);
  }
  updateElementSize(t) {
    this._applyElementSizeRatio(this.talkingEntity.element, t.talking);
  }
  setVisible(t) {
    this.talkingEntity.enabled = t.isTalking;
  }
  destroy() {
    this._talkingSprite.destroy();
  }
}
class Gt {
  static createDomNodes(t, e) {
    const i = document.createElement("div"), { horizontal: s } = t;
    return s.append(i), this.setTalkingStyles(i, e.isTalking), {
      talking: i
    };
  }
  static setTalkingStyles(t, e) {
    const i = D.talking;
    t.style.width = e ? `${i.width}px` : "0px", t.style.height = e ? `${i.height}px` : "0px";
  }
}
class ce extends Lt {
  _isTalking = !1;
  _triggerButtonUi = null;
  _stateIconsUi = null;
  _onNameTagClick = null;
  constructor(t, e) {
    e && e.text && (e.text = H(e.text, $)), super(t, e), this._onNameTagClick = e?.onNameTagClick || null;
  }
  _createDomNodes() {
    const t = super._createDomNodes(), e = Gt.createDomNodes(t, {
      isTalking: this._isTalking
    });
    return {
      ...t,
      ...e
    };
  }
  _updateElementSize(t) {
    super._updateElementSize(t), this._triggerButtonUi?.updateElementSize(t), this._stateIconsUi?.updateElementSize(t);
  }
  _createEntities() {
    const e = {
      ...super._createEntities(),
      ...this._onNameTagClick && { onNameTagClick: () => this._onNameTagClick() }
    };
    return this._triggerButtonUi = new Nt(this._entity.name, e), this._stateIconsUi = new Vt(this._entity.name, e), e;
  }
  _updateEntityVisibility() {
    super._updateEntityVisibility(), this._stateIconsUi?.setVisible({
      isTalking: this._isTalking
    });
  }
  _assembleContentEntities() {
    if (super._assembleContentEntities(), this._ui) {
      const t = this._ui.getEntities();
      this._triggerButtonUi?.assembleContentEntities(t), this._stateIconsUi?.assembleContentEntities(t);
    }
  }
  _hasContent() {
    return super._hasContent() || this._isTalking;
  }
  get isTalking() {
    return this._isTalking;
  }
  set isTalking(t) {
    this._isTalking = t, this._updateNameTag();
  }
  setText(t) {
    super.setText(H(t, $));
  }
  setSpeaking(t) {
    this.isTalking = t;
  }
  destroy() {
    this._triggerButtonUi && this._triggerButtonUi.destroy(), this._stateIconsUi && this._stateIconsUi.destroy();
  }
}
export {
  M as AudioProcessor,
  oe as AvatarOpacityRenderer,
  Jt as BaseModule,
  te as BaseSystem,
  Et as Billboard,
  vt as ConditionVerifier,
  pt as ConsoleDebugger,
  v as Debugger,
  ae as EntityStateEmitter,
  Lt as NameTag,
  Mt as NameTagUi,
  ce as PlayerNameTag,
  re as UVScroll,
  X as UiSpriteAnim,
  Qt as ViverseApp,
  ht as calculateAvatarCapsule,
  Yt as createAvatarCollision,
  ne as createFallbackGripBone,
  Zt as createLayer,
  ft as fetchViverseAvatarService,
  mt as fetchViversePublicAvatars,
  qt as getBoundingBox,
  se as getLocalPlayer,
  dt as getNextLayerId,
  Wt as getQueryString,
  ee as getRandomAvatar,
  ie as getRandomName,
  j as loadAsset,
  ut as loadAssetFromUrl,
  jt as loadFontAsset,
  Ut as qsGet,
  x as qsHas,
  Ht as qsRemove,
  $t as qsSet,
  Ft as registerModule,
  J as registerSystem,
  Xt as setsEqual,
  Kt as sortMapByOrder,
  yt as updateFallbackGripBonePosition
};
