/**
 * @license
 * Copyright 2010-2025 Three.js Authors
 * SPDX-License-Identifier: MIT
 */
const Ul = "180", bt = { LEFT: 0, MIDDLE: 1, RIGHT: 2, ROTATE: 0, DOLLY: 1, PAN: 2 }, hs = { ROTATE: 0, PAN: 1, DOLLY_PAN: 2, DOLLY_ROTATE: 3 }, vf = 0, Ph = 1, xf = 2, Og = 3, Fg = 0, jh = 1, bf = 2, Yi = 3, Di = 0, zt = 1, ri = 2, fn = 0, Dn = 1, Lh = 2, Ih = 3, Dh = 4, Sf = 5, Ln = 100, Mf = 101, wf = 102, Ef = 103, Tf = 104, Af = 200, Cf = 201, Rf = 202, Pf = 203, qo = 204, Zo = 205, Lf = 206, If = 207, Df = 208, Nf = 209, Uf = 210, Of = 211, Ff = 212, Bf = 213, kf = 214, Yo = 0, jo = 1, $o = 2, vs = 3, Ko = 4, Jo = 5, Qo = 6, el = 7, xa = 0, zf = 1, Hf = 2, mn = 0, Vf = 1, Gf = 2, Wf = 3, Xf = 4, qf = 5, Zf = 6, Yf = 7, Nh = "attached", jf = "detached", Ol = 300, _n = 301, Un = 302, na = 303, sa = 304, xr = 306, xs = 1e3, fi = 1001, ra = 1002, Xt = 1003, $h = 1004, Bg = 1004, nr = 1005, kg = 1005, Pt = 1006, Zr = 1007, zg = 1007, Ji = 1008, Hg = 1008, Hi = 1009, Kh = 1010, Jh = 1011, cr = 1012, Fl = 1013, yn = 1014, mi = 1015, br = 1016, Bl = 1017, kl = 1018, hr = 1020, Qh = 35902, ed = 35899, td = 1021, id = 1022, oi = 1023, dr = 1026, ur = 1027, zl = 1028, ba = 1029, nd = 1030, Hl = 1031, Vg = 1032, Vl = 1033, Yr = 33776, jr = 33777, $r = 33778, Kr = 33779, tl = 35840, il = 35841, nl = 35842, sl = 35843, rl = 36196, al = 37492, ol = 37496, ll = 37808, cl = 37809, hl = 37810, dl = 37811, ul = 37812, pl = 37813, fl = 37814, ml = 37815, gl = 37816, _l = 37817, yl = 37818, vl = 37819, xl = 37820, bl = 37821, Sl = 36492, Ml = 36494, wl = 36495, El = 36283, Tl = 36284, Al = 36285, Cl = 36286, $f = 2200, sd = 2201, rd = 2202, aa = 2300, Rl = 2301, zo = 2302, ds = 2400, us = 2401, oa = 2402, Gl = 2500, ad = 2501, Gg = 0, Wg = 1, Xg = 2, Kf = 3200, Jf = 3201, qg = 3202, Zg = 3203, zn = 0, Qf = 1, un = "", Qt = "srgb", On = "srgb-linear", la = "linear", ut = "srgb", Yg = 0, os = 7680, Ho = 7681, jg = 7682, $g = 7683, Vo = 34055, Go = 34056, Kg = 5386, Jg = 512, Qg = 513, e_ = 514, t_ = 515, i_ = 516, em = 517, n_ = 518, ca = 519, tm = 512, im = 513, nm = 514, od = 515, sm = 516, rm = 517, am = 518, om = 519, ha = 35044, s_ = 35048, r_ = 35040, a_ = 35045, o_ = 35049, l_ = 35041, c_ = 35046, h_ = 35050, d_ = 35042, u_ = "100", Uh = "300 es", wi = 2e3, pr = 2001, p_ = {
  COMPUTE: "compute",
  RENDER: "render"
}, f_ = {
  PERSPECTIVE: "perspective",
  LINEAR: "linear",
  FLAT: "flat"
}, m_ = {
  NORMAL: "normal",
  CENTROID: "centroid",
  SAMPLE: "sample",
  FIRST: "first",
  EITHER: "either"
};
class sn {
  /**
   * Adds the given event listener to the given event type.
   *
   * @param {string} type - The type of event to listen to.
   * @param {Function} listener - The function that gets called when the event is fired.
   */
  addEventListener(e, t) {
    this._listeners === void 0 && (this._listeners = {});
    const i = this._listeners;
    i[e] === void 0 && (i[e] = []), i[e].indexOf(t) === -1 && i[e].push(t);
  }
  /**
   * Returns `true` if the given event listener has been added to the given event type.
   *
   * @param {string} type - The type of event.
   * @param {Function} listener - The listener to check.
   * @return {boolean} Whether the given event listener has been added to the given event type.
   */
  hasEventListener(e, t) {
    const i = this._listeners;
    return i === void 0 ? !1 : i[e] !== void 0 && i[e].indexOf(t) !== -1;
  }
  /**
   * Removes the given event listener from the given event type.
   *
   * @param {string} type - The type of event.
   * @param {Function} listener - The listener to remove.
   */
  removeEventListener(e, t) {
    const i = this._listeners;
    if (i === void 0) return;
    const n = i[e];
    if (n !== void 0) {
      const s = n.indexOf(t);
      s !== -1 && n.splice(s, 1);
    }
  }
  /**
   * Dispatches an event object.
   *
   * @param {Object} event - The event that gets fired.
   */
  dispatchEvent(e) {
    const t = this._listeners;
    if (t === void 0) return;
    const i = t[e.type];
    if (i !== void 0) {
      e.target = this;
      const n = i.slice(0);
      for (let s = 0, a = n.length; s < a; s++)
        n[s].call(this, e);
      e.target = null;
    }
  }
}
const Zt = ["00", "01", "02", "03", "04", "05", "06", "07", "08", "09", "0a", "0b", "0c", "0d", "0e", "0f", "10", "11", "12", "13", "14", "15", "16", "17", "18", "19", "1a", "1b", "1c", "1d", "1e", "1f", "20", "21", "22", "23", "24", "25", "26", "27", "28", "29", "2a", "2b", "2c", "2d", "2e", "2f", "30", "31", "32", "33", "34", "35", "36", "37", "38", "39", "3a", "3b", "3c", "3d", "3e", "3f", "40", "41", "42", "43", "44", "45", "46", "47", "48", "49", "4a", "4b", "4c", "4d", "4e", "4f", "50", "51", "52", "53", "54", "55", "56", "57", "58", "59", "5a", "5b", "5c", "5d", "5e", "5f", "60", "61", "62", "63", "64", "65", "66", "67", "68", "69", "6a", "6b", "6c", "6d", "6e", "6f", "70", "71", "72", "73", "74", "75", "76", "77", "78", "79", "7a", "7b", "7c", "7d", "7e", "7f", "80", "81", "82", "83", "84", "85", "86", "87", "88", "89", "8a", "8b", "8c", "8d", "8e", "8f", "90", "91", "92", "93", "94", "95", "96", "97", "98", "99", "9a", "9b", "9c", "9d", "9e", "9f", "a0", "a1", "a2", "a3", "a4", "a5", "a6", "a7", "a8", "a9", "aa", "ab", "ac", "ad", "ae", "af", "b0", "b1", "b2", "b3", "b4", "b5", "b6", "b7", "b8", "b9", "ba", "bb", "bc", "bd", "be", "bf", "c0", "c1", "c2", "c3", "c4", "c5", "c6", "c7", "c8", "c9", "ca", "cb", "cc", "cd", "ce", "cf", "d0", "d1", "d2", "d3", "d4", "d5", "d6", "d7", "d8", "d9", "da", "db", "dc", "dd", "de", "df", "e0", "e1", "e2", "e3", "e4", "e5", "e6", "e7", "e8", "e9", "ea", "eb", "ec", "ed", "ee", "ef", "f0", "f1", "f2", "f3", "f4", "f5", "f6", "f7", "f8", "f9", "fa", "fb", "fc", "fd", "fe", "ff"];
let tu = 1234567;
const ms = Math.PI / 180, fr = 180 / Math.PI;
function Ti() {
  const r = Math.random() * 4294967295 | 0, e = Math.random() * 4294967295 | 0, t = Math.random() * 4294967295 | 0, i = Math.random() * 4294967295 | 0;
  return (Zt[r & 255] + Zt[r >> 8 & 255] + Zt[r >> 16 & 255] + Zt[r >> 24 & 255] + "-" + Zt[e & 255] + Zt[e >> 8 & 255] + "-" + Zt[e >> 16 & 15 | 64] + Zt[e >> 24 & 255] + "-" + Zt[t & 63 | 128] + Zt[t >> 8 & 255] + "-" + Zt[t >> 16 & 255] + Zt[t >> 24 & 255] + Zt[i & 255] + Zt[i >> 8 & 255] + Zt[i >> 16 & 255] + Zt[i >> 24 & 255]).toLowerCase();
}
function Fe(r, e, t) {
  return Math.max(e, Math.min(t, r));
}
function ld(r, e) {
  return (r % e + e) % e;
}
function g_(r, e, t, i, n) {
  return i + (r - e) * (n - i) / (t - e);
}
function __(r, e, t) {
  return r !== e ? (t - r) / (e - r) : 0;
}
function Jr(r, e, t) {
  return (1 - t) * r + t * e;
}
function y_(r, e, t, i) {
  return Jr(r, e, 1 - Math.exp(-t * i));
}
function v_(r, e = 1) {
  return e - Math.abs(ld(r, e * 2) - e);
}
function x_(r, e, t) {
  return r <= e ? 0 : r >= t ? 1 : (r = (r - e) / (t - e), r * r * (3 - 2 * r));
}
function b_(r, e, t) {
  return r <= e ? 0 : r >= t ? 1 : (r = (r - e) / (t - e), r * r * r * (r * (r * 6 - 15) + 10));
}
function S_(r, e) {
  return r + Math.floor(Math.random() * (e - r + 1));
}
function M_(r, e) {
  return r + Math.random() * (e - r);
}
function w_(r) {
  return r * (0.5 - Math.random());
}
function E_(r) {
  r !== void 0 && (tu = r);
  let e = tu += 1831565813;
  return e = Math.imul(e ^ e >>> 15, e | 1), e ^= e + Math.imul(e ^ e >>> 7, e | 61), ((e ^ e >>> 14) >>> 0) / 4294967296;
}
function T_(r) {
  return r * ms;
}
function A_(r) {
  return r * fr;
}
function C_(r) {
  return (r & r - 1) === 0 && r !== 0;
}
function R_(r) {
  return Math.pow(2, Math.ceil(Math.log(r) / Math.LN2));
}
function P_(r) {
  return Math.pow(2, Math.floor(Math.log(r) / Math.LN2));
}
function L_(r, e, t, i, n) {
  const s = Math.cos, a = Math.sin, o = s(t / 2), l = a(t / 2), c = s((e + i) / 2), h = a((e + i) / 2), d = s((e - i) / 2), u = a((e - i) / 2), p = s((i - e) / 2), m = a((i - e) / 2);
  switch (n) {
    case "XYX":
      r.set(o * h, l * d, l * u, o * c);
      break;
    case "YZY":
      r.set(l * u, o * h, l * d, o * c);
      break;
    case "ZXZ":
      r.set(l * d, l * u, o * h, o * c);
      break;
    case "XZX":
      r.set(o * h, l * m, l * p, o * c);
      break;
    case "YXY":
      r.set(l * p, o * h, l * m, o * c);
      break;
    case "ZYZ":
      r.set(l * m, l * p, o * h, o * c);
      break;
    default:
      console.warn("THREE.MathUtils: .setQuaternionFromProperEuler() encountered an unknown order: " + n);
  }
}
function ai(r, e) {
  switch (e.constructor) {
    case Float32Array:
      return r;
    case Uint32Array:
      return r / 4294967295;
    case Uint16Array:
      return r / 65535;
    case Uint8Array:
      return r / 255;
    case Int32Array:
      return Math.max(r / 2147483647, -1);
    case Int16Array:
      return Math.max(r / 32767, -1);
    case Int8Array:
      return Math.max(r / 127, -1);
    default:
      throw new Error("Invalid component type.");
  }
}
function Xe(r, e) {
  switch (e.constructor) {
    case Float32Array:
      return r;
    case Uint32Array:
      return Math.round(r * 4294967295);
    case Uint16Array:
      return Math.round(r * 65535);
    case Uint8Array:
      return Math.round(r * 255);
    case Int32Array:
      return Math.round(r * 2147483647);
    case Int16Array:
      return Math.round(r * 32767);
    case Int8Array:
      return Math.round(r * 127);
    default:
      throw new Error("Invalid component type.");
  }
}
const da = {
  DEG2RAD: ms,
  RAD2DEG: fr,
  /**
   * Generate a [UUID]{@link https://en.wikipedia.org/wiki/Universally_unique_identifier}
   * (universally unique identifier).
   *
   * @static
   * @method
   * @return {string} The UUID.
   */
  generateUUID: Ti,
  /**
   * Clamps the given value between min and max.
   *
   * @static
   * @method
   * @param {number} value - The value to clamp.
   * @param {number} min - The min value.
   * @param {number} max - The max value.
   * @return {number} The clamped value.
   */
  clamp: Fe,
  /**
   * Computes the Euclidean modulo of the given parameters that
   * is `( ( n % m ) + m ) % m`.
   *
   * @static
   * @method
   * @param {number} n - The first parameter.
   * @param {number} m - The second parameter.
   * @return {number} The Euclidean modulo.
   */
  euclideanModulo: ld,
  /**
   * Performs a linear mapping from range `<a1, a2>` to range `<b1, b2>`
   * for the given value.
   *
   * @static
   * @method
   * @param {number} x - The value to be mapped.
   * @param {number} a1 - Minimum value for range A.
   * @param {number} a2 - Maximum value for range A.
   * @param {number} b1 - Minimum value for range B.
   * @param {number} b2 - Maximum value for range B.
   * @return {number} The mapped value.
   */
  mapLinear: g_,
  /**
   * Returns the percentage in the closed interval `[0, 1]` of the given value
   * between the start and end point.
   *
   * @static
   * @method
   * @param {number} x - The start point
   * @param {number} y - The end point.
   * @param {number} value - A value between start and end.
   * @return {number} The interpolation factor.
   */
  inverseLerp: __,
  /**
   * Returns a value linearly interpolated from two known points based on the given interval -
   * `t = 0` will return `x` and `t = 1` will return `y`.
   *
   * @static
   * @method
   * @param {number} x - The start point
   * @param {number} y - The end point.
   * @param {number} t - The interpolation factor in the closed interval `[0, 1]`.
   * @return {number} The interpolated value.
   */
  lerp: Jr,
  /**
   * Smoothly interpolate a number from `x` to `y` in  a spring-like manner using a delta
   * time to maintain frame rate independent movement. For details, see
   * [Frame rate independent damping using lerp]{@link http://www.rorydriscoll.com/2016/03/07/frame-rate-independent-damping-using-lerp/}.
   *
   * @static
   * @method
   * @param {number} x - The current point.
   * @param {number} y - The target point.
   * @param {number} lambda - A higher lambda value will make the movement more sudden,
   * and a lower value will make the movement more gradual.
   * @param {number} dt - Delta time in seconds.
   * @return {number} The interpolated value.
   */
  damp: y_,
  /**
   * Returns a value that alternates between `0` and the given `length` parameter.
   *
   * @static
   * @method
   * @param {number} x - The value to pingpong.
   * @param {number} [length=1] - The positive value the function will pingpong to.
   * @return {number} The alternated value.
   */
  pingpong: v_,
  /**
   * Returns a value in the range `[0,1]` that represents the percentage that `x` has
   * moved between `min` and `max`, but smoothed or slowed down the closer `x` is to
   * the `min` and `max`.
   *
   * See [Smoothstep]{@link http://en.wikipedia.org/wiki/Smoothstep} for more details.
   *
   * @static
   * @method
   * @param {number} x - The value to evaluate based on its position between min and max.
   * @param {number} min - The min value. Any x value below min will be `0`.
   * @param {number} max - The max value. Any x value above max will be `1`.
   * @return {number} The alternated value.
   */
  smoothstep: x_,
  /**
   * A [variation on smoothstep]{@link https://en.wikipedia.org/wiki/Smoothstep#Variations}
   * that has zero 1st and 2nd order derivatives at x=0 and x=1.
   *
   * @static
   * @method
   * @param {number} x - The value to evaluate based on its position between min and max.
   * @param {number} min - The min value. Any x value below min will be `0`.
   * @param {number} max - The max value. Any x value above max will be `1`.
   * @return {number} The alternated value.
   */
  smootherstep: b_,
  /**
   * Returns a random integer from `<low, high>` interval.
   *
   * @static
   * @method
   * @param {number} low - The lower value boundary.
   * @param {number} high - The upper value boundary
   * @return {number} A random integer.
   */
  randInt: S_,
  /**
   * Returns a random float from `<low, high>` interval.
   *
   * @static
   * @method
   * @param {number} low - The lower value boundary.
   * @param {number} high - The upper value boundary
   * @return {number} A random float.
   */
  randFloat: M_,
  /**
   * Returns a random integer from `<-range/2, range/2>` interval.
   *
   * @static
   * @method
   * @param {number} range - Defines the value range.
   * @return {number} A random float.
   */
  randFloatSpread: w_,
  /**
   * Returns a deterministic pseudo-random float in the interval `[0, 1]`.
   *
   * @static
   * @method
   * @param {number} [s] - The integer seed.
   * @return {number} A random float.
   */
  seededRandom: E_,
  /**
   * Converts degrees to radians.
   *
   * @static
   * @method
   * @param {number} degrees - A value in degrees.
   * @return {number} The converted value in radians.
   */
  degToRad: T_,
  /**
   * Converts radians to degrees.
   *
   * @static
   * @method
   * @param {number} radians - A value in radians.
   * @return {number} The converted value in degrees.
   */
  radToDeg: A_,
  /**
   * Returns `true` if the given number is a power of two.
   *
   * @static
   * @method
   * @param {number} value - The value to check.
   * @return {boolean} Whether the given number is a power of two or not.
   */
  isPowerOfTwo: C_,
  /**
   * Returns the smallest power of two that is greater than or equal to the given number.
   *
   * @static
   * @method
   * @param {number} value - The value to find a POT for.
   * @return {number} The smallest power of two that is greater than or equal to the given number.
   */
  ceilPowerOfTwo: R_,
  /**
   * Returns the largest power of two that is less than or equal to the given number.
   *
   * @static
   * @method
   * @param {number} value - The value to find a POT for.
   * @return {number} The largest power of two that is less than or equal to the given number.
   */
  floorPowerOfTwo: P_,
  /**
   * Sets the given quaternion from the [Intrinsic Proper Euler Angles]{@link https://en.wikipedia.org/wiki/Euler_angles}
   * defined by the given angles and order.
   *
   * Rotations are applied to the axes in the order specified by order:
   * rotation by angle `a` is applied first, then by angle `b`, then by angle `c`.
   *
   * @static
   * @method
   * @param {Quaternion} q - The quaternion to set.
   * @param {number} a - The rotation applied to the first axis, in radians.
   * @param {number} b - The rotation applied to the second axis, in radians.
   * @param {number} c - The rotation applied to the third axis, in radians.
   * @param {('XYX'|'XZX'|'YXY'|'YZY'|'ZXZ'|'ZYZ')} order - A string specifying the axes order.
   */
  setQuaternionFromProperEuler: L_,
  /**
   * Normalizes the given value according to the given typed array.
   *
   * @static
   * @method
   * @param {number} value - The float value in the range `[0,1]` to normalize.
   * @param {TypedArray} array - The typed array that defines the data type of the value.
   * @return {number} The normalize value.
   */
  normalize: Xe,
  /**
   * Denormalizes the given value according to the given typed array.
   *
   * @static
   * @method
   * @param {number} value - The value to denormalize.
   * @param {TypedArray} array - The typed array that defines the data type of the value.
   * @return {number} The denormalize (float) value in the range `[0,1]`.
   */
  denormalize: ai
};
class H {
  /**
   * Constructs a new 2D vector.
   *
   * @param {number} [x=0] - The x value of this vector.
   * @param {number} [y=0] - The y value of this vector.
   */
  constructor(e = 0, t = 0) {
    H.prototype.isVector2 = !0, this.x = e, this.y = t;
  }
  /**
   * Alias for {@link Vector2#x}.
   *
   * @type {number}
   */
  get width() {
    return this.x;
  }
  set width(e) {
    this.x = e;
  }
  /**
   * Alias for {@link Vector2#y}.
   *
   * @type {number}
   */
  get height() {
    return this.y;
  }
  set height(e) {
    this.y = e;
  }
  /**
   * Sets the vector components.
   *
   * @param {number} x - The value of the x component.
   * @param {number} y - The value of the y component.
   * @return {Vector2} A reference to this vector.
   */
  set(e, t) {
    return this.x = e, this.y = t, this;
  }
  /**
   * Sets the vector components to the same value.
   *
   * @param {number} scalar - The value to set for all vector components.
   * @return {Vector2} A reference to this vector.
   */
  setScalar(e) {
    return this.x = e, this.y = e, this;
  }
  /**
   * Sets the vector's x component to the given value
   *
   * @param {number} x - The value to set.
   * @return {Vector2} A reference to this vector.
   */
  setX(e) {
    return this.x = e, this;
  }
  /**
   * Sets the vector's y component to the given value
   *
   * @param {number} y - The value to set.
   * @return {Vector2} A reference to this vector.
   */
  setY(e) {
    return this.y = e, this;
  }
  /**
   * Allows to set a vector component with an index.
   *
   * @param {number} index - The component index. `0` equals to x, `1` equals to y.
   * @param {number} value - The value to set.
   * @return {Vector2} A reference to this vector.
   */
  setComponent(e, t) {
    switch (e) {
      case 0:
        this.x = t;
        break;
      case 1:
        this.y = t;
        break;
      default:
        throw new Error("index is out of range: " + e);
    }
    return this;
  }
  /**
   * Returns the value of the vector component which matches the given index.
   *
   * @param {number} index - The component index. `0` equals to x, `1` equals to y.
   * @return {number} A vector component value.
   */
  getComponent(e) {
    switch (e) {
      case 0:
        return this.x;
      case 1:
        return this.y;
      default:
        throw new Error("index is out of range: " + e);
    }
  }
  /**
   * Returns a new vector with copied values from this instance.
   *
   * @return {Vector2} A clone of this instance.
   */
  clone() {
    return new this.constructor(this.x, this.y);
  }
  /**
   * Copies the values of the given vector to this instance.
   *
   * @param {Vector2} v - The vector to copy.
   * @return {Vector2} A reference to this vector.
   */
  copy(e) {
    return this.x = e.x, this.y = e.y, this;
  }
  /**
   * Adds the given vector to this instance.
   *
   * @param {Vector2} v - The vector to add.
   * @return {Vector2} A reference to this vector.
   */
  add(e) {
    return this.x += e.x, this.y += e.y, this;
  }
  /**
   * Adds the given scalar value to all components of this instance.
   *
   * @param {number} s - The scalar to add.
   * @return {Vector2} A reference to this vector.
   */
  addScalar(e) {
    return this.x += e, this.y += e, this;
  }
  /**
   * Adds the given vectors and stores the result in this instance.
   *
   * @param {Vector2} a - The first vector.
   * @param {Vector2} b - The second vector.
   * @return {Vector2} A reference to this vector.
   */
  addVectors(e, t) {
    return this.x = e.x + t.x, this.y = e.y + t.y, this;
  }
  /**
   * Adds the given vector scaled by the given factor to this instance.
   *
   * @param {Vector2} v - The vector.
   * @param {number} s - The factor that scales `v`.
   * @return {Vector2} A reference to this vector.
   */
  addScaledVector(e, t) {
    return this.x += e.x * t, this.y += e.y * t, this;
  }
  /**
   * Subtracts the given vector from this instance.
   *
   * @param {Vector2} v - The vector to subtract.
   * @return {Vector2} A reference to this vector.
   */
  sub(e) {
    return this.x -= e.x, this.y -= e.y, this;
  }
  /**
   * Subtracts the given scalar value from all components of this instance.
   *
   * @param {number} s - The scalar to subtract.
   * @return {Vector2} A reference to this vector.
   */
  subScalar(e) {
    return this.x -= e, this.y -= e, this;
  }
  /**
   * Subtracts the given vectors and stores the result in this instance.
   *
   * @param {Vector2} a - The first vector.
   * @param {Vector2} b - The second vector.
   * @return {Vector2} A reference to this vector.
   */
  subVectors(e, t) {
    return this.x = e.x - t.x, this.y = e.y - t.y, this;
  }
  /**
   * Multiplies the given vector with this instance.
   *
   * @param {Vector2} v - The vector to multiply.
   * @return {Vector2} A reference to this vector.
   */
  multiply(e) {
    return this.x *= e.x, this.y *= e.y, this;
  }
  /**
   * Multiplies the given scalar value with all components of this instance.
   *
   * @param {number} scalar - The scalar to multiply.
   * @return {Vector2} A reference to this vector.
   */
  multiplyScalar(e) {
    return this.x *= e, this.y *= e, this;
  }
  /**
   * Divides this instance by the given vector.
   *
   * @param {Vector2} v - The vector to divide.
   * @return {Vector2} A reference to this vector.
   */
  divide(e) {
    return this.x /= e.x, this.y /= e.y, this;
  }
  /**
   * Divides this vector by the given scalar.
   *
   * @param {number} scalar - The scalar to divide.
   * @return {Vector2} A reference to this vector.
   */
  divideScalar(e) {
    return this.multiplyScalar(1 / e);
  }
  /**
   * Multiplies this vector (with an implicit 1 as the 3rd component) by
   * the given 3x3 matrix.
   *
   * @param {Matrix3} m - The matrix to apply.
   * @return {Vector2} A reference to this vector.
   */
  applyMatrix3(e) {
    const t = this.x, i = this.y, n = e.elements;
    return this.x = n[0] * t + n[3] * i + n[6], this.y = n[1] * t + n[4] * i + n[7], this;
  }
  /**
   * If this vector's x or y value is greater than the given vector's x or y
   * value, replace that value with the corresponding min value.
   *
   * @param {Vector2} v - The vector.
   * @return {Vector2} A reference to this vector.
   */
  min(e) {
    return this.x = Math.min(this.x, e.x), this.y = Math.min(this.y, e.y), this;
  }
  /**
   * If this vector's x or y value is less than the given vector's x or y
   * value, replace that value with the corresponding max value.
   *
   * @param {Vector2} v - The vector.
   * @return {Vector2} A reference to this vector.
   */
  max(e) {
    return this.x = Math.max(this.x, e.x), this.y = Math.max(this.y, e.y), this;
  }
  /**
   * If this vector's x or y value is greater than the max vector's x or y
   * value, it is replaced by the corresponding value.
   * If this vector's x or y value is less than the min vector's x or y value,
   * it is replaced by the corresponding value.
   *
   * @param {Vector2} min - The minimum x and y values.
   * @param {Vector2} max - The maximum x and y values in the desired range.
   * @return {Vector2} A reference to this vector.
   */
  clamp(e, t) {
    return this.x = Fe(this.x, e.x, t.x), this.y = Fe(this.y, e.y, t.y), this;
  }
  /**
   * If this vector's x or y values are greater than the max value, they are
   * replaced by the max value.
   * If this vector's x or y values are less than the min value, they are
   * replaced by the min value.
   *
   * @param {number} minVal - The minimum value the components will be clamped to.
   * @param {number} maxVal - The maximum value the components will be clamped to.
   * @return {Vector2} A reference to this vector.
   */
  clampScalar(e, t) {
    return this.x = Fe(this.x, e, t), this.y = Fe(this.y, e, t), this;
  }
  /**
   * If this vector's length is greater than the max value, it is replaced by
   * the max value.
   * If this vector's length is less than the min value, it is replaced by the
   * min value.
   *
   * @param {number} min - The minimum value the vector length will be clamped to.
   * @param {number} max - The maximum value the vector length will be clamped to.
   * @return {Vector2} A reference to this vector.
   */
  clampLength(e, t) {
    const i = this.length();
    return this.divideScalar(i || 1).multiplyScalar(Fe(i, e, t));
  }
  /**
   * The components of this vector are rounded down to the nearest integer value.
   *
   * @return {Vector2} A reference to this vector.
   */
  floor() {
    return this.x = Math.floor(this.x), this.y = Math.floor(this.y), this;
  }
  /**
   * The components of this vector are rounded up to the nearest integer value.
   *
   * @return {Vector2} A reference to this vector.
   */
  ceil() {
    return this.x = Math.ceil(this.x), this.y = Math.ceil(this.y), this;
  }
  /**
   * The components of this vector are rounded to the nearest integer value
   *
   * @return {Vector2} A reference to this vector.
   */
  round() {
    return this.x = Math.round(this.x), this.y = Math.round(this.y), this;
  }
  /**
   * The components of this vector are rounded towards zero (up if negative,
   * down if positive) to an integer value.
   *
   * @return {Vector2} A reference to this vector.
   */
  roundToZero() {
    return this.x = Math.trunc(this.x), this.y = Math.trunc(this.y), this;
  }
  /**
   * Inverts this vector - i.e. sets x = -x and y = -y.
   *
   * @return {Vector2} A reference to this vector.
   */
  negate() {
    return this.x = -this.x, this.y = -this.y, this;
  }
  /**
   * Calculates the dot product of the given vector with this instance.
   *
   * @param {Vector2} v - The vector to compute the dot product with.
   * @return {number} The result of the dot product.
   */
  dot(e) {
    return this.x * e.x + this.y * e.y;
  }
  /**
   * Calculates the cross product of the given vector with this instance.
   *
   * @param {Vector2} v - The vector to compute the cross product with.
   * @return {number} The result of the cross product.
   */
  cross(e) {
    return this.x * e.y - this.y * e.x;
  }
  /**
   * Computes the square of the Euclidean length (straight-line length) from
   * (0, 0) to (x, y). If you are comparing the lengths of vectors, you should
   * compare the length squared instead as it is slightly more efficient to calculate.
   *
   * @return {number} The square length of this vector.
   */
  lengthSq() {
    return this.x * this.x + this.y * this.y;
  }
  /**
   * Computes the  Euclidean length (straight-line length) from (0, 0) to (x, y).
   *
   * @return {number} The length of this vector.
   */
  length() {
    return Math.sqrt(this.x * this.x + this.y * this.y);
  }
  /**
   * Computes the Manhattan length of this vector.
   *
   * @return {number} The length of this vector.
   */
  manhattanLength() {
    return Math.abs(this.x) + Math.abs(this.y);
  }
  /**
   * Converts this vector to a unit vector - that is, sets it equal to a vector
   * with the same direction as this one, but with a vector length of `1`.
   *
   * @return {Vector2} A reference to this vector.
   */
  normalize() {
    return this.divideScalar(this.length() || 1);
  }
  /**
   * Computes the angle in radians of this vector with respect to the positive x-axis.
   *
   * @return {number} The angle in radians.
   */
  angle() {
    return Math.atan2(-this.y, -this.x) + Math.PI;
  }
  /**
   * Returns the angle between the given vector and this instance in radians.
   *
   * @param {Vector2} v - The vector to compute the angle with.
   * @return {number} The angle in radians.
   */
  angleTo(e) {
    const t = Math.sqrt(this.lengthSq() * e.lengthSq());
    if (t === 0) return Math.PI / 2;
    const i = this.dot(e) / t;
    return Math.acos(Fe(i, -1, 1));
  }
  /**
   * Computes the distance from the given vector to this instance.
   *
   * @param {Vector2} v - The vector to compute the distance to.
   * @return {number} The distance.
   */
  distanceTo(e) {
    return Math.sqrt(this.distanceToSquared(e));
  }
  /**
   * Computes the squared distance from the given vector to this instance.
   * If you are just comparing the distance with another distance, you should compare
   * the distance squared instead as it is slightly more efficient to calculate.
   *
   * @param {Vector2} v - The vector to compute the squared distance to.
   * @return {number} The squared distance.
   */
  distanceToSquared(e) {
    const t = this.x - e.x, i = this.y - e.y;
    return t * t + i * i;
  }
  /**
   * Computes the Manhattan distance from the given vector to this instance.
   *
   * @param {Vector2} v - The vector to compute the Manhattan distance to.
   * @return {number} The Manhattan distance.
   */
  manhattanDistanceTo(e) {
    return Math.abs(this.x - e.x) + Math.abs(this.y - e.y);
  }
  /**
   * Sets this vector to a vector with the same direction as this one, but
   * with the specified length.
   *
   * @param {number} length - The new length of this vector.
   * @return {Vector2} A reference to this vector.
   */
  setLength(e) {
    return this.normalize().multiplyScalar(e);
  }
  /**
   * Linearly interpolates between the given vector and this instance, where
   * alpha is the percent distance along the line - alpha = 0 will be this
   * vector, and alpha = 1 will be the given one.
   *
   * @param {Vector2} v - The vector to interpolate towards.
   * @param {number} alpha - The interpolation factor, typically in the closed interval `[0, 1]`.
   * @return {Vector2} A reference to this vector.
   */
  lerp(e, t) {
    return this.x += (e.x - this.x) * t, this.y += (e.y - this.y) * t, this;
  }
  /**
   * Linearly interpolates between the given vectors, where alpha is the percent
   * distance along the line - alpha = 0 will be first vector, and alpha = 1 will
   * be the second one. The result is stored in this instance.
   *
   * @param {Vector2} v1 - The first vector.
   * @param {Vector2} v2 - The second vector.
   * @param {number} alpha - The interpolation factor, typically in the closed interval `[0, 1]`.
   * @return {Vector2} A reference to this vector.
   */
  lerpVectors(e, t, i) {
    return this.x = e.x + (t.x - e.x) * i, this.y = e.y + (t.y - e.y) * i, this;
  }
  /**
   * Returns `true` if this vector is equal with the given one.
   *
   * @param {Vector2} v - The vector to test for equality.
   * @return {boolean} Whether this vector is equal with the given one.
   */
  equals(e) {
    return e.x === this.x && e.y === this.y;
  }
  /**
   * Sets this vector's x value to be `array[ offset ]` and y
   * value to be `array[ offset + 1 ]`.
   *
   * @param {Array<number>} array - An array holding the vector component values.
   * @param {number} [offset=0] - The offset into the array.
   * @return {Vector2} A reference to this vector.
   */
  fromArray(e, t = 0) {
    return this.x = e[t], this.y = e[t + 1], this;
  }
  /**
   * Writes the components of this vector to the given array. If no array is provided,
   * the method returns a new instance.
   *
   * @param {Array<number>} [array=[]] - The target array holding the vector components.
   * @param {number} [offset=0] - Index of the first element in the array.
   * @return {Array<number>} The vector components.
   */
  toArray(e = [], t = 0) {
    return e[t] = this.x, e[t + 1] = this.y, e;
  }
  /**
   * Sets the components of this vector from the given buffer attribute.
   *
   * @param {BufferAttribute} attribute - The buffer attribute holding vector data.
   * @param {number} index - The index into the attribute.
   * @return {Vector2} A reference to this vector.
   */
  fromBufferAttribute(e, t) {
    return this.x = e.getX(t), this.y = e.getY(t), this;
  }
  /**
   * Rotates this vector around the given center by the given angle.
   *
   * @param {Vector2} center - The point around which to rotate.
   * @param {number} angle - The angle to rotate, in radians.
   * @return {Vector2} A reference to this vector.
   */
  rotateAround(e, t) {
    const i = Math.cos(t), n = Math.sin(t), s = this.x - e.x, a = this.y - e.y;
    return this.x = s * i - a * n + e.x, this.y = s * n + a * i + e.y, this;
  }
  /**
   * Sets each component of this vector to a pseudo-random value between `0` and
   * `1`, excluding `1`.
   *
   * @return {Vector2} A reference to this vector.
   */
  random() {
    return this.x = Math.random(), this.y = Math.random(), this;
  }
  *[Symbol.iterator]() {
    yield this.x, yield this.y;
  }
}
class ot {
  /**
   * Constructs a new quaternion.
   *
   * @param {number} [x=0] - The x value of this quaternion.
   * @param {number} [y=0] - The y value of this quaternion.
   * @param {number} [z=0] - The z value of this quaternion.
   * @param {number} [w=1] - The w value of this quaternion.
   */
  constructor(e = 0, t = 0, i = 0, n = 1) {
    this.isQuaternion = !0, this._x = e, this._y = t, this._z = i, this._w = n;
  }
  /**
   * Interpolates between two quaternions via SLERP. This implementation assumes the
   * quaternion data are managed  in flat arrays.
   *
   * @param {Array<number>} dst - The destination array.
   * @param {number} dstOffset - An offset into the destination array.
   * @param {Array<number>} src0 - The source array of the first quaternion.
   * @param {number} srcOffset0 - An offset into the first source array.
   * @param {Array<number>} src1 -  The source array of the second quaternion.
   * @param {number} srcOffset1 - An offset into the second source array.
   * @param {number} t - The interpolation factor in the range `[0,1]`.
   * @see {@link Quaternion#slerp}
   */
  static slerpFlat(e, t, i, n, s, a, o) {
    let l = i[n + 0], c = i[n + 1], h = i[n + 2], d = i[n + 3];
    const u = s[a + 0], p = s[a + 1], m = s[a + 2], _ = s[a + 3];
    if (o === 0) {
      e[t + 0] = l, e[t + 1] = c, e[t + 2] = h, e[t + 3] = d;
      return;
    }
    if (o === 1) {
      e[t + 0] = u, e[t + 1] = p, e[t + 2] = m, e[t + 3] = _;
      return;
    }
    if (d !== _ || l !== u || c !== p || h !== m) {
      let g = 1 - o;
      const f = l * u + c * p + h * m + d * _, v = f >= 0 ? 1 : -1, x = 1 - f * f;
      if (x > Number.EPSILON) {
        const A = Math.sqrt(x), S = Math.atan2(A, f * v);
        g = Math.sin(g * S) / A, o = Math.sin(o * S) / A;
      }
      const y = o * v;
      if (l = l * g + u * y, c = c * g + p * y, h = h * g + m * y, d = d * g + _ * y, g === 1 - o) {
        const A = 1 / Math.sqrt(l * l + c * c + h * h + d * d);
        l *= A, c *= A, h *= A, d *= A;
      }
    }
    e[t] = l, e[t + 1] = c, e[t + 2] = h, e[t + 3] = d;
  }
  /**
   * Multiplies two quaternions. This implementation assumes the quaternion data are managed
   * in flat arrays.
   *
   * @param {Array<number>} dst - The destination array.
   * @param {number} dstOffset - An offset into the destination array.
   * @param {Array<number>} src0 - The source array of the first quaternion.
   * @param {number} srcOffset0 - An offset into the first source array.
   * @param {Array<number>} src1 -  The source array of the second quaternion.
   * @param {number} srcOffset1 - An offset into the second source array.
   * @return {Array<number>} The destination array.
   * @see {@link Quaternion#multiplyQuaternions}.
   */
  static multiplyQuaternionsFlat(e, t, i, n, s, a) {
    const o = i[n], l = i[n + 1], c = i[n + 2], h = i[n + 3], d = s[a], u = s[a + 1], p = s[a + 2], m = s[a + 3];
    return e[t] = o * m + h * d + l * p - c * u, e[t + 1] = l * m + h * u + c * d - o * p, e[t + 2] = c * m + h * p + o * u - l * d, e[t + 3] = h * m - o * d - l * u - c * p, e;
  }
  /**
   * The x value of this quaternion.
   *
   * @type {number}
   * @default 0
   */
  get x() {
    return this._x;
  }
  set x(e) {
    this._x = e, this._onChangeCallback();
  }
  /**
   * The y value of this quaternion.
   *
   * @type {number}
   * @default 0
   */
  get y() {
    return this._y;
  }
  set y(e) {
    this._y = e, this._onChangeCallback();
  }
  /**
   * The z value of this quaternion.
   *
   * @type {number}
   * @default 0
   */
  get z() {
    return this._z;
  }
  set z(e) {
    this._z = e, this._onChangeCallback();
  }
  /**
   * The w value of this quaternion.
   *
   * @type {number}
   * @default 1
   */
  get w() {
    return this._w;
  }
  set w(e) {
    this._w = e, this._onChangeCallback();
  }
  /**
   * Sets the quaternion components.
   *
   * @param {number} x - The x value of this quaternion.
   * @param {number} y - The y value of this quaternion.
   * @param {number} z - The z value of this quaternion.
   * @param {number} w - The w value of this quaternion.
   * @return {Quaternion} A reference to this quaternion.
   */
  set(e, t, i, n) {
    return this._x = e, this._y = t, this._z = i, this._w = n, this._onChangeCallback(), this;
  }
  /**
   * Returns a new quaternion with copied values from this instance.
   *
   * @return {Quaternion} A clone of this instance.
   */
  clone() {
    return new this.constructor(this._x, this._y, this._z, this._w);
  }
  /**
   * Copies the values of the given quaternion to this instance.
   *
   * @param {Quaternion} quaternion - The quaternion to copy.
   * @return {Quaternion} A reference to this quaternion.
   */
  copy(e) {
    return this._x = e.x, this._y = e.y, this._z = e.z, this._w = e.w, this._onChangeCallback(), this;
  }
  /**
   * Sets this quaternion from the rotation specified by the given
   * Euler angles.
   *
   * @param {Euler} euler - The Euler angles.
   * @param {boolean} [update=true] - Whether the internal `onChange` callback should be executed or not.
   * @return {Quaternion} A reference to this quaternion.
   */
  setFromEuler(e, t = !0) {
    const i = e._x, n = e._y, s = e._z, a = e._order, o = Math.cos, l = Math.sin, c = o(i / 2), h = o(n / 2), d = o(s / 2), u = l(i / 2), p = l(n / 2), m = l(s / 2);
    switch (a) {
      case "XYZ":
        this._x = u * h * d + c * p * m, this._y = c * p * d - u * h * m, this._z = c * h * m + u * p * d, this._w = c * h * d - u * p * m;
        break;
      case "YXZ":
        this._x = u * h * d + c * p * m, this._y = c * p * d - u * h * m, this._z = c * h * m - u * p * d, this._w = c * h * d + u * p * m;
        break;
      case "ZXY":
        this._x = u * h * d - c * p * m, this._y = c * p * d + u * h * m, this._z = c * h * m + u * p * d, this._w = c * h * d - u * p * m;
        break;
      case "ZYX":
        this._x = u * h * d - c * p * m, this._y = c * p * d + u * h * m, this._z = c * h * m - u * p * d, this._w = c * h * d + u * p * m;
        break;
      case "YZX":
        this._x = u * h * d + c * p * m, this._y = c * p * d + u * h * m, this._z = c * h * m - u * p * d, this._w = c * h * d - u * p * m;
        break;
      case "XZY":
        this._x = u * h * d - c * p * m, this._y = c * p * d - u * h * m, this._z = c * h * m + u * p * d, this._w = c * h * d + u * p * m;
        break;
      default:
        console.warn("THREE.Quaternion: .setFromEuler() encountered an unknown order: " + a);
    }
    return t === !0 && this._onChangeCallback(), this;
  }
  /**
   * Sets this quaternion from the given axis and angle.
   *
   * @param {Vector3} axis - The normalized axis.
   * @param {number} angle - The angle in radians.
   * @return {Quaternion} A reference to this quaternion.
   */
  setFromAxisAngle(e, t) {
    const i = t / 2, n = Math.sin(i);
    return this._x = e.x * n, this._y = e.y * n, this._z = e.z * n, this._w = Math.cos(i), this._onChangeCallback(), this;
  }
  /**
   * Sets this quaternion from the given rotation matrix.
   *
   * @param {Matrix4} m - A 4x4 matrix of which the upper 3x3 of matrix is a pure rotation matrix (i.e. unscaled).
   * @return {Quaternion} A reference to this quaternion.
   */
  setFromRotationMatrix(e) {
    const t = e.elements, i = t[0], n = t[4], s = t[8], a = t[1], o = t[5], l = t[9], c = t[2], h = t[6], d = t[10], u = i + o + d;
    if (u > 0) {
      const p = 0.5 / Math.sqrt(u + 1);
      this._w = 0.25 / p, this._x = (h - l) * p, this._y = (s - c) * p, this._z = (a - n) * p;
    } else if (i > o && i > d) {
      const p = 2 * Math.sqrt(1 + i - o - d);
      this._w = (h - l) / p, this._x = 0.25 * p, this._y = (n + a) / p, this._z = (s + c) / p;
    } else if (o > d) {
      const p = 2 * Math.sqrt(1 + o - i - d);
      this._w = (s - c) / p, this._x = (n + a) / p, this._y = 0.25 * p, this._z = (l + h) / p;
    } else {
      const p = 2 * Math.sqrt(1 + d - i - o);
      this._w = (a - n) / p, this._x = (s + c) / p, this._y = (l + h) / p, this._z = 0.25 * p;
    }
    return this._onChangeCallback(), this;
  }
  /**
   * Sets this quaternion to the rotation required to rotate the direction vector
   * `vFrom` to the direction vector `vTo`.
   *
   * @param {Vector3} vFrom - The first (normalized) direction vector.
   * @param {Vector3} vTo - The second (normalized) direction vector.
   * @return {Quaternion} A reference to this quaternion.
   */
  setFromUnitVectors(e, t) {
    let i = e.dot(t) + 1;
    return i < 1e-8 ? (i = 0, Math.abs(e.x) > Math.abs(e.z) ? (this._x = -e.y, this._y = e.x, this._z = 0, this._w = i) : (this._x = 0, this._y = -e.z, this._z = e.y, this._w = i)) : (this._x = e.y * t.z - e.z * t.y, this._y = e.z * t.x - e.x * t.z, this._z = e.x * t.y - e.y * t.x, this._w = i), this.normalize();
  }
  /**
   * Returns the angle between this quaternion and the given one in radians.
   *
   * @param {Quaternion} q - The quaternion to compute the angle with.
   * @return {number} The angle in radians.
   */
  angleTo(e) {
    return 2 * Math.acos(Math.abs(Fe(this.dot(e), -1, 1)));
  }
  /**
   * Rotates this quaternion by a given angular step to the given quaternion.
   * The method ensures that the final quaternion will not overshoot `q`.
   *
   * @param {Quaternion} q - The target quaternion.
   * @param {number} step - The angular step in radians.
   * @return {Quaternion} A reference to this quaternion.
   */
  rotateTowards(e, t) {
    const i = this.angleTo(e);
    if (i === 0) return this;
    const n = Math.min(1, t / i);
    return this.slerp(e, n), this;
  }
  /**
   * Sets this quaternion to the identity quaternion; that is, to the
   * quaternion that represents "no rotation".
   *
   * @return {Quaternion} A reference to this quaternion.
   */
  identity() {
    return this.set(0, 0, 0, 1);
  }
  /**
   * Inverts this quaternion via {@link Quaternion#conjugate}. The
   * quaternion is assumed to have unit length.
   *
   * @return {Quaternion} A reference to this quaternion.
   */
  invert() {
    return this.conjugate();
  }
  /**
   * Returns the rotational conjugate of this quaternion. The conjugate of a
   * quaternion represents the same rotation in the opposite direction about
   * the rotational axis.
   *
   * @return {Quaternion} A reference to this quaternion.
   */
  conjugate() {
    return this._x *= -1, this._y *= -1, this._z *= -1, this._onChangeCallback(), this;
  }
  /**
   * Calculates the dot product of this quaternion and the given one.
   *
   * @param {Quaternion} v - The quaternion to compute the dot product with.
   * @return {number} The result of the dot product.
   */
  dot(e) {
    return this._x * e._x + this._y * e._y + this._z * e._z + this._w * e._w;
  }
  /**
   * Computes the squared Euclidean length (straight-line length) of this quaternion,
   * considered as a 4 dimensional vector. This can be useful if you are comparing the
   * lengths of two quaternions, as this is a slightly more efficient calculation than
   * {@link Quaternion#length}.
   *
   * @return {number} The squared Euclidean length.
   */
  lengthSq() {
    return this._x * this._x + this._y * this._y + this._z * this._z + this._w * this._w;
  }
  /**
   * Computes the Euclidean length (straight-line length) of this quaternion,
   * considered as a 4 dimensional vector.
   *
   * @return {number} The Euclidean length.
   */
  length() {
    return Math.sqrt(this._x * this._x + this._y * this._y + this._z * this._z + this._w * this._w);
  }
  /**
   * Normalizes this quaternion - that is, calculated the quaternion that performs
   * the same rotation as this one, but has a length equal to `1`.
   *
   * @return {Quaternion} A reference to this quaternion.
   */
  normalize() {
    let e = this.length();
    return e === 0 ? (this._x = 0, this._y = 0, this._z = 0, this._w = 1) : (e = 1 / e, this._x = this._x * e, this._y = this._y * e, this._z = this._z * e, this._w = this._w * e), this._onChangeCallback(), this;
  }
  /**
   * Multiplies this quaternion by the given one.
   *
   * @param {Quaternion} q - The quaternion.
   * @return {Quaternion} A reference to this quaternion.
   */
  multiply(e) {
    return this.multiplyQuaternions(this, e);
  }
  /**
   * Pre-multiplies this quaternion by the given one.
   *
   * @param {Quaternion} q - The quaternion.
   * @return {Quaternion} A reference to this quaternion.
   */
  premultiply(e) {
    return this.multiplyQuaternions(e, this);
  }
  /**
   * Multiplies the given quaternions and stores the result in this instance.
   *
   * @param {Quaternion} a - The first quaternion.
   * @param {Quaternion} b - The second quaternion.
   * @return {Quaternion} A reference to this quaternion.
   */
  multiplyQuaternions(e, t) {
    const i = e._x, n = e._y, s = e._z, a = e._w, o = t._x, l = t._y, c = t._z, h = t._w;
    return this._x = i * h + a * o + n * c - s * l, this._y = n * h + a * l + s * o - i * c, this._z = s * h + a * c + i * l - n * o, this._w = a * h - i * o - n * l - s * c, this._onChangeCallback(), this;
  }
  /**
   * Performs a spherical linear interpolation between quaternions.
   *
   * @param {Quaternion} qb - The target quaternion.
   * @param {number} t - The interpolation factor in the closed interval `[0, 1]`.
   * @return {Quaternion} A reference to this quaternion.
   */
  slerp(e, t) {
    if (t === 0) return this;
    if (t === 1) return this.copy(e);
    const i = this._x, n = this._y, s = this._z, a = this._w;
    let o = a * e._w + i * e._x + n * e._y + s * e._z;
    if (o < 0 ? (this._w = -e._w, this._x = -e._x, this._y = -e._y, this._z = -e._z, o = -o) : this.copy(e), o >= 1)
      return this._w = a, this._x = i, this._y = n, this._z = s, this;
    const l = 1 - o * o;
    if (l <= Number.EPSILON) {
      const p = 1 - t;
      return this._w = p * a + t * this._w, this._x = p * i + t * this._x, this._y = p * n + t * this._y, this._z = p * s + t * this._z, this.normalize(), this;
    }
    const c = Math.sqrt(l), h = Math.atan2(c, o), d = Math.sin((1 - t) * h) / c, u = Math.sin(t * h) / c;
    return this._w = a * d + this._w * u, this._x = i * d + this._x * u, this._y = n * d + this._y * u, this._z = s * d + this._z * u, this._onChangeCallback(), this;
  }
  /**
   * Performs a spherical linear interpolation between the given quaternions
   * and stores the result in this quaternion.
   *
   * @param {Quaternion} qa - The source quaternion.
   * @param {Quaternion} qb - The target quaternion.
   * @param {number} t - The interpolation factor in the closed interval `[0, 1]`.
   * @return {Quaternion} A reference to this quaternion.
   */
  slerpQuaternions(e, t, i) {
    return this.copy(e).slerp(t, i);
  }
  /**
   * Sets this quaternion to a uniformly random, normalized quaternion.
   *
   * @return {Quaternion} A reference to this quaternion.
   */
  random() {
    const e = 2 * Math.PI * Math.random(), t = 2 * Math.PI * Math.random(), i = Math.random(), n = Math.sqrt(1 - i), s = Math.sqrt(i);
    return this.set(
      n * Math.sin(e),
      n * Math.cos(e),
      s * Math.sin(t),
      s * Math.cos(t)
    );
  }
  /**
   * Returns `true` if this quaternion is equal with the given one.
   *
   * @param {Quaternion} quaternion - The quaternion to test for equality.
   * @return {boolean} Whether this quaternion is equal with the given one.
   */
  equals(e) {
    return e._x === this._x && e._y === this._y && e._z === this._z && e._w === this._w;
  }
  /**
   * Sets this quaternion's components from the given array.
   *
   * @param {Array<number>} array - An array holding the quaternion component values.
   * @param {number} [offset=0] - The offset into the array.
   * @return {Quaternion} A reference to this quaternion.
   */
  fromArray(e, t = 0) {
    return this._x = e[t], this._y = e[t + 1], this._z = e[t + 2], this._w = e[t + 3], this._onChangeCallback(), this;
  }
  /**
   * Writes the components of this quaternion to the given array. If no array is provided,
   * the method returns a new instance.
   *
   * @param {Array<number>} [array=[]] - The target array holding the quaternion components.
   * @param {number} [offset=0] - Index of the first element in the array.
   * @return {Array<number>} The quaternion components.
   */
  toArray(e = [], t = 0) {
    return e[t] = this._x, e[t + 1] = this._y, e[t + 2] = this._z, e[t + 3] = this._w, e;
  }
  /**
   * Sets the components of this quaternion from the given buffer attribute.
   *
   * @param {BufferAttribute} attribute - The buffer attribute holding quaternion data.
   * @param {number} index - The index into the attribute.
   * @return {Quaternion} A reference to this quaternion.
   */
  fromBufferAttribute(e, t) {
    return this._x = e.getX(t), this._y = e.getY(t), this._z = e.getZ(t), this._w = e.getW(t), this._onChangeCallback(), this;
  }
  /**
   * This methods defines the serialization result of this class. Returns the
   * numerical elements of this quaternion in an array of format `[x, y, z, w]`.
   *
   * @return {Array<number>} The serialized quaternion.
   */
  toJSON() {
    return this.toArray();
  }
  _onChange(e) {
    return this._onChangeCallback = e, this;
  }
  _onChangeCallback() {
  }
  *[Symbol.iterator]() {
    yield this._x, yield this._y, yield this._z, yield this._w;
  }
}
class b {
  /**
   * Constructs a new 3D vector.
   *
   * @param {number} [x=0] - The x value of this vector.
   * @param {number} [y=0] - The y value of this vector.
   * @param {number} [z=0] - The z value of this vector.
   */
  constructor(e = 0, t = 0, i = 0) {
    b.prototype.isVector3 = !0, this.x = e, this.y = t, this.z = i;
  }
  /**
   * Sets the vector components.
   *
   * @param {number} x - The value of the x component.
   * @param {number} y - The value of the y component.
   * @param {number} z - The value of the z component.
   * @return {Vector3} A reference to this vector.
   */
  set(e, t, i) {
    return i === void 0 && (i = this.z), this.x = e, this.y = t, this.z = i, this;
  }
  /**
   * Sets the vector components to the same value.
   *
   * @param {number} scalar - The value to set for all vector components.
   * @return {Vector3} A reference to this vector.
   */
  setScalar(e) {
    return this.x = e, this.y = e, this.z = e, this;
  }
  /**
   * Sets the vector's x component to the given value
   *
   * @param {number} x - The value to set.
   * @return {Vector3} A reference to this vector.
   */
  setX(e) {
    return this.x = e, this;
  }
  /**
   * Sets the vector's y component to the given value
   *
   * @param {number} y - The value to set.
   * @return {Vector3} A reference to this vector.
   */
  setY(e) {
    return this.y = e, this;
  }
  /**
   * Sets the vector's z component to the given value
   *
   * @param {number} z - The value to set.
   * @return {Vector3} A reference to this vector.
   */
  setZ(e) {
    return this.z = e, this;
  }
  /**
   * Allows to set a vector component with an index.
   *
   * @param {number} index - The component index. `0` equals to x, `1` equals to y, `2` equals to z.
   * @param {number} value - The value to set.
   * @return {Vector3} A reference to this vector.
   */
  setComponent(e, t) {
    switch (e) {
      case 0:
        this.x = t;
        break;
      case 1:
        this.y = t;
        break;
      case 2:
        this.z = t;
        break;
      default:
        throw new Error("index is out of range: " + e);
    }
    return this;
  }
  /**
   * Returns the value of the vector component which matches the given index.
   *
   * @param {number} index - The component index. `0` equals to x, `1` equals to y, `2` equals to z.
   * @return {number} A vector component value.
   */
  getComponent(e) {
    switch (e) {
      case 0:
        return this.x;
      case 1:
        return this.y;
      case 2:
        return this.z;
      default:
        throw new Error("index is out of range: " + e);
    }
  }
  /**
   * Returns a new vector with copied values from this instance.
   *
   * @return {Vector3} A clone of this instance.
   */
  clone() {
    return new this.constructor(this.x, this.y, this.z);
  }
  /**
   * Copies the values of the given vector to this instance.
   *
   * @param {Vector3} v - The vector to copy.
   * @return {Vector3} A reference to this vector.
   */
  copy(e) {
    return this.x = e.x, this.y = e.y, this.z = e.z, this;
  }
  /**
   * Adds the given vector to this instance.
   *
   * @param {Vector3} v - The vector to add.
   * @return {Vector3} A reference to this vector.
   */
  add(e) {
    return this.x += e.x, this.y += e.y, this.z += e.z, this;
  }
  /**
   * Adds the given scalar value to all components of this instance.
   *
   * @param {number} s - The scalar to add.
   * @return {Vector3} A reference to this vector.
   */
  addScalar(e) {
    return this.x += e, this.y += e, this.z += e, this;
  }
  /**
   * Adds the given vectors and stores the result in this instance.
   *
   * @param {Vector3} a - The first vector.
   * @param {Vector3} b - The second vector.
   * @return {Vector3} A reference to this vector.
   */
  addVectors(e, t) {
    return this.x = e.x + t.x, this.y = e.y + t.y, this.z = e.z + t.z, this;
  }
  /**
   * Adds the given vector scaled by the given factor to this instance.
   *
   * @param {Vector3|Vector4} v - The vector.
   * @param {number} s - The factor that scales `v`.
   * @return {Vector3} A reference to this vector.
   */
  addScaledVector(e, t) {
    return this.x += e.x * t, this.y += e.y * t, this.z += e.z * t, this;
  }
  /**
   * Subtracts the given vector from this instance.
   *
   * @param {Vector3} v - The vector to subtract.
   * @return {Vector3} A reference to this vector.
   */
  sub(e) {
    return this.x -= e.x, this.y -= e.y, this.z -= e.z, this;
  }
  /**
   * Subtracts the given scalar value from all components of this instance.
   *
   * @param {number} s - The scalar to subtract.
   * @return {Vector3} A reference to this vector.
   */
  subScalar(e) {
    return this.x -= e, this.y -= e, this.z -= e, this;
  }
  /**
   * Subtracts the given vectors and stores the result in this instance.
   *
   * @param {Vector3} a - The first vector.
   * @param {Vector3} b - The second vector.
   * @return {Vector3} A reference to this vector.
   */
  subVectors(e, t) {
    return this.x = e.x - t.x, this.y = e.y - t.y, this.z = e.z - t.z, this;
  }
  /**
   * Multiplies the given vector with this instance.
   *
   * @param {Vector3} v - The vector to multiply.
   * @return {Vector3} A reference to this vector.
   */
  multiply(e) {
    return this.x *= e.x, this.y *= e.y, this.z *= e.z, this;
  }
  /**
   * Multiplies the given scalar value with all components of this instance.
   *
   * @param {number} scalar - The scalar to multiply.
   * @return {Vector3} A reference to this vector.
   */
  multiplyScalar(e) {
    return this.x *= e, this.y *= e, this.z *= e, this;
  }
  /**
   * Multiplies the given vectors and stores the result in this instance.
   *
   * @param {Vector3} a - The first vector.
   * @param {Vector3} b - The second vector.
   * @return {Vector3} A reference to this vector.
   */
  multiplyVectors(e, t) {
    return this.x = e.x * t.x, this.y = e.y * t.y, this.z = e.z * t.z, this;
  }
  /**
   * Applies the given Euler rotation to this vector.
   *
   * @param {Euler} euler - The Euler angles.
   * @return {Vector3} A reference to this vector.
   */
  applyEuler(e) {
    return this.applyQuaternion(iu.setFromEuler(e));
  }
  /**
   * Applies a rotation specified by an axis and an angle to this vector.
   *
   * @param {Vector3} axis - A normalized vector representing the rotation axis.
   * @param {number} angle - The angle in radians.
   * @return {Vector3} A reference to this vector.
   */
  applyAxisAngle(e, t) {
    return this.applyQuaternion(iu.setFromAxisAngle(e, t));
  }
  /**
   * Multiplies this vector with the given 3x3 matrix.
   *
   * @param {Matrix3} m - The 3x3 matrix.
   * @return {Vector3} A reference to this vector.
   */
  applyMatrix3(e) {
    const t = this.x, i = this.y, n = this.z, s = e.elements;
    return this.x = s[0] * t + s[3] * i + s[6] * n, this.y = s[1] * t + s[4] * i + s[7] * n, this.z = s[2] * t + s[5] * i + s[8] * n, this;
  }
  /**
   * Multiplies this vector by the given normal matrix and normalizes
   * the result.
   *
   * @param {Matrix3} m - The normal matrix.
   * @return {Vector3} A reference to this vector.
   */
  applyNormalMatrix(e) {
    return this.applyMatrix3(e).normalize();
  }
  /**
   * Multiplies this vector (with an implicit 1 in the 4th dimension) by m, and
   * divides by perspective.
   *
   * @param {Matrix4} m - The matrix to apply.
   * @return {Vector3} A reference to this vector.
   */
  applyMatrix4(e) {
    const t = this.x, i = this.y, n = this.z, s = e.elements, a = 1 / (s[3] * t + s[7] * i + s[11] * n + s[15]);
    return this.x = (s[0] * t + s[4] * i + s[8] * n + s[12]) * a, this.y = (s[1] * t + s[5] * i + s[9] * n + s[13]) * a, this.z = (s[2] * t + s[6] * i + s[10] * n + s[14]) * a, this;
  }
  /**
   * Applies the given Quaternion to this vector.
   *
   * @param {Quaternion} q - The Quaternion.
   * @return {Vector3} A reference to this vector.
   */
  applyQuaternion(e) {
    const t = this.x, i = this.y, n = this.z, s = e.x, a = e.y, o = e.z, l = e.w, c = 2 * (a * n - o * i), h = 2 * (o * t - s * n), d = 2 * (s * i - a * t);
    return this.x = t + l * c + a * d - o * h, this.y = i + l * h + o * c - s * d, this.z = n + l * d + s * h - a * c, this;
  }
  /**
   * Projects this vector from world space into the camera's normalized
   * device coordinate (NDC) space.
   *
   * @param {Camera} camera - The camera.
   * @return {Vector3} A reference to this vector.
   */
  project(e) {
    return this.applyMatrix4(e.matrixWorldInverse).applyMatrix4(e.projectionMatrix);
  }
  /**
   * Unprojects this vector from the camera's normalized device coordinate (NDC)
   * space into world space.
   *
   * @param {Camera} camera - The camera.
   * @return {Vector3} A reference to this vector.
   */
  unproject(e) {
    return this.applyMatrix4(e.projectionMatrixInverse).applyMatrix4(e.matrixWorld);
  }
  /**
   * Transforms the direction of this vector by a matrix (the upper left 3 x 3
   * subset of the given 4x4 matrix and then normalizes the result.
   *
   * @param {Matrix4} m - The matrix.
   * @return {Vector3} A reference to this vector.
   */
  transformDirection(e) {
    const t = this.x, i = this.y, n = this.z, s = e.elements;
    return this.x = s[0] * t + s[4] * i + s[8] * n, this.y = s[1] * t + s[5] * i + s[9] * n, this.z = s[2] * t + s[6] * i + s[10] * n, this.normalize();
  }
  /**
   * Divides this instance by the given vector.
   *
   * @param {Vector3} v - The vector to divide.
   * @return {Vector3} A reference to this vector.
   */
  divide(e) {
    return this.x /= e.x, this.y /= e.y, this.z /= e.z, this;
  }
  /**
   * Divides this vector by the given scalar.
   *
   * @param {number} scalar - The scalar to divide.
   * @return {Vector3} A reference to this vector.
   */
  divideScalar(e) {
    return this.multiplyScalar(1 / e);
  }
  /**
   * If this vector's x, y or z value is greater than the given vector's x, y or z
   * value, replace that value with the corresponding min value.
   *
   * @param {Vector3} v - The vector.
   * @return {Vector3} A reference to this vector.
   */
  min(e) {
    return this.x = Math.min(this.x, e.x), this.y = Math.min(this.y, e.y), this.z = Math.min(this.z, e.z), this;
  }
  /**
   * If this vector's x, y or z value is less than the given vector's x, y or z
   * value, replace that value with the corresponding max value.
   *
   * @param {Vector3} v - The vector.
   * @return {Vector3} A reference to this vector.
   */
  max(e) {
    return this.x = Math.max(this.x, e.x), this.y = Math.max(this.y, e.y), this.z = Math.max(this.z, e.z), this;
  }
  /**
   * If this vector's x, y or z value is greater than the max vector's x, y or z
   * value, it is replaced by the corresponding value.
   * If this vector's x, y or z value is less than the min vector's x, y or z value,
   * it is replaced by the corresponding value.
   *
   * @param {Vector3} min - The minimum x, y and z values.
   * @param {Vector3} max - The maximum x, y and z values in the desired range.
   * @return {Vector3} A reference to this vector.
   */
  clamp(e, t) {
    return this.x = Fe(this.x, e.x, t.x), this.y = Fe(this.y, e.y, t.y), this.z = Fe(this.z, e.z, t.z), this;
  }
  /**
   * If this vector's x, y or z values are greater than the max value, they are
   * replaced by the max value.
   * If this vector's x, y or z values are less than the min value, they are
   * replaced by the min value.
   *
   * @param {number} minVal - The minimum value the components will be clamped to.
   * @param {number} maxVal - The maximum value the components will be clamped to.
   * @return {Vector3} A reference to this vector.
   */
  clampScalar(e, t) {
    return this.x = Fe(this.x, e, t), this.y = Fe(this.y, e, t), this.z = Fe(this.z, e, t), this;
  }
  /**
   * If this vector's length is greater than the max value, it is replaced by
   * the max value.
   * If this vector's length is less than the min value, it is replaced by the
   * min value.
   *
   * @param {number} min - The minimum value the vector length will be clamped to.
   * @param {number} max - The maximum value the vector length will be clamped to.
   * @return {Vector3} A reference to this vector.
   */
  clampLength(e, t) {
    const i = this.length();
    return this.divideScalar(i || 1).multiplyScalar(Fe(i, e, t));
  }
  /**
   * The components of this vector are rounded down to the nearest integer value.
   *
   * @return {Vector3} A reference to this vector.
   */
  floor() {
    return this.x = Math.floor(this.x), this.y = Math.floor(this.y), this.z = Math.floor(this.z), this;
  }
  /**
   * The components of this vector are rounded up to the nearest integer value.
   *
   * @return {Vector3} A reference to this vector.
   */
  ceil() {
    return this.x = Math.ceil(this.x), this.y = Math.ceil(this.y), this.z = Math.ceil(this.z), this;
  }
  /**
   * The components of this vector are rounded to the nearest integer value
   *
   * @return {Vector3} A reference to this vector.
   */
  round() {
    return this.x = Math.round(this.x), this.y = Math.round(this.y), this.z = Math.round(this.z), this;
  }
  /**
   * The components of this vector are rounded towards zero (up if negative,
   * down if positive) to an integer value.
   *
   * @return {Vector3} A reference to this vector.
   */
  roundToZero() {
    return this.x = Math.trunc(this.x), this.y = Math.trunc(this.y), this.z = Math.trunc(this.z), this;
  }
  /**
   * Inverts this vector - i.e. sets x = -x, y = -y and z = -z.
   *
   * @return {Vector3} A reference to this vector.
   */
  negate() {
    return this.x = -this.x, this.y = -this.y, this.z = -this.z, this;
  }
  /**
   * Calculates the dot product of the given vector with this instance.
   *
   * @param {Vector3} v - The vector to compute the dot product with.
   * @return {number} The result of the dot product.
   */
  dot(e) {
    return this.x * e.x + this.y * e.y + this.z * e.z;
  }
  // TODO lengthSquared?
  /**
   * Computes the square of the Euclidean length (straight-line length) from
   * (0, 0, 0) to (x, y, z). If you are comparing the lengths of vectors, you should
   * compare the length squared instead as it is slightly more efficient to calculate.
   *
   * @return {number} The square length of this vector.
   */
  lengthSq() {
    return this.x * this.x + this.y * this.y + this.z * this.z;
  }
  /**
   * Computes the  Euclidean length (straight-line length) from (0, 0, 0) to (x, y, z).
   *
   * @return {number} The length of this vector.
   */
  length() {
    return Math.sqrt(this.x * this.x + this.y * this.y + this.z * this.z);
  }
  /**
   * Computes the Manhattan length of this vector.
   *
   * @return {number} The length of this vector.
   */
  manhattanLength() {
    return Math.abs(this.x) + Math.abs(this.y) + Math.abs(this.z);
  }
  /**
   * Converts this vector to a unit vector - that is, sets it equal to a vector
   * with the same direction as this one, but with a vector length of `1`.
   *
   * @return {Vector3} A reference to this vector.
   */
  normalize() {
    return this.divideScalar(this.length() || 1);
  }
  /**
   * Sets this vector to a vector with the same direction as this one, but
   * with the specified length.
   *
   * @param {number} length - The new length of this vector.
   * @return {Vector3} A reference to this vector.
   */
  setLength(e) {
    return this.normalize().multiplyScalar(e);
  }
  /**
   * Linearly interpolates between the given vector and this instance, where
   * alpha is the percent distance along the line - alpha = 0 will be this
   * vector, and alpha = 1 will be the given one.
   *
   * @param {Vector3} v - The vector to interpolate towards.
   * @param {number} alpha - The interpolation factor, typically in the closed interval `[0, 1]`.
   * @return {Vector3} A reference to this vector.
   */
  lerp(e, t) {
    return this.x += (e.x - this.x) * t, this.y += (e.y - this.y) * t, this.z += (e.z - this.z) * t, this;
  }
  /**
   * Linearly interpolates between the given vectors, where alpha is the percent
   * distance along the line - alpha = 0 will be first vector, and alpha = 1 will
   * be the second one. The result is stored in this instance.
   *
   * @param {Vector3} v1 - The first vector.
   * @param {Vector3} v2 - The second vector.
   * @param {number} alpha - The interpolation factor, typically in the closed interval `[0, 1]`.
   * @return {Vector3} A reference to this vector.
   */
  lerpVectors(e, t, i) {
    return this.x = e.x + (t.x - e.x) * i, this.y = e.y + (t.y - e.y) * i, this.z = e.z + (t.z - e.z) * i, this;
  }
  /**
   * Calculates the cross product of the given vector with this instance.
   *
   * @param {Vector3} v - The vector to compute the cross product with.
   * @return {Vector3} The result of the cross product.
   */
  cross(e) {
    return this.crossVectors(this, e);
  }
  /**
   * Calculates the cross product of the given vectors and stores the result
   * in this instance.
   *
   * @param {Vector3} a - The first vector.
   * @param {Vector3} b - The second vector.
   * @return {Vector3} A reference to this vector.
   */
  crossVectors(e, t) {
    const i = e.x, n = e.y, s = e.z, a = t.x, o = t.y, l = t.z;
    return this.x = n * l - s * o, this.y = s * a - i * l, this.z = i * o - n * a, this;
  }
  /**
   * Projects this vector onto the given one.
   *
   * @param {Vector3} v - The vector to project to.
   * @return {Vector3} A reference to this vector.
   */
  projectOnVector(e) {
    const t = e.lengthSq();
    if (t === 0) return this.set(0, 0, 0);
    const i = e.dot(this) / t;
    return this.copy(e).multiplyScalar(i);
  }
  /**
   * Projects this vector onto a plane by subtracting this
   * vector projected onto the plane's normal from this vector.
   *
   * @param {Vector3} planeNormal - The plane normal.
   * @return {Vector3} A reference to this vector.
   */
  projectOnPlane(e) {
    return xc.copy(this).projectOnVector(e), this.sub(xc);
  }
  /**
   * Reflects this vector off a plane orthogonal to the given normal vector.
   *
   * @param {Vector3} normal - The (normalized) normal vector.
   * @return {Vector3} A reference to this vector.
   */
  reflect(e) {
    return this.sub(xc.copy(e).multiplyScalar(2 * this.dot(e)));
  }
  /**
   * Returns the angle between the given vector and this instance in radians.
   *
   * @param {Vector3} v - The vector to compute the angle with.
   * @return {number} The angle in radians.
   */
  angleTo(e) {
    const t = Math.sqrt(this.lengthSq() * e.lengthSq());
    if (t === 0) return Math.PI / 2;
    const i = this.dot(e) / t;
    return Math.acos(Fe(i, -1, 1));
  }
  /**
   * Computes the distance from the given vector to this instance.
   *
   * @param {Vector3} v - The vector to compute the distance to.
   * @return {number} The distance.
   */
  distanceTo(e) {
    return Math.sqrt(this.distanceToSquared(e));
  }
  /**
   * Computes the squared distance from the given vector to this instance.
   * If you are just comparing the distance with another distance, you should compare
   * the distance squared instead as it is slightly more efficient to calculate.
   *
   * @param {Vector3} v - The vector to compute the squared distance to.
   * @return {number} The squared distance.
   */
  distanceToSquared(e) {
    const t = this.x - e.x, i = this.y - e.y, n = this.z - e.z;
    return t * t + i * i + n * n;
  }
  /**
   * Computes the Manhattan distance from the given vector to this instance.
   *
   * @param {Vector3} v - The vector to compute the Manhattan distance to.
   * @return {number} The Manhattan distance.
   */
  manhattanDistanceTo(e) {
    return Math.abs(this.x - e.x) + Math.abs(this.y - e.y) + Math.abs(this.z - e.z);
  }
  /**
   * Sets the vector components from the given spherical coordinates.
   *
   * @param {Spherical} s - The spherical coordinates.
   * @return {Vector3} A reference to this vector.
   */
  setFromSpherical(e) {
    return this.setFromSphericalCoords(e.radius, e.phi, e.theta);
  }
  /**
   * Sets the vector components from the given spherical coordinates.
   *
   * @param {number} radius - The radius.
   * @param {number} phi - The phi angle in radians.
   * @param {number} theta - The theta angle in radians.
   * @return {Vector3} A reference to this vector.
   */
  setFromSphericalCoords(e, t, i) {
    const n = Math.sin(t) * e;
    return this.x = n * Math.sin(i), this.y = Math.cos(t) * e, this.z = n * Math.cos(i), this;
  }
  /**
   * Sets the vector components from the given cylindrical coordinates.
   *
   * @param {Cylindrical} c - The cylindrical coordinates.
   * @return {Vector3} A reference to this vector.
   */
  setFromCylindrical(e) {
    return this.setFromCylindricalCoords(e.radius, e.theta, e.y);
  }
  /**
   * Sets the vector components from the given cylindrical coordinates.
   *
   * @param {number} radius - The radius.
   * @param {number} theta - The theta angle in radians.
   * @param {number} y - The y value.
   * @return {Vector3} A reference to this vector.
   */
  setFromCylindricalCoords(e, t, i) {
    return this.x = e * Math.sin(t), this.y = i, this.z = e * Math.cos(t), this;
  }
  /**
   * Sets the vector components to the position elements of the
   * given transformation matrix.
   *
   * @param {Matrix4} m - The 4x4 matrix.
   * @return {Vector3} A reference to this vector.
   */
  setFromMatrixPosition(e) {
    const t = e.elements;
    return this.x = t[12], this.y = t[13], this.z = t[14], this;
  }
  /**
   * Sets the vector components to the scale elements of the
   * given transformation matrix.
   *
   * @param {Matrix4} m - The 4x4 matrix.
   * @return {Vector3} A reference to this vector.
   */
  setFromMatrixScale(e) {
    const t = this.setFromMatrixColumn(e, 0).length(), i = this.setFromMatrixColumn(e, 1).length(), n = this.setFromMatrixColumn(e, 2).length();
    return this.x = t, this.y = i, this.z = n, this;
  }
  /**
   * Sets the vector components from the specified matrix column.
   *
   * @param {Matrix4} m - The 4x4 matrix.
   * @param {number} index - The column index.
   * @return {Vector3} A reference to this vector.
   */
  setFromMatrixColumn(e, t) {
    return this.fromArray(e.elements, t * 4);
  }
  /**
   * Sets the vector components from the specified matrix column.
   *
   * @param {Matrix3} m - The 3x3 matrix.
   * @param {number} index - The column index.
   * @return {Vector3} A reference to this vector.
   */
  setFromMatrix3Column(e, t) {
    return this.fromArray(e.elements, t * 3);
  }
  /**
   * Sets the vector components from the given Euler angles.
   *
   * @param {Euler} e - The Euler angles to set.
   * @return {Vector3} A reference to this vector.
   */
  setFromEuler(e) {
    return this.x = e._x, this.y = e._y, this.z = e._z, this;
  }
  /**
   * Sets the vector components from the RGB components of the
   * given color.
   *
   * @param {Color} c - The color to set.
   * @return {Vector3} A reference to this vector.
   */
  setFromColor(e) {
    return this.x = e.r, this.y = e.g, this.z = e.b, this;
  }
  /**
   * Returns `true` if this vector is equal with the given one.
   *
   * @param {Vector3} v - The vector to test for equality.
   * @return {boolean} Whether this vector is equal with the given one.
   */
  equals(e) {
    return e.x === this.x && e.y === this.y && e.z === this.z;
  }
  /**
   * Sets this vector's x value to be `array[ offset ]`, y value to be `array[ offset + 1 ]`
   * and z value to be `array[ offset + 2 ]`.
   *
   * @param {Array<number>} array - An array holding the vector component values.
   * @param {number} [offset=0] - The offset into the array.
   * @return {Vector3} A reference to this vector.
   */
  fromArray(e, t = 0) {
    return this.x = e[t], this.y = e[t + 1], this.z = e[t + 2], this;
  }
  /**
   * Writes the components of this vector to the given array. If no array is provided,
   * the method returns a new instance.
   *
   * @param {Array<number>} [array=[]] - The target array holding the vector components.
   * @param {number} [offset=0] - Index of the first element in the array.
   * @return {Array<number>} The vector components.
   */
  toArray(e = [], t = 0) {
    return e[t] = this.x, e[t + 1] = this.y, e[t + 2] = this.z, e;
  }
  /**
   * Sets the components of this vector from the given buffer attribute.
   *
   * @param {BufferAttribute} attribute - The buffer attribute holding vector data.
   * @param {number} index - The index into the attribute.
   * @return {Vector3} A reference to this vector.
   */
  fromBufferAttribute(e, t) {
    return this.x = e.getX(t), this.y = e.getY(t), this.z = e.getZ(t), this;
  }
  /**
   * Sets each component of this vector to a pseudo-random value between `0` and
   * `1`, excluding `1`.
   *
   * @return {Vector3} A reference to this vector.
   */
  random() {
    return this.x = Math.random(), this.y = Math.random(), this.z = Math.random(), this;
  }
  /**
   * Sets this vector to a uniformly random point on a unit sphere.
   *
   * @return {Vector3} A reference to this vector.
   */
  randomDirection() {
    const e = Math.random() * Math.PI * 2, t = Math.random() * 2 - 1, i = Math.sqrt(1 - t * t);
    return this.x = i * Math.cos(e), this.y = t, this.z = i * Math.sin(e), this;
  }
  *[Symbol.iterator]() {
    yield this.x, yield this.y, yield this.z;
  }
}
const xc = /* @__PURE__ */ new b(), iu = /* @__PURE__ */ new ot();
class He {
  /**
   * Constructs a new 3x3 matrix. The arguments are supposed to be
   * in row-major order. If no arguments are provided, the constructor
   * initializes the matrix as an identity matrix.
   *
   * @param {number} [n11] - 1-1 matrix element.
   * @param {number} [n12] - 1-2 matrix element.
   * @param {number} [n13] - 1-3 matrix element.
   * @param {number} [n21] - 2-1 matrix element.
   * @param {number} [n22] - 2-2 matrix element.
   * @param {number} [n23] - 2-3 matrix element.
   * @param {number} [n31] - 3-1 matrix element.
   * @param {number} [n32] - 3-2 matrix element.
   * @param {number} [n33] - 3-3 matrix element.
   */
  constructor(e, t, i, n, s, a, o, l, c) {
    He.prototype.isMatrix3 = !0, this.elements = [
      1,
      0,
      0,
      0,
      1,
      0,
      0,
      0,
      1
    ], e !== void 0 && this.set(e, t, i, n, s, a, o, l, c);
  }
  /**
   * Sets the elements of the matrix.The arguments are supposed to be
   * in row-major order.
   *
   * @param {number} [n11] - 1-1 matrix element.
   * @param {number} [n12] - 1-2 matrix element.
   * @param {number} [n13] - 1-3 matrix element.
   * @param {number} [n21] - 2-1 matrix element.
   * @param {number} [n22] - 2-2 matrix element.
   * @param {number} [n23] - 2-3 matrix element.
   * @param {number} [n31] - 3-1 matrix element.
   * @param {number} [n32] - 3-2 matrix element.
   * @param {number} [n33] - 3-3 matrix element.
   * @return {Matrix3} A reference to this matrix.
   */
  set(e, t, i, n, s, a, o, l, c) {
    const h = this.elements;
    return h[0] = e, h[1] = n, h[2] = o, h[3] = t, h[4] = s, h[5] = l, h[6] = i, h[7] = a, h[8] = c, this;
  }
  /**
   * Sets this matrix to the 3x3 identity matrix.
   *
   * @return {Matrix3} A reference to this matrix.
   */
  identity() {
    return this.set(
      1,
      0,
      0,
      0,
      1,
      0,
      0,
      0,
      1
    ), this;
  }
  /**
   * Copies the values of the given matrix to this instance.
   *
   * @param {Matrix3} m - The matrix to copy.
   * @return {Matrix3} A reference to this matrix.
   */
  copy(e) {
    const t = this.elements, i = e.elements;
    return t[0] = i[0], t[1] = i[1], t[2] = i[2], t[3] = i[3], t[4] = i[4], t[5] = i[5], t[6] = i[6], t[7] = i[7], t[8] = i[8], this;
  }
  /**
   * Extracts the basis of this matrix into the three axis vectors provided.
   *
   * @param {Vector3} xAxis - The basis's x axis.
   * @param {Vector3} yAxis - The basis's y axis.
   * @param {Vector3} zAxis - The basis's z axis.
   * @return {Matrix3} A reference to this matrix.
   */
  extractBasis(e, t, i) {
    return e.setFromMatrix3Column(this, 0), t.setFromMatrix3Column(this, 1), i.setFromMatrix3Column(this, 2), this;
  }
  /**
   * Set this matrix to the upper 3x3 matrix of the given 4x4 matrix.
   *
   * @param {Matrix4} m - The 4x4 matrix.
   * @return {Matrix3} A reference to this matrix.
   */
  setFromMatrix4(e) {
    const t = e.elements;
    return this.set(
      t[0],
      t[4],
      t[8],
      t[1],
      t[5],
      t[9],
      t[2],
      t[6],
      t[10]
    ), this;
  }
  /**
   * Post-multiplies this matrix by the given 3x3 matrix.
   *
   * @param {Matrix3} m - The matrix to multiply with.
   * @return {Matrix3} A reference to this matrix.
   */
  multiply(e) {
    return this.multiplyMatrices(this, e);
  }
  /**
   * Pre-multiplies this matrix by the given 3x3 matrix.
   *
   * @param {Matrix3} m - The matrix to multiply with.
   * @return {Matrix3} A reference to this matrix.
   */
  premultiply(e) {
    return this.multiplyMatrices(e, this);
  }
  /**
   * Multiples the given 3x3 matrices and stores the result
   * in this matrix.
   *
   * @param {Matrix3} a - The first matrix.
   * @param {Matrix3} b - The second matrix.
   * @return {Matrix3} A reference to this matrix.
   */
  multiplyMatrices(e, t) {
    const i = e.elements, n = t.elements, s = this.elements, a = i[0], o = i[3], l = i[6], c = i[1], h = i[4], d = i[7], u = i[2], p = i[5], m = i[8], _ = n[0], g = n[3], f = n[6], v = n[1], x = n[4], y = n[7], A = n[2], S = n[5], C = n[8];
    return s[0] = a * _ + o * v + l * A, s[3] = a * g + o * x + l * S, s[6] = a * f + o * y + l * C, s[1] = c * _ + h * v + d * A, s[4] = c * g + h * x + d * S, s[7] = c * f + h * y + d * C, s[2] = u * _ + p * v + m * A, s[5] = u * g + p * x + m * S, s[8] = u * f + p * y + m * C, this;
  }
  /**
   * Multiplies every component of the matrix by the given scalar.
   *
   * @param {number} s - The scalar.
   * @return {Matrix3} A reference to this matrix.
   */
  multiplyScalar(e) {
    const t = this.elements;
    return t[0] *= e, t[3] *= e, t[6] *= e, t[1] *= e, t[4] *= e, t[7] *= e, t[2] *= e, t[5] *= e, t[8] *= e, this;
  }
  /**
   * Computes and returns the determinant of this matrix.
   *
   * @return {number} The determinant.
   */
  determinant() {
    const e = this.elements, t = e[0], i = e[1], n = e[2], s = e[3], a = e[4], o = e[5], l = e[6], c = e[7], h = e[8];
    return t * a * h - t * o * c - i * s * h + i * o * l + n * s * c - n * a * l;
  }
  /**
   * Inverts this matrix, using the [analytic method]{@link https://en.wikipedia.org/wiki/Invertible_matrix#Analytic_solution}.
   * You can not invert with a determinant of zero. If you attempt this, the method produces
   * a zero matrix instead.
   *
   * @return {Matrix3} A reference to this matrix.
   */
  invert() {
    const e = this.elements, t = e[0], i = e[1], n = e[2], s = e[3], a = e[4], o = e[5], l = e[6], c = e[7], h = e[8], d = h * a - o * c, u = o * l - h * s, p = c * s - a * l, m = t * d + i * u + n * p;
    if (m === 0) return this.set(0, 0, 0, 0, 0, 0, 0, 0, 0);
    const _ = 1 / m;
    return e[0] = d * _, e[1] = (n * c - h * i) * _, e[2] = (o * i - n * a) * _, e[3] = u * _, e[4] = (h * t - n * l) * _, e[5] = (n * s - o * t) * _, e[6] = p * _, e[7] = (i * l - c * t) * _, e[8] = (a * t - i * s) * _, this;
  }
  /**
   * Transposes this matrix in place.
   *
   * @return {Matrix3} A reference to this matrix.
   */
  transpose() {
    let e;
    const t = this.elements;
    return e = t[1], t[1] = t[3], t[3] = e, e = t[2], t[2] = t[6], t[6] = e, e = t[5], t[5] = t[7], t[7] = e, this;
  }
  /**
   * Computes the normal matrix which is the inverse transpose of the upper
   * left 3x3 portion of the given 4x4 matrix.
   *
   * @param {Matrix4} matrix4 - The 4x4 matrix.
   * @return {Matrix3} A reference to this matrix.
   */
  getNormalMatrix(e) {
    return this.setFromMatrix4(e).invert().transpose();
  }
  /**
   * Transposes this matrix into the supplied array, and returns itself unchanged.
   *
   * @param {Array<number>} r - An array to store the transposed matrix elements.
   * @return {Matrix3} A reference to this matrix.
   */
  transposeIntoArray(e) {
    const t = this.elements;
    return e[0] = t[0], e[1] = t[3], e[2] = t[6], e[3] = t[1], e[4] = t[4], e[5] = t[7], e[6] = t[2], e[7] = t[5], e[8] = t[8], this;
  }
  /**
   * Sets the UV transform matrix from offset, repeat, rotation, and center.
   *
   * @param {number} tx - Offset x.
   * @param {number} ty - Offset y.
   * @param {number} sx - Repeat x.
   * @param {number} sy - Repeat y.
   * @param {number} rotation - Rotation, in radians. Positive values rotate counterclockwise.
   * @param {number} cx - Center x of rotation.
   * @param {number} cy - Center y of rotation
   * @return {Matrix3} A reference to this matrix.
   */
  setUvTransform(e, t, i, n, s, a, o) {
    const l = Math.cos(s), c = Math.sin(s);
    return this.set(
      i * l,
      i * c,
      -i * (l * a + c * o) + a + e,
      -n * c,
      n * l,
      -n * (-c * a + l * o) + o + t,
      0,
      0,
      1
    ), this;
  }
  /**
   * Scales this matrix with the given scalar values.
   *
   * @param {number} sx - The amount to scale in the X axis.
   * @param {number} sy - The amount to scale in the Y axis.
   * @return {Matrix3} A reference to this matrix.
   */
  scale(e, t) {
    return this.premultiply(bc.makeScale(e, t)), this;
  }
  /**
   * Rotates this matrix by the given angle.
   *
   * @param {number} theta - The rotation in radians.
   * @return {Matrix3} A reference to this matrix.
   */
  rotate(e) {
    return this.premultiply(bc.makeRotation(-e)), this;
  }
  /**
   * Translates this matrix by the given scalar values.
   *
   * @param {number} tx - The amount to translate in the X axis.
   * @param {number} ty - The amount to translate in the Y axis.
   * @return {Matrix3} A reference to this matrix.
   */
  translate(e, t) {
    return this.premultiply(bc.makeTranslation(e, t)), this;
  }
  // for 2D Transforms
  /**
   * Sets this matrix as a 2D translation transform.
   *
   * @param {number|Vector2} x - The amount to translate in the X axis or alternatively a translation vector.
   * @param {number} y - The amount to translate in the Y axis.
   * @return {Matrix3} A reference to this matrix.
   */
  makeTranslation(e, t) {
    return e.isVector2 ? this.set(
      1,
      0,
      e.x,
      0,
      1,
      e.y,
      0,
      0,
      1
    ) : this.set(
      1,
      0,
      e,
      0,
      1,
      t,
      0,
      0,
      1
    ), this;
  }
  /**
   * Sets this matrix as a 2D rotational transformation.
   *
   * @param {number} theta - The rotation in radians.
   * @return {Matrix3} A reference to this matrix.
   */
  makeRotation(e) {
    const t = Math.cos(e), i = Math.sin(e);
    return this.set(
      t,
      -i,
      0,
      i,
      t,
      0,
      0,
      0,
      1
    ), this;
  }
  /**
   * Sets this matrix as a 2D scale transform.
   *
   * @param {number} x - The amount to scale in the X axis.
   * @param {number} y - The amount to scale in the Y axis.
   * @return {Matrix3} A reference to this matrix.
   */
  makeScale(e, t) {
    return this.set(
      e,
      0,
      0,
      0,
      t,
      0,
      0,
      0,
      1
    ), this;
  }
  /**
   * Returns `true` if this matrix is equal with the given one.
   *
   * @param {Matrix3} matrix - The matrix to test for equality.
   * @return {boolean} Whether this matrix is equal with the given one.
   */
  equals(e) {
    const t = this.elements, i = e.elements;
    for (let n = 0; n < 9; n++)
      if (t[n] !== i[n]) return !1;
    return !0;
  }
  /**
   * Sets the elements of the matrix from the given array.
   *
   * @param {Array<number>} array - The matrix elements in column-major order.
   * @param {number} [offset=0] - Index of the first element in the array.
   * @return {Matrix3} A reference to this matrix.
   */
  fromArray(e, t = 0) {
    for (let i = 0; i < 9; i++)
      this.elements[i] = e[i + t];
    return this;
  }
  /**
   * Writes the elements of this matrix to the given array. If no array is provided,
   * the method returns a new instance.
   *
   * @param {Array<number>} [array=[]] - The target array holding the matrix elements in column-major order.
   * @param {number} [offset=0] - Index of the first element in the array.
   * @return {Array<number>} The matrix elements in column-major order.
   */
  toArray(e = [], t = 0) {
    const i = this.elements;
    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;
  }
  /**
   * Returns a matrix with copied values from this instance.
   *
   * @return {Matrix3} A clone of this instance.
   */
  clone() {
    return new this.constructor().fromArray(this.elements);
  }
}
const bc = /* @__PURE__ */ new He();
function lm(r) {
  for (let e = r.length - 1; e >= 0; --e)
    if (r[e] >= 65535) return !0;
  return !1;
}
const I_ = {
  Int8Array,
  Uint8Array,
  Uint8ClampedArray,
  Int16Array,
  Uint16Array,
  Int32Array,
  Uint32Array,
  Float32Array,
  Float64Array
};
function sr(r, e) {
  return new I_[r](e);
}
function ua(r) {
  return document.createElementNS("http://www.w3.org/1999/xhtml", r);
}
function cm() {
  const r = ua("canvas");
  return r.style.display = "block", r;
}
const nu = {};
function pa(r) {
  r in nu || (nu[r] = !0, console.warn(r));
}
function D_(r, e, t) {
  return new Promise(function(i, n) {
    function s() {
      switch (r.clientWaitSync(e, r.SYNC_FLUSH_COMMANDS_BIT, 0)) {
        case r.WAIT_FAILED:
          n();
          break;
        case r.TIMEOUT_EXPIRED:
          setTimeout(s, t);
          break;
        default:
          i();
      }
    }
    setTimeout(s, t);
  });
}
const su = /* @__PURE__ */ new He().set(
  0.4123908,
  0.3575843,
  0.1804808,
  0.212639,
  0.7151687,
  0.0721923,
  0.0193308,
  0.1191948,
  0.9505322
), ru = /* @__PURE__ */ new He().set(
  3.2409699,
  -1.5373832,
  -0.4986108,
  -0.9692436,
  1.8759675,
  0.0415551,
  0.0556301,
  -0.203977,
  1.0569715
);
function N_() {
  const r = {
    enabled: !0,
    workingColorSpace: On,
    /**
     * Implementations of supported color spaces.
     *
     * Required:
     *	- primaries: chromaticity coordinates [ rx ry gx gy bx by ]
     *	- whitePoint: reference white [ x y ]
     *	- transfer: transfer function (pre-defined)
     *	- toXYZ: Matrix3 RGB to XYZ transform
     *	- fromXYZ: Matrix3 XYZ to RGB transform
     *	- luminanceCoefficients: RGB luminance coefficients
     *
     * Optional:
     *  - outputColorSpaceConfig: { drawingBufferColorSpace: ColorSpace, toneMappingMode: 'extended' | 'standard' }
     *  - workingColorSpaceConfig: { unpackColorSpace: ColorSpace }
     *
     * Reference:
     * - https://www.russellcottrell.com/photo/matrixCalculator.htm
     */
    spaces: {},
    convert: function(n, s, a) {
      return this.enabled === !1 || s === a || !s || !a || (this.spaces[s].transfer === ut && (n.r = gn(n.r), n.g = gn(n.g), n.b = gn(n.b)), this.spaces[s].primaries !== this.spaces[a].primaries && (n.applyMatrix3(this.spaces[s].toXYZ), n.applyMatrix3(this.spaces[a].fromXYZ)), this.spaces[a].transfer === ut && (n.r = ar(n.r), n.g = ar(n.g), n.b = ar(n.b))), n;
    },
    workingToColorSpace: function(n, s) {
      return this.convert(n, this.workingColorSpace, s);
    },
    colorSpaceToWorking: function(n, s) {
      return this.convert(n, s, this.workingColorSpace);
    },
    getPrimaries: function(n) {
      return this.spaces[n].primaries;
    },
    getTransfer: function(n) {
      return n === un ? la : this.spaces[n].transfer;
    },
    getToneMappingMode: function(n) {
      return this.spaces[n].outputColorSpaceConfig.toneMappingMode || "standard";
    },
    getLuminanceCoefficients: function(n, s = this.workingColorSpace) {
      return n.fromArray(this.spaces[s].luminanceCoefficients);
    },
    define: function(n) {
      Object.assign(this.spaces, n);
    },
    // Internal APIs
    _getMatrix: function(n, s, a) {
      return n.copy(this.spaces[s].toXYZ).multiply(this.spaces[a].fromXYZ);
    },
    _getDrawingBufferColorSpace: function(n) {
      return this.spaces[n].outputColorSpaceConfig.drawingBufferColorSpace;
    },
    _getUnpackColorSpace: function(n = this.workingColorSpace) {
      return this.spaces[n].workingColorSpaceConfig.unpackColorSpace;
    },
    // Deprecated
    fromWorkingColorSpace: function(n, s) {
      return pa("THREE.ColorManagement: .fromWorkingColorSpace() has been renamed to .workingToColorSpace()."), r.workingToColorSpace(n, s);
    },
    toWorkingColorSpace: function(n, s) {
      return pa("THREE.ColorManagement: .toWorkingColorSpace() has been renamed to .colorSpaceToWorking()."), r.colorSpaceToWorking(n, s);
    }
  }, e = [0.64, 0.33, 0.3, 0.6, 0.15, 0.06], t = [0.2126, 0.7152, 0.0722], i = [0.3127, 0.329];
  return r.define({
    [On]: {
      primaries: e,
      whitePoint: i,
      transfer: la,
      toXYZ: su,
      fromXYZ: ru,
      luminanceCoefficients: t,
      workingColorSpaceConfig: { unpackColorSpace: Qt },
      outputColorSpaceConfig: { drawingBufferColorSpace: Qt }
    },
    [Qt]: {
      primaries: e,
      whitePoint: i,
      transfer: ut,
      toXYZ: su,
      fromXYZ: ru,
      luminanceCoefficients: t,
      outputColorSpaceConfig: { drawingBufferColorSpace: Qt }
    }
  }), r;
}
const et = /* @__PURE__ */ N_();
function gn(r) {
  return r < 0.04045 ? r * 0.0773993808 : Math.pow(r * 0.9478672986 + 0.0521327014, 2.4);
}
function ar(r) {
  return r < 31308e-7 ? r * 12.92 : 1.055 * Math.pow(r, 0.41666) - 0.055;
}
let Ps;
class hm {
  /**
   * Returns a data URI containing a representation of the given image.
   *
   * @param {(HTMLImageElement|HTMLCanvasElement)} image - The image object.
   * @param {string} [type='image/png'] - Indicates the image format.
   * @return {string} The data URI.
   */
  static getDataURL(e, t = "image/png") {
    if (/^data:/i.test(e.src) || typeof HTMLCanvasElement > "u")
      return e.src;
    let i;
    if (e instanceof HTMLCanvasElement)
      i = e;
    else {
      Ps === void 0 && (Ps = ua("canvas")), Ps.width = e.width, Ps.height = e.height;
      const n = Ps.getContext("2d");
      e instanceof ImageData ? n.putImageData(e, 0, 0) : n.drawImage(e, 0, 0, e.width, e.height), i = Ps;
    }
    return i.toDataURL(t);
  }
  /**
   * Converts the given sRGB image data to linear color space.
   *
   * @param {(HTMLImageElement|HTMLCanvasElement|ImageBitmap|Object)} image - The image object.
   * @return {HTMLCanvasElement|Object} The converted image.
   */
  static sRGBToLinear(e) {
    if (typeof HTMLImageElement < "u" && e instanceof HTMLImageElement || typeof HTMLCanvasElement < "u" && e instanceof HTMLCanvasElement || typeof ImageBitmap < "u" && e instanceof ImageBitmap) {
      const t = ua("canvas");
      t.width = e.width, t.height = e.height;
      const i = t.getContext("2d");
      i.drawImage(e, 0, 0, e.width, e.height);
      const n = i.getImageData(0, 0, e.width, e.height), s = n.data;
      for (let a = 0; a < s.length; a++)
        s[a] = gn(s[a] / 255) * 255;
      return i.putImageData(n, 0, 0), t;
    } else if (e.data) {
      const t = e.data.slice(0);
      for (let i = 0; i < t.length; i++)
        t instanceof Uint8Array || t instanceof Uint8ClampedArray ? t[i] = Math.floor(gn(t[i] / 255) * 255) : t[i] = gn(t[i]);
      return {
        data: t,
        width: e.width,
        height: e.height
      };
    } else
      return console.warn("THREE.ImageUtils.sRGBToLinear(): Unsupported image type. No color space conversion applied."), e;
  }
}
let U_ = 0;
class In {
  /**
   * Constructs a new video texture.
   *
   * @param {any} [data=null] - The data definition of a texture.
   */
  constructor(e = null) {
    this.isSource = !0, Object.defineProperty(this, "id", { value: U_++ }), this.uuid = Ti(), this.data = e, this.dataReady = !0, this.version = 0;
  }
  /**
   * Returns the dimensions of the source into the given target vector.
   *
   * @param {(Vector2|Vector3)} target - The target object the result is written into.
   * @return {(Vector2|Vector3)} The dimensions of the source.
   */
  getSize(e) {
    const t = this.data;
    return typeof HTMLVideoElement < "u" && t instanceof HTMLVideoElement ? e.set(t.videoWidth, t.videoHeight, 0) : t instanceof VideoFrame ? e.set(t.displayHeight, t.displayWidth, 0) : t !== null ? e.set(t.width, t.height, t.depth || 0) : e.set(0, 0, 0), e;
  }
  /**
   * When the property is set to `true`, the engine allocates the memory
   * for the texture (if necessary) and triggers the actual texture upload
   * to the GPU next time the source is used.
   *
   * @type {boolean}
   * @default false
   * @param {boolean} value
   */
  set needsUpdate(e) {
    e === !0 && this.version++;
  }
  /**
   * Serializes the source into JSON.
   *
   * @param {?(Object|string)} meta - An optional value holding meta information about the serialization.
   * @return {Object} A JSON object representing the serialized source.
   * @see {@link ObjectLoader#parse}
   */
  toJSON(e) {
    const t = e === void 0 || typeof e == "string";
    if (!t && e.images[this.uuid] !== void 0)
      return e.images[this.uuid];
    const i = {
      uuid: this.uuid,
      url: ""
    }, n = this.data;
    if (n !== null) {
      let s;
      if (Array.isArray(n)) {
        s = [];
        for (let a = 0, o = n.length; a < o; a++)
          n[a].isDataTexture ? s.push(Sc(n[a].image)) : s.push(Sc(n[a]));
      } else
        s = Sc(n);
      i.url = s;
    }
    return t || (e.images[this.uuid] = i), i;
  }
}
function Sc(r) {
  return typeof HTMLImageElement < "u" && r instanceof HTMLImageElement || typeof HTMLCanvasElement < "u" && r instanceof HTMLCanvasElement || typeof ImageBitmap < "u" && r instanceof ImageBitmap ? hm.getDataURL(r) : r.data ? {
    data: Array.from(r.data),
    width: r.width,
    height: r.height,
    type: r.data.constructor.name
  } : (console.warn("THREE.Texture: Unable to serialize Texture."), {});
}
let O_ = 0;
const Mc = /* @__PURE__ */ new b();
class Et extends sn {
  /**
   * Constructs a new texture.
   *
   * @param {?Object} [image=Texture.DEFAULT_IMAGE] - The image holding the texture data.
   * @param {number} [mapping=Texture.DEFAULT_MAPPING] - The texture mapping.
   * @param {number} [wrapS=ClampToEdgeWrapping] - The wrapS value.
   * @param {number} [wrapT=ClampToEdgeWrapping] - The wrapT value.
   * @param {number} [magFilter=LinearFilter] - The mag filter value.
   * @param {number} [minFilter=LinearMipmapLinearFilter] - The min filter value.
   * @param {number} [format=RGBAFormat] - The texture format.
   * @param {number} [type=UnsignedByteType] - The texture type.
   * @param {number} [anisotropy=Texture.DEFAULT_ANISOTROPY] - The anisotropy value.
   * @param {string} [colorSpace=NoColorSpace] - The color space.
   */
  constructor(e = Et.DEFAULT_IMAGE, t = Et.DEFAULT_MAPPING, i = fi, n = fi, s = Pt, a = Ji, o = oi, l = Hi, c = Et.DEFAULT_ANISOTROPY, h = un) {
    super(), this.isTexture = !0, Object.defineProperty(this, "id", { value: O_++ }), this.uuid = Ti(), this.name = "", this.source = new In(e), this.mipmaps = [], this.mapping = t, this.channel = 0, this.wrapS = i, this.wrapT = n, this.magFilter = s, this.minFilter = a, this.anisotropy = c, this.format = o, this.internalFormat = null, this.type = l, this.offset = new H(0, 0), this.repeat = new H(1, 1), this.center = new H(0, 0), this.rotation = 0, this.matrixAutoUpdate = !0, this.matrix = new He(), this.generateMipmaps = !0, this.premultiplyAlpha = !1, this.flipY = !0, this.unpackAlignment = 4, this.colorSpace = h, this.userData = {}, this.updateRanges = [], this.version = 0, this.onUpdate = null, this.renderTarget = null, this.isRenderTargetTexture = !1, this.isArrayTexture = !!(e && e.depth && e.depth > 1), this.pmremVersion = 0;
  }
  /**
   * The width of the texture in pixels.
   */
  get width() {
    return this.source.getSize(Mc).x;
  }
  /**
   * The height of the texture in pixels.
   */
  get height() {
    return this.source.getSize(Mc).y;
  }
  /**
   * The depth of the texture in pixels.
   */
  get depth() {
    return this.source.getSize(Mc).z;
  }
  /**
   * The image object holding the texture data.
   *
   * @type {?Object}
   */
  get image() {
    return this.source.data;
  }
  set image(e = null) {
    this.source.data = e;
  }
  /**
   * Updates the texture transformation matrix from the from the properties {@link Texture#offset},
   * {@link Texture#repeat}, {@link Texture#rotation}, and {@link Texture#center}.
   */
  updateMatrix() {
    this.matrix.setUvTransform(this.offset.x, this.offset.y, this.repeat.x, this.repeat.y, this.rotation, this.center.x, this.center.y);
  }
  /**
   * Adds a range of data in the data texture to be updated on the GPU.
   *
   * @param {number} start - Position at which to start update.
   * @param {number} count - The number of components to update.
   */
  addUpdateRange(e, t) {
    this.updateRanges.push({ start: e, count: t });
  }
  /**
   * Clears the update ranges.
   */
  clearUpdateRanges() {
    this.updateRanges.length = 0;
  }
  /**
   * Returns a new texture with copied values from this instance.
   *
   * @return {Texture} A clone of this instance.
   */
  clone() {
    return new this.constructor().copy(this);
  }
  /**
   * Copies the values of the given texture to this instance.
   *
   * @param {Texture} source - The texture to copy.
   * @return {Texture} A reference to this instance.
   */
  copy(e) {
    return this.name = e.name, this.source = e.source, this.mipmaps = e.mipmaps.slice(0), this.mapping = e.mapping, this.channel = e.channel, this.wrapS = e.wrapS, this.wrapT = e.wrapT, this.magFilter = e.magFilter, this.minFilter = e.minFilter, this.anisotropy = e.anisotropy, this.format = e.format, this.internalFormat = e.internalFormat, this.type = e.type, this.offset.copy(e.offset), this.repeat.copy(e.repeat), this.center.copy(e.center), this.rotation = e.rotation, this.matrixAutoUpdate = e.matrixAutoUpdate, this.matrix.copy(e.matrix), this.generateMipmaps = e.generateMipmaps, this.premultiplyAlpha = e.premultiplyAlpha, this.flipY = e.flipY, this.unpackAlignment = e.unpackAlignment, this.colorSpace = e.colorSpace, this.renderTarget = e.renderTarget, this.isRenderTargetTexture = e.isRenderTargetTexture, this.isArrayTexture = e.isArrayTexture, this.userData = JSON.parse(JSON.stringify(e.userData)), this.needsUpdate = !0, this;
  }
  /**
   * Sets this texture's properties based on `values`.
   * @param {Object} values - A container with texture parameters.
   */
  setValues(e) {
    for (const t in e) {
      const i = e[t];
      if (i === void 0) {
        console.warn(`THREE.Texture.setValues(): parameter '${t}' has value of undefined.`);
        continue;
      }
      const n = this[t];
      if (n === void 0) {
        console.warn(`THREE.Texture.setValues(): property '${t}' does not exist.`);
        continue;
      }
      n && i && n.isVector2 && i.isVector2 || n && i && n.isVector3 && i.isVector3 || n && i && n.isMatrix3 && i.isMatrix3 ? n.copy(i) : this[t] = i;
    }
  }
  /**
   * Serializes the texture into JSON.
   *
   * @param {?(Object|string)} meta - An optional value holding meta information about the serialization.
   * @return {Object} A JSON object representing the serialized texture.
   * @see {@link ObjectLoader#parse}
   */
  toJSON(e) {
    const t = e === void 0 || typeof e == "string";
    if (!t && e.textures[this.uuid] !== void 0)
      return e.textures[this.uuid];
    const i = {
      metadata: {
        version: 4.7,
        type: "Texture",
        generator: "Texture.toJSON"
      },
      uuid: this.uuid,
      name: this.name,
      image: this.source.toJSON(e).uuid,
      mapping: this.mapping,
      channel: this.channel,
      repeat: [this.repeat.x, this.repeat.y],
      offset: [this.offset.x, this.offset.y],
      center: [this.center.x, this.center.y],
      rotation: this.rotation,
      wrap: [this.wrapS, this.wrapT],
      format: this.format,
      internalFormat: this.internalFormat,
      type: this.type,
      colorSpace: this.colorSpace,
      minFilter: this.minFilter,
      magFilter: this.magFilter,
      anisotropy: this.anisotropy,
      flipY: this.flipY,
      generateMipmaps: this.generateMipmaps,
      premultiplyAlpha: this.premultiplyAlpha,
      unpackAlignment: this.unpackAlignment
    };
    return Object.keys(this.userData).length > 0 && (i.userData = this.userData), t || (e.textures[this.uuid] = i), i;
  }
  /**
   * Frees the GPU-related resources allocated by this instance. Call this
   * method whenever this instance is no longer used in your app.
   *
   * @fires Texture#dispose
   */
  dispose() {
    this.dispatchEvent({ type: "dispose" });
  }
  /**
   * Transforms the given uv vector with the textures uv transformation matrix.
   *
   * @param {Vector2} uv - The uv vector.
   * @return {Vector2} The transformed uv vector.
   */
  transformUv(e) {
    if (this.mapping !== Ol) return e;
    if (e.applyMatrix3(this.matrix), e.x < 0 || e.x > 1)
      switch (this.wrapS) {
        case xs:
          e.x = e.x - Math.floor(e.x);
          break;
        case fi:
          e.x = e.x < 0 ? 0 : 1;
          break;
        case ra:
          Math.abs(Math.floor(e.x) % 2) === 1 ? e.x = Math.ceil(e.x) - e.x : e.x = e.x - Math.floor(e.x);
          break;
      }
    if (e.y < 0 || e.y > 1)
      switch (this.wrapT) {
        case xs:
          e.y = e.y - Math.floor(e.y);
          break;
        case fi:
          e.y = e.y < 0 ? 0 : 1;
          break;
        case ra:
          Math.abs(Math.floor(e.y) % 2) === 1 ? e.y = Math.ceil(e.y) - e.y : e.y = e.y - Math.floor(e.y);
          break;
      }
    return this.flipY && (e.y = 1 - e.y), e;
  }
  /**
   * Setting this property to `true` indicates the engine the texture
   * must be updated in the next render. This triggers a texture upload
   * to the GPU and ensures correct texture parameter configuration.
   *
   * @type {boolean}
   * @default false
   * @param {boolean} value
   */
  set needsUpdate(e) {
    e === !0 && (this.version++, this.source.needsUpdate = !0);
  }
  /**
   * Setting this property to `true` indicates the engine the PMREM
   * must be regenerated.
   *
   * @type {boolean}
   * @default false
   * @param {boolean} value
   */
  set needsPMREMUpdate(e) {
    e === !0 && this.pmremVersion++;
  }
}
Et.DEFAULT_IMAGE = null;
Et.DEFAULT_MAPPING = Ol;
Et.DEFAULT_ANISOTROPY = 1;
class Ye {
  /**
   * Constructs a new 4D vector.
   *
   * @param {number} [x=0] - The x value of this vector.
   * @param {number} [y=0] - The y value of this vector.
   * @param {number} [z=0] - The z value of this vector.
   * @param {number} [w=1] - The w value of this vector.
   */
  constructor(e = 0, t = 0, i = 0, n = 1) {
    Ye.prototype.isVector4 = !0, this.x = e, this.y = t, this.z = i, this.w = n;
  }
  /**
   * Alias for {@link Vector4#z}.
   *
   * @type {number}
   */
  get width() {
    return this.z;
  }
  set width(e) {
    this.z = e;
  }
  /**
   * Alias for {@link Vector4#w}.
   *
   * @type {number}
   */
  get height() {
    return this.w;
  }
  set height(e) {
    this.w = e;
  }
  /**
   * Sets the vector components.
   *
   * @param {number} x - The value of the x component.
   * @param {number} y - The value of the y component.
   * @param {number} z - The value of the z component.
   * @param {number} w - The value of the w component.
   * @return {Vector4} A reference to this vector.
   */
  set(e, t, i, n) {
    return this.x = e, this.y = t, this.z = i, this.w = n, this;
  }
  /**
   * Sets the vector components to the same value.
   *
   * @param {number} scalar - The value to set for all vector components.
   * @return {Vector4} A reference to this vector.
   */
  setScalar(e) {
    return this.x = e, this.y = e, this.z = e, this.w = e, this;
  }
  /**
   * Sets the vector's x component to the given value
   *
   * @param {number} x - The value to set.
   * @return {Vector4} A reference to this vector.
   */
  setX(e) {
    return this.x = e, this;
  }
  /**
   * Sets the vector's y component to the given value
   *
   * @param {number} y - The value to set.
   * @return {Vector4} A reference to this vector.
   */
  setY(e) {
    return this.y = e, this;
  }
  /**
   * Sets the vector's z component to the given value
   *
   * @param {number} z - The value to set.
   * @return {Vector4} A reference to this vector.
   */
  setZ(e) {
    return this.z = e, this;
  }
  /**
   * Sets the vector's w component to the given value
   *
   * @param {number} w - The value to set.
   * @return {Vector4} A reference to this vector.
   */
  setW(e) {
    return this.w = e, this;
  }
  /**
   * Allows to set a vector component with an index.
   *
   * @param {number} index - The component index. `0` equals to x, `1` equals to y,
   * `2` equals to z, `3` equals to w.
   * @param {number} value - The value to set.
   * @return {Vector4} A reference to this vector.
   */
  setComponent(e, t) {
    switch (e) {
      case 0:
        this.x = t;
        break;
      case 1:
        this.y = t;
        break;
      case 2:
        this.z = t;
        break;
      case 3:
        this.w = t;
        break;
      default:
        throw new Error("index is out of range: " + e);
    }
    return this;
  }
  /**
   * Returns the value of the vector component which matches the given index.
   *
   * @param {number} index - The component index. `0` equals to x, `1` equals to y,
   * `2` equals to z, `3` equals to w.
   * @return {number} A vector component value.
   */
  getComponent(e) {
    switch (e) {
      case 0:
        return this.x;
      case 1:
        return this.y;
      case 2:
        return this.z;
      case 3:
        return this.w;
      default:
        throw new Error("index is out of range: " + e);
    }
  }
  /**
   * Returns a new vector with copied values from this instance.
   *
   * @return {Vector4} A clone of this instance.
   */
  clone() {
    return new this.constructor(this.x, this.y, this.z, this.w);
  }
  /**
   * Copies the values of the given vector to this instance.
   *
   * @param {Vector3|Vector4} v - The vector to copy.
   * @return {Vector4} A reference to this vector.
   */
  copy(e) {
    return this.x = e.x, this.y = e.y, this.z = e.z, this.w = e.w !== void 0 ? e.w : 1, this;
  }
  /**
   * Adds the given vector to this instance.
   *
   * @param {Vector4} v - The vector to add.
   * @return {Vector4} A reference to this vector.
   */
  add(e) {
    return this.x += e.x, this.y += e.y, this.z += e.z, this.w += e.w, this;
  }
  /**
   * Adds the given scalar value to all components of this instance.
   *
   * @param {number} s - The scalar to add.
   * @return {Vector4} A reference to this vector.
   */
  addScalar(e) {
    return this.x += e, this.y += e, this.z += e, this.w += e, this;
  }
  /**
   * Adds the given vectors and stores the result in this instance.
   *
   * @param {Vector4} a - The first vector.
   * @param {Vector4} b - The second vector.
   * @return {Vector4} A reference to this vector.
   */
  addVectors(e, t) {
    return this.x = e.x + t.x, this.y = e.y + t.y, this.z = e.z + t.z, this.w = e.w + t.w, this;
  }
  /**
   * Adds the given vector scaled by the given factor to this instance.
   *
   * @param {Vector4} v - The vector.
   * @param {number} s - The factor that scales `v`.
   * @return {Vector4} A reference to this vector.
   */
  addScaledVector(e, t) {
    return this.x += e.x * t, this.y += e.y * t, this.z += e.z * t, this.w += e.w * t, this;
  }
  /**
   * Subtracts the given vector from this instance.
   *
   * @param {Vector4} v - The vector to subtract.
   * @return {Vector4} A reference to this vector.
   */
  sub(e) {
    return this.x -= e.x, this.y -= e.y, this.z -= e.z, this.w -= e.w, this;
  }
  /**
   * Subtracts the given scalar value from all components of this instance.
   *
   * @param {number} s - The scalar to subtract.
   * @return {Vector4} A reference to this vector.
   */
  subScalar(e) {
    return this.x -= e, this.y -= e, this.z -= e, this.w -= e, this;
  }
  /**
   * Subtracts the given vectors and stores the result in this instance.
   *
   * @param {Vector4} a - The first vector.
   * @param {Vector4} b - The second vector.
   * @return {Vector4} A reference to this vector.
   */
  subVectors(e, t) {
    return this.x = e.x - t.x, this.y = e.y - t.y, this.z = e.z - t.z, this.w = e.w - t.w, this;
  }
  /**
   * Multiplies the given vector with this instance.
   *
   * @param {Vector4} v - The vector to multiply.
   * @return {Vector4} A reference to this vector.
   */
  multiply(e) {
    return this.x *= e.x, this.y *= e.y, this.z *= e.z, this.w *= e.w, this;
  }
  /**
   * Multiplies the given scalar value with all components of this instance.
   *
   * @param {number} scalar - The scalar to multiply.
   * @return {Vector4} A reference to this vector.
   */
  multiplyScalar(e) {
    return this.x *= e, this.y *= e, this.z *= e, this.w *= e, this;
  }
  /**
   * Multiplies this vector with the given 4x4 matrix.
   *
   * @param {Matrix4} m - The 4x4 matrix.
   * @return {Vector4} A reference to this vector.
   */
  applyMatrix4(e) {
    const t = this.x, i = this.y, n = this.z, s = this.w, a = e.elements;
    return this.x = a[0] * t + a[4] * i + a[8] * n + a[12] * s, this.y = a[1] * t + a[5] * i + a[9] * n + a[13] * s, this.z = a[2] * t + a[6] * i + a[10] * n + a[14] * s, this.w = a[3] * t + a[7] * i + a[11] * n + a[15] * s, this;
  }
  /**
   * Divides this instance by the given vector.
   *
   * @param {Vector4} v - The vector to divide.
   * @return {Vector4} A reference to this vector.
   */
  divide(e) {
    return this.x /= e.x, this.y /= e.y, this.z /= e.z, this.w /= e.w, this;
  }
  /**
   * Divides this vector by the given scalar.
   *
   * @param {number} scalar - The scalar to divide.
   * @return {Vector4} A reference to this vector.
   */
  divideScalar(e) {
    return this.multiplyScalar(1 / e);
  }
  /**
   * Sets the x, y and z components of this
   * vector to the quaternion's axis and w to the angle.
   *
   * @param {Quaternion} q - The Quaternion to set.
   * @return {Vector4} A reference to this vector.
   */
  setAxisAngleFromQuaternion(e) {
    this.w = 2 * Math.acos(e.w);
    const t = Math.sqrt(1 - e.w * e.w);
    return t < 1e-4 ? (this.x = 1, this.y = 0, this.z = 0) : (this.x = e.x / t, this.y = e.y / t, this.z = e.z / t), this;
  }
  /**
   * Sets the x, y and z components of this
   * vector to the axis of rotation and w to the angle.
   *
   * @param {Matrix4} m - A 4x4 matrix of which the upper left 3x3 matrix is a pure rotation matrix.
   * @return {Vector4} A reference to this vector.
   */
  setAxisAngleFromRotationMatrix(e) {
    let t, i, n, s;
    const l = e.elements, c = l[0], h = l[4], d = l[8], u = l[1], p = l[5], m = l[9], _ = l[2], g = l[6], f = l[10];
    if (Math.abs(h - u) < 0.01 && Math.abs(d - _) < 0.01 && Math.abs(m - g) < 0.01) {
      if (Math.abs(h + u) < 0.1 && Math.abs(d + _) < 0.1 && Math.abs(m + g) < 0.1 && Math.abs(c + p + f - 3) < 0.1)
        return this.set(1, 0, 0, 0), this;
      t = Math.PI;
      const x = (c + 1) / 2, y = (p + 1) / 2, A = (f + 1) / 2, S = (h + u) / 4, C = (d + _) / 4, P = (m + g) / 4;
      return x > y && x > A ? x < 0.01 ? (i = 0, n = 0.707106781, s = 0.707106781) : (i = Math.sqrt(x), n = S / i, s = C / i) : y > A ? y < 0.01 ? (i = 0.707106781, n = 0, s = 0.707106781) : (n = Math.sqrt(y), i = S / n, s = P / n) : A < 0.01 ? (i = 0.707106781, n = 0.707106781, s = 0) : (s = Math.sqrt(A), i = C / s, n = P / s), this.set(i, n, s, t), this;
    }
    let v = Math.sqrt((g - m) * (g - m) + (d - _) * (d - _) + (u - h) * (u - h));
    return Math.abs(v) < 1e-3 && (v = 1), this.x = (g - m) / v, this.y = (d - _) / v, this.z = (u - h) / v, this.w = Math.acos((c + p + f - 1) / 2), this;
  }
  /**
   * Sets the vector components to the position elements of the
   * given transformation matrix.
   *
   * @param {Matrix4} m - The 4x4 matrix.
   * @return {Vector4} A reference to this vector.
   */
  setFromMatrixPosition(e) {
    const t = e.elements;
    return this.x = t[12], this.y = t[13], this.z = t[14], this.w = t[15], this;
  }
  /**
   * If this vector's x, y, z or w value is greater than the given vector's x, y, z or w
   * value, replace that value with the corresponding min value.
   *
   * @param {Vector4} v - The vector.
   * @return {Vector4} A reference to this vector.
   */
  min(e) {
    return this.x = Math.min(this.x, e.x), this.y = Math.min(this.y, e.y), this.z = Math.min(this.z, e.z), this.w = Math.min(this.w, e.w), this;
  }
  /**
   * If this vector's x, y, z or w value is less than the given vector's x, y, z or w
   * value, replace that value with the corresponding max value.
   *
   * @param {Vector4} v - The vector.
   * @return {Vector4} A reference to this vector.
   */
  max(e) {
    return this.x = Math.max(this.x, e.x), this.y = Math.max(this.y, e.y), this.z = Math.max(this.z, e.z), this.w = Math.max(this.w, e.w), this;
  }
  /**
   * If this vector's x, y, z or w value is greater than the max vector's x, y, z or w
   * value, it is replaced by the corresponding value.
   * If this vector's x, y, z or w value is less than the min vector's x, y, z or w value,
   * it is replaced by the corresponding value.
   *
   * @param {Vector4} min - The minimum x, y and z values.
   * @param {Vector4} max - The maximum x, y and z values in the desired range.
   * @return {Vector4} A reference to this vector.
   */
  clamp(e, t) {
    return this.x = Fe(this.x, e.x, t.x), this.y = Fe(this.y, e.y, t.y), this.z = Fe(this.z, e.z, t.z), this.w = Fe(this.w, e.w, t.w), this;
  }
  /**
   * If this vector's x, y, z or w values are greater than the max value, they are
   * replaced by the max value.
   * If this vector's x, y, z or w values are less than the min value, they are
   * replaced by the min value.
   *
   * @param {number} minVal - The minimum value the components will be clamped to.
   * @param {number} maxVal - The maximum value the components will be clamped to.
   * @return {Vector4} A reference to this vector.
   */
  clampScalar(e, t) {
    return this.x = Fe(this.x, e, t), this.y = Fe(this.y, e, t), this.z = Fe(this.z, e, t), this.w = Fe(this.w, e, t), this;
  }
  /**
   * If this vector's length is greater than the max value, it is replaced by
   * the max value.
   * If this vector's length is less than the min value, it is replaced by the
   * min value.
   *
   * @param {number} min - The minimum value the vector length will be clamped to.
   * @param {number} max - The maximum value the vector length will be clamped to.
   * @return {Vector4} A reference to this vector.
   */
  clampLength(e, t) {
    const i = this.length();
    return this.divideScalar(i || 1).multiplyScalar(Fe(i, e, t));
  }
  /**
   * The components of this vector are rounded down to the nearest integer value.
   *
   * @return {Vector4} A reference to this vector.
   */
  floor() {
    return this.x = Math.floor(this.x), this.y = Math.floor(this.y), this.z = Math.floor(this.z), this.w = Math.floor(this.w), this;
  }
  /**
   * The components of this vector are rounded up to the nearest integer value.
   *
   * @return {Vector4} A reference to this vector.
   */
  ceil() {
    return this.x = Math.ceil(this.x), this.y = Math.ceil(this.y), this.z = Math.ceil(this.z), this.w = Math.ceil(this.w), this;
  }
  /**
   * The components of this vector are rounded to the nearest integer value
   *
   * @return {Vector4} A reference to this vector.
   */
  round() {
    return this.x = Math.round(this.x), this.y = Math.round(this.y), this.z = Math.round(this.z), this.w = Math.round(this.w), this;
  }
  /**
   * The components of this vector are rounded towards zero (up if negative,
   * down if positive) to an integer value.
   *
   * @return {Vector4} A reference to this vector.
   */
  roundToZero() {
    return this.x = Math.trunc(this.x), this.y = Math.trunc(this.y), this.z = Math.trunc(this.z), this.w = Math.trunc(this.w), this;
  }
  /**
   * Inverts this vector - i.e. sets x = -x, y = -y, z = -z, w = -w.
   *
   * @return {Vector4} A reference to this vector.
   */
  negate() {
    return this.x = -this.x, this.y = -this.y, this.z = -this.z, this.w = -this.w, this;
  }
  /**
   * Calculates the dot product of the given vector with this instance.
   *
   * @param {Vector4} v - The vector to compute the dot product with.
   * @return {number} The result of the dot product.
   */
  dot(e) {
    return this.x * e.x + this.y * e.y + this.z * e.z + this.w * e.w;
  }
  /**
   * Computes the square of the Euclidean length (straight-line length) from
   * (0, 0, 0, 0) to (x, y, z, w). If you are comparing the lengths of vectors, you should
   * compare the length squared instead as it is slightly more efficient to calculate.
   *
   * @return {number} The square length of this vector.
   */
  lengthSq() {
    return this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w;
  }
  /**
   * Computes the  Euclidean length (straight-line length) from (0, 0, 0, 0) to (x, y, z, w).
   *
   * @return {number} The length of this vector.
   */
  length() {
    return Math.sqrt(this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w);
  }
  /**
   * Computes the Manhattan length of this vector.
   *
   * @return {number} The length of this vector.
   */
  manhattanLength() {
    return Math.abs(this.x) + Math.abs(this.y) + Math.abs(this.z) + Math.abs(this.w);
  }
  /**
   * Converts this vector to a unit vector - that is, sets it equal to a vector
   * with the same direction as this one, but with a vector length of `1`.
   *
   * @return {Vector4} A reference to this vector.
   */
  normalize() {
    return this.divideScalar(this.length() || 1);
  }
  /**
   * Sets this vector to a vector with the same direction as this one, but
   * with the specified length.
   *
   * @param {number} length - The new length of this vector.
   * @return {Vector4} A reference to this vector.
   */
  setLength(e) {
    return this.normalize().multiplyScalar(e);
  }
  /**
   * Linearly interpolates between the given vector and this instance, where
   * alpha is the percent distance along the line - alpha = 0 will be this
   * vector, and alpha = 1 will be the given one.
   *
   * @param {Vector4} v - The vector to interpolate towards.
   * @param {number} alpha - The interpolation factor, typically in the closed interval `[0, 1]`.
   * @return {Vector4} A reference to this vector.
   */
  lerp(e, t) {
    return this.x += (e.x - this.x) * t, this.y += (e.y - this.y) * t, this.z += (e.z - this.z) * t, this.w += (e.w - this.w) * t, this;
  }
  /**
   * Linearly interpolates between the given vectors, where alpha is the percent
   * distance along the line - alpha = 0 will be first vector, and alpha = 1 will
   * be the second one. The result is stored in this instance.
   *
   * @param {Vector4} v1 - The first vector.
   * @param {Vector4} v2 - The second vector.
   * @param {number} alpha - The interpolation factor, typically in the closed interval `[0, 1]`.
   * @return {Vector4} A reference to this vector.
   */
  lerpVectors(e, t, i) {
    return this.x = e.x + (t.x - e.x) * i, this.y = e.y + (t.y - e.y) * i, this.z = e.z + (t.z - e.z) * i, this.w = e.w + (t.w - e.w) * i, this;
  }
  /**
   * Returns `true` if this vector is equal with the given one.
   *
   * @param {Vector4} v - The vector to test for equality.
   * @return {boolean} Whether this vector is equal with the given one.
   */
  equals(e) {
    return e.x === this.x && e.y === this.y && e.z === this.z && e.w === this.w;
  }
  /**
   * Sets this vector's x value to be `array[ offset ]`, y value to be `array[ offset + 1 ]`,
   * z value to be `array[ offset + 2 ]`, w value to be `array[ offset + 3 ]`.
   *
   * @param {Array<number>} array - An array holding the vector component values.
   * @param {number} [offset=0] - The offset into the array.
   * @return {Vector4} A reference to this vector.
   */
  fromArray(e, t = 0) {
    return this.x = e[t], this.y = e[t + 1], this.z = e[t + 2], this.w = e[t + 3], this;
  }
  /**
   * Writes the components of this vector to the given array. If no array is provided,
   * the method returns a new instance.
   *
   * @param {Array<number>} [array=[]] - The target array holding the vector components.
   * @param {number} [offset=0] - Index of the first element in the array.
   * @return {Array<number>} The vector components.
   */
  toArray(e = [], t = 0) {
    return e[t] = this.x, e[t + 1] = this.y, e[t + 2] = this.z, e[t + 3] = this.w, e;
  }
  /**
   * Sets the components of this vector from the given buffer attribute.
   *
   * @param {BufferAttribute} attribute - The buffer attribute holding vector data.
   * @param {number} index - The index into the attribute.
   * @return {Vector4} A reference to this vector.
   */
  fromBufferAttribute(e, t) {
    return this.x = e.getX(t), this.y = e.getY(t), this.z = e.getZ(t), this.w = e.getW(t), this;
  }
  /**
   * Sets each component of this vector to a pseudo-random value between `0` and
   * `1`, excluding `1`.
   *
   * @return {Vector4} A reference to this vector.
   */
  random() {
    return this.x = Math.random(), this.y = Math.random(), this.z = Math.random(), this.w = Math.random(), this;
  }
  *[Symbol.iterator]() {
    yield this.x, yield this.y, yield this.z, yield this.w;
  }
}
class cd extends sn {
  /**
   * Render target options.
   *
   * @typedef {Object} RenderTarget~Options
   * @property {boolean} [generateMipmaps=false] - Whether to generate mipmaps or not.
   * @property {number} [magFilter=LinearFilter] - The mag filter.
   * @property {number} [minFilter=LinearFilter] - The min filter.
   * @property {number} [format=RGBAFormat] - The texture format.
   * @property {number} [type=UnsignedByteType] - The texture type.
   * @property {?string} [internalFormat=null] - The texture's internal format.
   * @property {number} [wrapS=ClampToEdgeWrapping] - The texture's uv wrapping mode.
   * @property {number} [wrapT=ClampToEdgeWrapping] - The texture's uv wrapping mode.
   * @property {number} [anisotropy=1] - The texture's anisotropy value.
   * @property {string} [colorSpace=NoColorSpace] - The texture's color space.
   * @property {boolean} [depthBuffer=true] - Whether to allocate a depth buffer or not.
   * @property {boolean} [stencilBuffer=false] - Whether to allocate a stencil buffer or not.
   * @property {boolean} [resolveDepthBuffer=true] - Whether to resolve the depth buffer or not.
   * @property {boolean} [resolveStencilBuffer=true] - Whether  to resolve the stencil buffer or not.
   * @property {?Texture} [depthTexture=null] - Reference to a depth texture.
   * @property {number} [samples=0] - The MSAA samples count.
   * @property {number} [count=1] - Defines the number of color attachments . Must be at least `1`.
   * @property {number} [depth=1] - The texture depth.
   * @property {boolean} [multiview=false] - Whether this target is used for multiview rendering.
   */
  /**
   * Constructs a new render target.
   *
   * @param {number} [width=1] - The width of the render target.
   * @param {number} [height=1] - The height of the render target.
   * @param {RenderTarget~Options} [options] - The configuration object.
   */
  constructor(e = 1, t = 1, i = {}) {
    super(), i = Object.assign({
      generateMipmaps: !1,
      internalFormat: null,
      minFilter: Pt,
      depthBuffer: !0,
      stencilBuffer: !1,
      resolveDepthBuffer: !0,
      resolveStencilBuffer: !0,
      depthTexture: null,
      samples: 0,
      count: 1,
      depth: 1,
      multiview: !1
    }, i), this.isRenderTarget = !0, this.width = e, this.height = t, this.depth = i.depth, this.scissor = new Ye(0, 0, e, t), this.scissorTest = !1, this.viewport = new Ye(0, 0, e, t);
    const n = { width: e, height: t, depth: i.depth }, s = new Et(n);
    this.textures = [];
    const a = i.count;
    for (let o = 0; o < a; o++)
      this.textures[o] = s.clone(), this.textures[o].isRenderTargetTexture = !0, this.textures[o].renderTarget = this;
    this._setTextureOptions(i), this.depthBuffer = i.depthBuffer, this.stencilBuffer = i.stencilBuffer, this.resolveDepthBuffer = i.resolveDepthBuffer, this.resolveStencilBuffer = i.resolveStencilBuffer, this._depthTexture = null, this.depthTexture = i.depthTexture, this.samples = i.samples, this.multiview = i.multiview;
  }
  _setTextureOptions(e = {}) {
    const t = {
      minFilter: Pt,
      generateMipmaps: !1,
      flipY: !1,
      internalFormat: null
    };
    e.mapping !== void 0 && (t.mapping = e.mapping), e.wrapS !== void 0 && (t.wrapS = e.wrapS), e.wrapT !== void 0 && (t.wrapT = e.wrapT), e.wrapR !== void 0 && (t.wrapR = e.wrapR), e.magFilter !== void 0 && (t.magFilter = e.magFilter), e.minFilter !== void 0 && (t.minFilter = e.minFilter), e.format !== void 0 && (t.format = e.format), e.type !== void 0 && (t.type = e.type), e.anisotropy !== void 0 && (t.anisotropy = e.anisotropy), e.colorSpace !== void 0 && (t.colorSpace = e.colorSpace), e.flipY !== void 0 && (t.flipY = e.flipY), e.generateMipmaps !== void 0 && (t.generateMipmaps = e.generateMipmaps), e.internalFormat !== void 0 && (t.internalFormat = e.internalFormat);
    for (let i = 0; i < this.textures.length; i++)
      this.textures[i].setValues(t);
  }
  /**
   * The texture representing the default color attachment.
   *
   * @type {Texture}
   */
  get texture() {
    return this.textures[0];
  }
  set texture(e) {
    this.textures[0] = e;
  }
  set depthTexture(e) {
    this._depthTexture !== null && (this._depthTexture.renderTarget = null), e !== null && (e.renderTarget = this), this._depthTexture = e;
  }
  /**
   * Instead of saving the depth in a renderbuffer, a texture
   * can be used instead which is useful for further processing
   * e.g. in context of post-processing.
   *
   * @type {?DepthTexture}
   * @default null
   */
  get depthTexture() {
    return this._depthTexture;
  }
  /**
   * Sets the size of this render target.
   *
   * @param {number} width - The width.
   * @param {number} height - The height.
   * @param {number} [depth=1] - The depth.
   */
  setSize(e, t, i = 1) {
    if (this.width !== e || this.height !== t || this.depth !== i) {
      this.width = e, this.height = t, this.depth = i;
      for (let n = 0, s = this.textures.length; n < s; n++)
        this.textures[n].image.width = e, this.textures[n].image.height = t, this.textures[n].image.depth = i, this.textures[n].isArrayTexture = this.textures[n].image.depth > 1;
      this.dispose();
    }
    this.viewport.set(0, 0, e, t), this.scissor.set(0, 0, e, t);
  }
  /**
   * Returns a new render target with copied values from this instance.
   *
   * @return {RenderTarget} A clone of this instance.
   */
  clone() {
    return new this.constructor().copy(this);
  }
  /**
   * Copies the settings of the given render target. This is a structural copy so
   * no resources are shared between render targets after the copy. That includes
   * all MRT textures and the depth texture.
   *
   * @param {RenderTarget} source - The render target to copy.
   * @return {RenderTarget} A reference to this instance.
   */
  copy(e) {
    this.width = e.width, this.height = e.height, this.depth = e.depth, this.scissor.copy(e.scissor), this.scissorTest = e.scissorTest, this.viewport.copy(e.viewport), this.textures.length = 0;
    for (let t = 0, i = e.textures.length; t < i; t++) {
      this.textures[t] = e.textures[t].clone(), this.textures[t].isRenderTargetTexture = !0, this.textures[t].renderTarget = this;
      const n = Object.assign({}, e.textures[t].image);
      this.textures[t].source = new In(n);
    }
    return this.depthBuffer = e.depthBuffer, this.stencilBuffer = e.stencilBuffer, this.resolveDepthBuffer = e.resolveDepthBuffer, this.resolveStencilBuffer = e.resolveStencilBuffer, e.depthTexture !== null && (this.depthTexture = e.depthTexture.clone()), this.samples = e.samples, this;
  }
  /**
   * Frees the GPU-related resources allocated by this instance. Call this
   * method whenever this instance is no longer used in your app.
   *
   * @fires RenderTarget#dispose
   */
  dispose() {
    this.dispatchEvent({ type: "dispose" });
  }
}
class nn extends cd {
  /**
   * Constructs a new 3D render target.
   *
   * @param {number} [width=1] - The width of the render target.
   * @param {number} [height=1] - The height of the render target.
   * @param {RenderTarget~Options} [options] - The configuration object.
   */
  constructor(e = 1, t = 1, i = {}) {
    super(e, t, i), this.isWebGLRenderTarget = !0;
  }
}
class Wl extends Et {
  /**
   * Constructs a new data array texture.
   *
   * @param {?TypedArray} [data=null] - The buffer data.
   * @param {number} [width=1] - The width of the texture.
   * @param {number} [height=1] - The height of the texture.
   * @param {number} [depth=1] - The depth of the texture.
   */
  constructor(e = null, t = 1, i = 1, n = 1) {
    super(null), this.isDataArrayTexture = !0, this.image = { data: e, width: t, height: i, depth: n }, this.magFilter = Xt, this.minFilter = Xt, this.wrapR = fi, this.generateMipmaps = !1, this.flipY = !1, this.unpackAlignment = 1, this.layerUpdates = /* @__PURE__ */ new Set();
  }
  /**
   * Describes that a specific layer of the texture needs to be updated.
   * Normally when {@link Texture#needsUpdate} is set to `true`, the
   * entire data texture array is sent to the GPU. Marking specific
   * layers will only transmit subsets of all mipmaps associated with a
   * specific depth in the array which is often much more performant.
   *
   * @param {number} layerIndex - The layer index that should be updated.
   */
  addLayerUpdate(e) {
    this.layerUpdates.add(e);
  }
  /**
   * Resets the layer updates registry.
   */
  clearLayerUpdates() {
    this.layerUpdates.clear();
  }
}
class F_ extends nn {
  /**
   * Constructs a new array render target.
   *
   * @param {number} [width=1] - The width of the render target.
   * @param {number} [height=1] - The height of the render target.
   * @param {number} [depth=1] - The height of the render target.
   * @param {RenderTarget~Options} [options] - The configuration object.
   */
  constructor(e = 1, t = 1, i = 1, n = {}) {
    super(e, t, n), this.isWebGLArrayRenderTarget = !0, this.depth = i, this.texture = new Wl(null, e, t, i), this._setTextureOptions(n), this.texture.isRenderTargetTexture = !0;
  }
}
class Xl extends Et {
  /**
   * Constructs a new data array texture.
   *
   * @param {?TypedArray} [data=null] - The buffer data.
   * @param {number} [width=1] - The width of the texture.
   * @param {number} [height=1] - The height of the texture.
   * @param {number} [depth=1] - The depth of the texture.
   */
  constructor(e = null, t = 1, i = 1, n = 1) {
    super(null), this.isData3DTexture = !0, this.image = { data: e, width: t, height: i, depth: n }, this.magFilter = Xt, this.minFilter = Xt, this.wrapR = fi, this.generateMipmaps = !1, this.flipY = !1, this.unpackAlignment = 1;
  }
}
class B_ extends nn {
  /**
   * Constructs a new 3D render target.
   *
   * @param {number} [width=1] - The width of the render target.
   * @param {number} [height=1] - The height of the render target.
   * @param {number} [depth=1] - The height of the render target.
   * @param {RenderTarget~Options} [options] - The configuration object.
   */
  constructor(e = 1, t = 1, i = 1, n = {}) {
    super(e, t, n), this.isWebGL3DRenderTarget = !0, this.depth = i, this.texture = new Xl(null, e, t, i), this._setTextureOptions(n), this.texture.isRenderTargetTexture = !0;
  }
}
class Tt {
  /**
   * Constructs a new bounding box.
   *
   * @param {Vector3} [min=(Infinity,Infinity,Infinity)] - A vector representing the lower boundary of the box.
   * @param {Vector3} [max=(-Infinity,-Infinity,-Infinity)] - A vector representing the upper boundary of the box.
   */
  constructor(e = new b(1 / 0, 1 / 0, 1 / 0), t = new b(-1 / 0, -1 / 0, -1 / 0)) {
    this.isBox3 = !0, this.min = e, this.max = t;
  }
  /**
   * Sets the lower and upper boundaries of this box.
   * Please note that this method only copies the values from the given objects.
   *
   * @param {Vector3} min - The lower boundary of the box.
   * @param {Vector3} max - The upper boundary of the box.
   * @return {Box3} A reference to this bounding box.
   */
  set(e, t) {
    return this.min.copy(e), this.max.copy(t), this;
  }
  /**
   * Sets the upper and lower bounds of this box so it encloses the position data
   * in the given array.
   *
   * @param {Array<number>} array - An array holding 3D position data.
   * @return {Box3} A reference to this bounding box.
   */
  setFromArray(e) {
    this.makeEmpty();
    for (let t = 0, i = e.length; t < i; t += 3)
      this.expandByPoint(Ui.fromArray(e, t));
    return this;
  }
  /**
   * Sets the upper and lower bounds of this box so it encloses the position data
   * in the given buffer attribute.
   *
   * @param {BufferAttribute} attribute - A buffer attribute holding 3D position data.
   * @return {Box3} A reference to this bounding box.
   */
  setFromBufferAttribute(e) {
    this.makeEmpty();
    for (let t = 0, i = e.count; t < i; t++)
      this.expandByPoint(Ui.fromBufferAttribute(e, t));
    return this;
  }
  /**
   * Sets the upper and lower bounds of this box so it encloses the position data
   * in the given array.
   *
   * @param {Array<Vector3>} points - An array holding 3D position data as instances of {@link Vector3}.
   * @return {Box3} A reference to this bounding box.
   */
  setFromPoints(e) {
    this.makeEmpty();
    for (let t = 0, i = e.length; t < i; t++)
      this.expandByPoint(e[t]);
    return this;
  }
  /**
   * Centers this box on the given center vector and sets this box's width, height and
   * depth to the given size values.
   *
   * @param {Vector3} center - The center of the box.
   * @param {Vector3} size - The x, y and z dimensions of the box.
   * @return {Box3} A reference to this bounding box.
   */
  setFromCenterAndSize(e, t) {
    const i = Ui.copy(t).multiplyScalar(0.5);
    return this.min.copy(e).sub(i), this.max.copy(e).add(i), this;
  }
  /**
   * Computes the world-axis-aligned bounding box for the given 3D object
   * (including its children), accounting for the object's, and children's,
   * world transforms. The function may result in a larger box than strictly necessary.
   *
   * @param {Object3D} object - The 3D object to compute the bounding box for.
   * @param {boolean} [precise=false] - If set to `true`, the method computes the smallest
   * world-axis-aligned bounding box at the expense of more computation.
   * @return {Box3} A reference to this bounding box.
   */
  setFromObject(e, t = !1) {
    return this.makeEmpty(), this.expandByObject(e, t);
  }
  /**
   * Returns a new box with copied values from this instance.
   *
   * @return {Box3} A clone of this instance.
   */
  clone() {
    return new this.constructor().copy(this);
  }
  /**
   * Copies the values of the given box to this instance.
   *
   * @param {Box3} box - The box to copy.
   * @return {Box3} A reference to this bounding box.
   */
  copy(e) {
    return this.min.copy(e.min), this.max.copy(e.max), this;
  }
  /**
   * Makes this box empty which means in encloses a zero space in 3D.
   *
   * @return {Box3} A reference to this bounding box.
   */
  makeEmpty() {
    return this.min.x = this.min.y = this.min.z = 1 / 0, this.max.x = this.max.y = this.max.z = -1 / 0, this;
  }
  /**
   * Returns true if this box includes zero points within its bounds.
   * Note that a box with equal lower and upper bounds still includes one
   * point, the one both bounds share.
   *
   * @return {boolean} Whether this box is empty or not.
   */
  isEmpty() {
    return this.max.x < this.min.x || this.max.y < this.min.y || this.max.z < this.min.z;
  }
  /**
   * Returns the center point of this box.
   *
   * @param {Vector3} target - The target vector that is used to store the method's result.
   * @return {Vector3} The center point.
   */
  getCenter(e) {
    return this.isEmpty() ? e.set(0, 0, 0) : e.addVectors(this.min, this.max).multiplyScalar(0.5);
  }
  /**
   * Returns the dimensions of this box.
   *
   * @param {Vector3} target - The target vector that is used to store the method's result.
   * @return {Vector3} The size.
   */
  getSize(e) {
    return this.isEmpty() ? e.set(0, 0, 0) : e.subVectors(this.max, this.min);
  }
  /**
   * Expands the boundaries of this box to include the given point.
   *
   * @param {Vector3} point - The point that should be included by the bounding box.
   * @return {Box3} A reference to this bounding box.
   */
  expandByPoint(e) {
    return this.min.min(e), this.max.max(e), this;
  }
  /**
   * Expands this box equilaterally by the given vector. The width of this
   * box will be expanded by the x component of the vector in both
   * directions. The height of this box will be expanded by the y component of
   * the vector in both directions. The depth of this box will be
   * expanded by the z component of the vector in both directions.
   *
   * @param {Vector3} vector - The vector that should expand the bounding box.
   * @return {Box3} A reference to this bounding box.
   */
  expandByVector(e) {
    return this.min.sub(e), this.max.add(e), this;
  }
  /**
   * Expands each dimension of the box by the given scalar. If negative, the
   * dimensions of the box will be contracted.
   *
   * @param {number} scalar - The scalar value that should expand the bounding box.
   * @return {Box3} A reference to this bounding box.
   */
  expandByScalar(e) {
    return this.min.addScalar(-e), this.max.addScalar(e), this;
  }
  /**
   * Expands the boundaries of this box to include the given 3D object and
   * its children, accounting for the object's, and children's, world
   * transforms. The function may result in a larger box than strictly
   * necessary (unless the precise parameter is set to true).
   *
   * @param {Object3D} object - The 3D object that should expand the bounding box.
   * @param {boolean} precise - If set to `true`, the method expands the bounding box
   * as little as necessary at the expense of more computation.
   * @return {Box3} A reference to this bounding box.
   */
  expandByObject(e, t = !1) {
    e.updateWorldMatrix(!1, !1);
    const i = e.geometry;
    if (i !== void 0) {
      const s = i.getAttribute("position");
      if (t === !0 && s !== void 0 && e.isInstancedMesh !== !0)
        for (let a = 0, o = s.count; a < o; a++)
          e.isMesh === !0 ? e.getVertexPosition(a, Ui) : Ui.fromBufferAttribute(s, a), Ui.applyMatrix4(e.matrixWorld), this.expandByPoint(Ui);
      else
        e.boundingBox !== void 0 ? (e.boundingBox === null && e.computeBoundingBox(), Pa.copy(e.boundingBox)) : (i.boundingBox === null && i.computeBoundingBox(), Pa.copy(i.boundingBox)), Pa.applyMatrix4(e.matrixWorld), this.union(Pa);
    }
    const n = e.children;
    for (let s = 0, a = n.length; s < a; s++)
      this.expandByObject(n[s], t);
    return this;
  }
  /**
   * Returns `true` if the given point lies within or on the boundaries of this box.
   *
   * @param {Vector3} point - The point to test.
   * @return {boolean} Whether the bounding box contains the given point or not.
   */
  containsPoint(e) {
    return e.x >= this.min.x && e.x <= this.max.x && e.y >= this.min.y && e.y <= this.max.y && e.z >= this.min.z && e.z <= this.max.z;
  }
  /**
   * Returns `true` if this bounding box includes the entirety of the given bounding box.
   * If this box and the given one are identical, this function also returns `true`.
   *
   * @param {Box3} box - The bounding box to test.
   * @return {boolean} Whether the bounding box contains the given bounding box or not.
   */
  containsBox(e) {
    return this.min.x <= e.min.x && e.max.x <= this.max.x && this.min.y <= e.min.y && e.max.y <= this.max.y && this.min.z <= e.min.z && e.max.z <= this.max.z;
  }
  /**
   * Returns a point as a proportion of this box's width, height and depth.
   *
   * @param {Vector3} point - A point in 3D space.
   * @param {Vector3} target - The target vector that is used to store the method's result.
   * @return {Vector3} A point as a proportion of this box's width, height and depth.
   */
  getParameter(e, t) {
    return t.set(
      (e.x - this.min.x) / (this.max.x - this.min.x),
      (e.y - this.min.y) / (this.max.y - this.min.y),
      (e.z - this.min.z) / (this.max.z - this.min.z)
    );
  }
  /**
   * Returns `true` if the given bounding box intersects with this bounding box.
   *
   * @param {Box3} box - The bounding box to test.
   * @return {boolean} Whether the given bounding box intersects with this bounding box.
   */
  intersectsBox(e) {
    return e.max.x >= this.min.x && e.min.x <= this.max.x && e.max.y >= this.min.y && e.min.y <= this.max.y && e.max.z >= this.min.z && e.min.z <= this.max.z;
  }
  /**
   * Returns `true` if the given bounding sphere intersects with this bounding box.
   *
   * @param {Sphere} sphere - The bounding sphere to test.
   * @return {boolean} Whether the given bounding sphere intersects with this bounding box.
   */
  intersectsSphere(e) {
    return this.clampPoint(e.center, Ui), Ui.distanceToSquared(e.center) <= e.radius * e.radius;
  }
  /**
   * Returns `true` if the given plane intersects with this bounding box.
   *
   * @param {Plane} plane - The plane to test.
   * @return {boolean} Whether the given plane intersects with this bounding box.
   */
  intersectsPlane(e) {
    let t, i;
    return e.normal.x > 0 ? (t = e.normal.x * this.min.x, i = e.normal.x * this.max.x) : (t = e.normal.x * this.max.x, i = e.normal.x * this.min.x), e.normal.y > 0 ? (t += e.normal.y * this.min.y, i += e.normal.y * this.max.y) : (t += e.normal.y * this.max.y, i += e.normal.y * this.min.y), e.normal.z > 0 ? (t += e.normal.z * this.min.z, i += e.normal.z * this.max.z) : (t += e.normal.z * this.max.z, i += e.normal.z * this.min.z), t <= -e.constant && i >= -e.constant;
  }
  /**
   * Returns `true` if the given triangle intersects with this bounding box.
   *
   * @param {Triangle} triangle - The triangle to test.
   * @return {boolean} Whether the given triangle intersects with this bounding box.
   */
  intersectsTriangle(e) {
    if (this.isEmpty())
      return !1;
    this.getCenter(Ar), La.subVectors(this.max, Ar), Ls.subVectors(e.a, Ar), Is.subVectors(e.b, Ar), Ds.subVectors(e.c, Ar), xn.subVectors(Is, Ls), bn.subVectors(Ds, Is), qn.subVectors(Ls, Ds);
    let t = [
      0,
      -xn.z,
      xn.y,
      0,
      -bn.z,
      bn.y,
      0,
      -qn.z,
      qn.y,
      xn.z,
      0,
      -xn.x,
      bn.z,
      0,
      -bn.x,
      qn.z,
      0,
      -qn.x,
      -xn.y,
      xn.x,
      0,
      -bn.y,
      bn.x,
      0,
      -qn.y,
      qn.x,
      0
    ];
    return !wc(t, Ls, Is, Ds, La) || (t = [1, 0, 0, 0, 1, 0, 0, 0, 1], !wc(t, Ls, Is, Ds, La)) ? !1 : (Ia.crossVectors(xn, bn), t = [Ia.x, Ia.y, Ia.z], wc(t, Ls, Is, Ds, La));
  }
  /**
   * Clamps the given point within the bounds of this box.
   *
   * @param {Vector3} point - The point to clamp.
   * @param {Vector3} target - The target vector that is used to store the method's result.
   * @return {Vector3} The clamped point.
   */
  clampPoint(e, t) {
    return t.copy(e).clamp(this.min, this.max);
  }
  /**
   * Returns the euclidean distance from any edge of this box to the specified point. If
   * the given point lies inside of this box, the distance will be `0`.
   *
   * @param {Vector3} point - The point to compute the distance to.
   * @return {number} The euclidean distance.
   */
  distanceToPoint(e) {
    return this.clampPoint(e, Ui).distanceTo(e);
  }
  /**
   * Returns a bounding sphere that encloses this bounding box.
   *
   * @param {Sphere} target - The target sphere that is used to store the method's result.
   * @return {Sphere} The bounding sphere that encloses this bounding box.
   */
  getBoundingSphere(e) {
    return this.isEmpty() ? e.makeEmpty() : (this.getCenter(e.center), e.radius = this.getSize(Ui).length() * 0.5), e;
  }
  /**
   * Computes the intersection of this bounding box and the given one, setting the upper
   * bound of this box to the lesser of the two boxes' upper bounds and the
   * lower bound of this box to the greater of the two boxes' lower bounds. If
   * there's no overlap, makes this box empty.
   *
   * @param {Box3} box - The bounding box to intersect with.
   * @return {Box3} A reference to this bounding box.
   */
  intersect(e) {
    return this.min.max(e.min), this.max.min(e.max), this.isEmpty() && this.makeEmpty(), this;
  }
  /**
   * Computes the union of this box and another and the given one, setting the upper
   * bound of this box to the greater of the two boxes' upper bounds and the
   * lower bound of this box to the lesser of the two boxes' lower bounds.
   *
   * @param {Box3} box - The bounding box that will be unioned with this instance.
   * @return {Box3} A reference to this bounding box.
   */
  union(e) {
    return this.min.min(e.min), this.max.max(e.max), this;
  }
  /**
   * Transforms this bounding box by the given 4x4 transformation matrix.
   *
   * @param {Matrix4} matrix - The transformation matrix.
   * @return {Box3} A reference to this bounding box.
   */
  applyMatrix4(e) {
    return this.isEmpty() ? this : (an[0].set(this.min.x, this.min.y, this.min.z).applyMatrix4(e), an[1].set(this.min.x, this.min.y, this.max.z).applyMatrix4(e), an[2].set(this.min.x, this.max.y, this.min.z).applyMatrix4(e), an[3].set(this.min.x, this.max.y, this.max.z).applyMatrix4(e), an[4].set(this.max.x, this.min.y, this.min.z).applyMatrix4(e), an[5].set(this.max.x, this.min.y, this.max.z).applyMatrix4(e), an[6].set(this.max.x, this.max.y, this.min.z).applyMatrix4(e), an[7].set(this.max.x, this.max.y, this.max.z).applyMatrix4(e), this.setFromPoints(an), this);
  }
  /**
   * Adds the given offset to both the upper and lower bounds of this bounding box,
   * effectively moving it in 3D space.
   *
   * @param {Vector3} offset - The offset that should be used to translate the bounding box.
   * @return {Box3} A reference to this bounding box.
   */
  translate(e) {
    return this.min.add(e), this.max.add(e), this;
  }
  /**
   * Returns `true` if this bounding box is equal with the given one.
   *
   * @param {Box3} box - The box to test for equality.
   * @return {boolean} Whether this bounding box is equal with the given one.
   */
  equals(e) {
    return e.min.equals(this.min) && e.max.equals(this.max);
  }
  /**
   * Returns a serialized structure of the bounding box.
   *
   * @return {Object} Serialized structure with fields representing the object state.
   */
  toJSON() {
    return {
      min: this.min.toArray(),
      max: this.max.toArray()
    };
  }
  /**
   * Returns a serialized structure of the bounding box.
   *
   * @param {Object} json - The serialized json to set the box from.
   * @return {Box3} A reference to this bounding box.
   */
  fromJSON(e) {
    return this.min.fromArray(e.min), this.max.fromArray(e.max), this;
  }
}
const an = [
  /* @__PURE__ */ new b(),
  /* @__PURE__ */ new b(),
  /* @__PURE__ */ new b(),
  /* @__PURE__ */ new b(),
  /* @__PURE__ */ new b(),
  /* @__PURE__ */ new b(),
  /* @__PURE__ */ new b(),
  /* @__PURE__ */ new b()
], Ui = /* @__PURE__ */ new b(), Pa = /* @__PURE__ */ new Tt(), Ls = /* @__PURE__ */ new b(), Is = /* @__PURE__ */ new b(), Ds = /* @__PURE__ */ new b(), xn = /* @__PURE__ */ new b(), bn = /* @__PURE__ */ new b(), qn = /* @__PURE__ */ new b(), Ar = /* @__PURE__ */ new b(), La = /* @__PURE__ */ new b(), Ia = /* @__PURE__ */ new b(), Zn = /* @__PURE__ */ new b();
function wc(r, e, t, i, n) {
  for (let s = 0, a = r.length - 3; s <= a; s += 3) {
    Zn.fromArray(r, s);
    const o = n.x * Math.abs(Zn.x) + n.y * Math.abs(Zn.y) + n.z * Math.abs(Zn.z), l = e.dot(Zn), c = t.dot(Zn), h = i.dot(Zn);
    if (Math.max(-Math.max(l, c, h), Math.min(l, c, h)) > o)
      return !1;
  }
  return !0;
}
const k_ = /* @__PURE__ */ new Tt(), Cr = /* @__PURE__ */ new b(), Ec = /* @__PURE__ */ new b();
class Lt {
  /**
   * Constructs a new sphere.
   *
   * @param {Vector3} [center=(0,0,0)] - The center of the sphere
   * @param {number} [radius=-1] - The radius of the sphere.
   */
  constructor(e = new b(), t = -1) {
    this.isSphere = !0, this.center = e, this.radius = t;
  }
  /**
   * Sets the sphere's components by copying the given values.
   *
   * @param {Vector3} center - The center.
   * @param {number} radius - The radius.
   * @return {Sphere} A reference to this sphere.
   */
  set(e, t) {
    return this.center.copy(e), this.radius = t, this;
  }
  /**
   * Computes the minimum bounding sphere for list of points.
   * If the optional center point is given, it is used as the sphere's
   * center. Otherwise, the center of the axis-aligned bounding box
   * encompassing the points is calculated.
   *
   * @param {Array<Vector3>} points - A list of points in 3D space.
   * @param {Vector3} [optionalCenter] - The center of the sphere.
   * @return {Sphere} A reference to this sphere.
   */
  setFromPoints(e, t) {
    const i = this.center;
    t !== void 0 ? i.copy(t) : k_.setFromPoints(e).getCenter(i);
    let n = 0;
    for (let s = 0, a = e.length; s < a; s++)
      n = Math.max(n, i.distanceToSquared(e[s]));
    return this.radius = Math.sqrt(n), this;
  }
  /**
   * Copies the values of the given sphere to this instance.
   *
   * @param {Sphere} sphere - The sphere to copy.
   * @return {Sphere} A reference to this sphere.
   */
  copy(e) {
    return this.center.copy(e.center), this.radius = e.radius, this;
  }
  /**
   * Returns `true` if the sphere is empty (the radius set to a negative number).
   *
   * Spheres with a radius of `0` contain only their center point and are not
   * considered to be empty.
   *
   * @return {boolean} Whether this sphere is empty or not.
   */
  isEmpty() {
    return this.radius < 0;
  }
  /**
   * Makes this sphere empty which means in encloses a zero space in 3D.
   *
   * @return {Sphere} A reference to this sphere.
   */
  makeEmpty() {
    return this.center.set(0, 0, 0), this.radius = -1, this;
  }
  /**
   * Returns `true` if this sphere contains the given point inclusive of
   * the surface of the sphere.
   *
   * @param {Vector3} point - The point to check.
   * @return {boolean} Whether this sphere contains the given point or not.
   */
  containsPoint(e) {
    return e.distanceToSquared(this.center) <= this.radius * this.radius;
  }
  /**
   * Returns the closest distance from the boundary of the sphere to the
   * given point. If the sphere contains the point, the distance will
   * be negative.
   *
   * @param {Vector3} point - The point to compute the distance to.
   * @return {number} The distance to the point.
   */
  distanceToPoint(e) {
    return e.distanceTo(this.center) - this.radius;
  }
  /**
   * Returns `true` if this sphere intersects with the given one.
   *
   * @param {Sphere} sphere - The sphere to test.
   * @return {boolean} Whether this sphere intersects with the given one or not.
   */
  intersectsSphere(e) {
    const t = this.radius + e.radius;
    return e.center.distanceToSquared(this.center) <= t * t;
  }
  /**
   * Returns `true` if this sphere intersects with the given box.
   *
   * @param {Box3} box - The box to test.
   * @return {boolean} Whether this sphere intersects with the given box or not.
   */
  intersectsBox(e) {
    return e.intersectsSphere(this);
  }
  /**
   * Returns `true` if this sphere intersects with the given plane.
   *
   * @param {Plane} plane - The plane to test.
   * @return {boolean} Whether this sphere intersects with the given plane or not.
   */
  intersectsPlane(e) {
    return Math.abs(e.distanceToPoint(this.center)) <= this.radius;
  }
  /**
   * Clamps a point within the sphere. If the point is outside the sphere, it
   * will clamp it to the closest point on the edge of the sphere. Points
   * already inside the sphere will not be affected.
   *
   * @param {Vector3} point - The plane to clamp.
   * @param {Vector3} target - The target vector that is used to store the method's result.
   * @return {Vector3} The clamped point.
   */
  clampPoint(e, t) {
    const i = this.center.distanceToSquared(e);
    return t.copy(e), i > this.radius * this.radius && (t.sub(this.center).normalize(), t.multiplyScalar(this.radius).add(this.center)), t;
  }
  /**
   * Returns a bounding box that encloses this sphere.
   *
   * @param {Box3} target - The target box that is used to store the method's result.
   * @return {Box3} The bounding box that encloses this sphere.
   */
  getBoundingBox(e) {
    return this.isEmpty() ? (e.makeEmpty(), e) : (e.set(this.center, this.center), e.expandByScalar(this.radius), e);
  }
  /**
   * Transforms this sphere with the given 4x4 transformation matrix.
   *
   * @param {Matrix4} matrix - The transformation matrix.
   * @return {Sphere} A reference to this sphere.
   */
  applyMatrix4(e) {
    return this.center.applyMatrix4(e), this.radius = this.radius * e.getMaxScaleOnAxis(), this;
  }
  /**
   * Translates the sphere's center by the given offset.
   *
   * @param {Vector3} offset - The offset.
   * @return {Sphere} A reference to this sphere.
   */
  translate(e) {
    return this.center.add(e), this;
  }
  /**
   * Expands the boundaries of this sphere to include the given point.
   *
   * @param {Vector3} point - The point to include.
   * @return {Sphere} A reference to this sphere.
   */
  expandByPoint(e) {
    if (this.isEmpty())
      return this.center.copy(e), this.radius = 0, this;
    Cr.subVectors(e, this.center);
    const t = Cr.lengthSq();
    if (t > this.radius * this.radius) {
      const i = Math.sqrt(t), n = (i - this.radius) * 0.5;
      this.center.addScaledVector(Cr, n / i), this.radius += n;
    }
    return this;
  }
  /**
   * Expands this sphere to enclose both the original sphere and the given sphere.
   *
   * @param {Sphere} sphere - The sphere to include.
   * @return {Sphere} A reference to this sphere.
   */
  union(e) {
    return e.isEmpty() ? this : this.isEmpty() ? (this.copy(e), this) : (this.center.equals(e.center) === !0 ? this.radius = Math.max(this.radius, e.radius) : (Ec.subVectors(e.center, this.center).setLength(e.radius), this.expandByPoint(Cr.copy(e.center).add(Ec)), this.expandByPoint(Cr.copy(e.center).sub(Ec))), this);
  }
  /**
   * Returns `true` if this sphere is equal with the given one.
   *
   * @param {Sphere} sphere - The sphere to test for equality.
   * @return {boolean} Whether this bounding sphere is equal with the given one.
   */
  equals(e) {
    return e.center.equals(this.center) && e.radius === this.radius;
  }
  /**
   * Returns a new sphere with copied values from this instance.
   *
   * @return {Sphere} A clone of this instance.
   */
  clone() {
    return new this.constructor().copy(this);
  }
  /**
   * Returns a serialized structure of the bounding sphere.
   *
   * @return {Object} Serialized structure with fields representing the object state.
   */
  toJSON() {
    return {
      radius: this.radius,
      center: this.center.toArray()
    };
  }
  /**
   * Returns a serialized structure of the bounding sphere.
   *
   * @param {Object} json - The serialized json to set the sphere from.
   * @return {Box3} A reference to this bounding sphere.
   */
  fromJSON(e) {
    return this.radius = e.radius, this.center.fromArray(e.center), this;
  }
}
const on = /* @__PURE__ */ new b(), Tc = /* @__PURE__ */ new b(), Da = /* @__PURE__ */ new b(), Sn = /* @__PURE__ */ new b(), Ac = /* @__PURE__ */ new b(), Na = /* @__PURE__ */ new b(), Cc = /* @__PURE__ */ new b();
class ws {
  /**
   * Constructs a new ray.
   *
   * @param {Vector3} [origin=(0,0,0)] - The origin of the ray.
   * @param {Vector3} [direction=(0,0,-1)] - The (normalized) direction of the ray.
   */
  constructor(e = new b(), t = new b(0, 0, -1)) {
    this.origin = e, this.direction = t;
  }
  /**
   * Sets the ray's components by copying the given values.
   *
   * @param {Vector3} origin - The origin.
   * @param {Vector3} direction - The direction.
   * @return {Ray} A reference to this ray.
   */
  set(e, t) {
    return this.origin.copy(e), this.direction.copy(t), this;
  }
  /**
   * Copies the values of the given ray to this instance.
   *
   * @param {Ray} ray - The ray to copy.
   * @return {Ray} A reference to this ray.
   */
  copy(e) {
    return this.origin.copy(e.origin), this.direction.copy(e.direction), this;
  }
  /**
   * Returns a vector that is located at a given distance along this ray.
   *
   * @param {number} t - The distance along the ray to retrieve a position for.
   * @param {Vector3} target - The target vector that is used to store the method's result.
   * @return {Vector3} A position on the ray.
   */
  at(e, t) {
    return t.copy(this.origin).addScaledVector(this.direction, e);
  }
  /**
   * Adjusts the direction of the ray to point at the given vector in world space.
   *
   * @param {Vector3} v - The target position.
   * @return {Ray} A reference to this ray.
   */
  lookAt(e) {
    return this.direction.copy(e).sub(this.origin).normalize(), this;
  }
  /**
   * Shift the origin of this ray along its direction by the given distance.
   *
   * @param {number} t - The distance along the ray to interpolate.
   * @return {Ray} A reference to this ray.
   */
  recast(e) {
    return this.origin.copy(this.at(e, on)), this;
  }
  /**
   * Returns the point along this ray that is closest to the given point.
   *
   * @param {Vector3} point - A point in 3D space to get the closet location on the ray for.
   * @param {Vector3} target - The target vector that is used to store the method's result.
   * @return {Vector3} The closest point on this ray.
   */
  closestPointToPoint(e, t) {
    t.subVectors(e, this.origin);
    const i = t.dot(this.direction);
    return i < 0 ? t.copy(this.origin) : t.copy(this.origin).addScaledVector(this.direction, i);
  }
  /**
   * Returns the distance of the closest approach between this ray and the given point.
   *
   * @param {Vector3} point - A point in 3D space to compute the distance to.
   * @return {number} The distance.
   */
  distanceToPoint(e) {
    return Math.sqrt(this.distanceSqToPoint(e));
  }
  /**
   * Returns the squared distance of the closest approach between this ray and the given point.
   *
   * @param {Vector3} point - A point in 3D space to compute the distance to.
   * @return {number} The squared distance.
   */
  distanceSqToPoint(e) {
    const t = on.subVectors(e, this.origin).dot(this.direction);
    return t < 0 ? this.origin.distanceToSquared(e) : (on.copy(this.origin).addScaledVector(this.direction, t), on.distanceToSquared(e));
  }
  /**
   * Returns the squared distance between this ray and the given line segment.
   *
   * @param {Vector3} v0 - The start point of the line segment.
   * @param {Vector3} v1 - The end point of the line segment.
   * @param {Vector3} [optionalPointOnRay] - When provided, it receives the point on this ray that is closest to the segment.
   * @param {Vector3} [optionalPointOnSegment] - When provided, it receives the point on the line segment that is closest to this ray.
   * @return {number} The squared distance.
   */
  distanceSqToSegment(e, t, i, n) {
    Tc.copy(e).add(t).multiplyScalar(0.5), Da.copy(t).sub(e).normalize(), Sn.copy(this.origin).sub(Tc);
    const s = e.distanceTo(t) * 0.5, a = -this.direction.dot(Da), o = Sn.dot(this.direction), l = -Sn.dot(Da), c = Sn.lengthSq(), h = Math.abs(1 - a * a);
    let d, u, p, m;
    if (h > 0)
      if (d = a * l - o, u = a * o - l, m = s * h, d >= 0)
        if (u >= -m)
          if (u <= m) {
            const _ = 1 / h;
            d *= _, u *= _, p = d * (d + a * u + 2 * o) + u * (a * d + u + 2 * l) + c;
          } else
            u = s, d = Math.max(0, -(a * u + o)), p = -d * d + u * (u + 2 * l) + c;
        else
          u = -s, d = Math.max(0, -(a * u + o)), p = -d * d + u * (u + 2 * l) + c;
      else
        u <= -m ? (d = Math.max(0, -(-a * s + o)), u = d > 0 ? -s : Math.min(Math.max(-s, -l), s), p = -d * d + u * (u + 2 * l) + c) : u <= m ? (d = 0, u = Math.min(Math.max(-s, -l), s), p = u * (u + 2 * l) + c) : (d = Math.max(0, -(a * s + o)), u = d > 0 ? s : Math.min(Math.max(-s, -l), s), p = -d * d + u * (u + 2 * l) + c);
    else
      u = a > 0 ? -s : s, d = Math.max(0, -(a * u + o)), p = -d * d + u * (u + 2 * l) + c;
    return i && i.copy(this.origin).addScaledVector(this.direction, d), n && n.copy(Tc).addScaledVector(Da, u), p;
  }
  /**
   * Intersects this ray with the given sphere, returning the intersection
   * point or `null` if there is no intersection.
   *
   * @param {Sphere} sphere - The sphere to intersect.
   * @param {Vector3} target - The target vector that is used to store the method's result.
   * @return {?Vector3} The intersection point.
   */
  intersectSphere(e, t) {
    on.subVectors(e.center, this.origin);
    const i = on.dot(this.direction), n = on.dot(on) - i * i, s = e.radius * e.radius;
    if (n > s) return null;
    const a = Math.sqrt(s - n), o = i - a, l = i + a;
    return l < 0 ? null : o < 0 ? this.at(l, t) : this.at(o, t);
  }
  /**
   * Returns `true` if this ray intersects with the given sphere.
   *
   * @param {Sphere} sphere - The sphere to intersect.
   * @return {boolean} Whether this ray intersects with the given sphere or not.
   */
  intersectsSphere(e) {
    return e.radius < 0 ? !1 : this.distanceSqToPoint(e.center) <= e.radius * e.radius;
  }
  /**
   * Computes the distance from the ray's origin to the given plane. Returns `null` if the ray
   * does not intersect with the plane.
   *
   * @param {Plane} plane - The plane to compute the distance to.
   * @return {?number} Whether this ray intersects with the given sphere or not.
   */
  distanceToPlane(e) {
    const t = e.normal.dot(this.direction);
    if (t === 0)
      return e.distanceToPoint(this.origin) === 0 ? 0 : null;
    const i = -(this.origin.dot(e.normal) + e.constant) / t;
    return i >= 0 ? i : null;
  }
  /**
   * Intersects this ray with the given plane, returning the intersection
   * point or `null` if there is no intersection.
   *
   * @param {Plane} plane - The plane to intersect.
   * @param {Vector3} target - The target vector that is used to store the method's result.
   * @return {?Vector3} The intersection point.
   */
  intersectPlane(e, t) {
    const i = this.distanceToPlane(e);
    return i === null ? null : this.at(i, t);
  }
  /**
   * Returns `true` if this ray intersects with the given plane.
   *
   * @param {Plane} plane - The plane to intersect.
   * @return {boolean} Whether this ray intersects with the given plane or not.
   */
  intersectsPlane(e) {
    const t = e.distanceToPoint(this.origin);
    return t === 0 || e.normal.dot(this.direction) * t < 0;
  }
  /**
   * Intersects this ray with the given bounding box, returning the intersection
   * point or `null` if there is no intersection.
   *
   * @param {Box3} box - The box to intersect.
   * @param {Vector3} target - The target vector that is used to store the method's result.
   * @return {?Vector3} The intersection point.
   */
  intersectBox(e, t) {
    let i, n, s, a, o, l;
    const c = 1 / this.direction.x, h = 1 / this.direction.y, d = 1 / this.direction.z, u = this.origin;
    return c >= 0 ? (i = (e.min.x - u.x) * c, n = (e.max.x - u.x) * c) : (i = (e.max.x - u.x) * c, n = (e.min.x - u.x) * c), h >= 0 ? (s = (e.min.y - u.y) * h, a = (e.max.y - u.y) * h) : (s = (e.max.y - u.y) * h, a = (e.min.y - u.y) * h), i > a || s > n || ((s > i || isNaN(i)) && (i = s), (a < n || isNaN(n)) && (n = a), d >= 0 ? (o = (e.min.z - u.z) * d, l = (e.max.z - u.z) * d) : (o = (e.max.z - u.z) * d, l = (e.min.z - u.z) * d), i > l || o > n) || ((o > i || i !== i) && (i = o), (l < n || n !== n) && (n = l), n < 0) ? null : this.at(i >= 0 ? i : n, t);
  }
  /**
   * Returns `true` if this ray intersects with the given box.
   *
   * @param {Box3} box - The box to intersect.
   * @return {boolean} Whether this ray intersects with the given box or not.
   */
  intersectsBox(e) {
    return this.intersectBox(e, on) !== null;
  }
  /**
   * Intersects this ray with the given triangle, returning the intersection
   * point or `null` if there is no intersection.
   *
   * @param {Vector3} a - The first vertex of the triangle.
   * @param {Vector3} b - The second vertex of the triangle.
   * @param {Vector3} c - The third vertex of the triangle.
   * @param {boolean} backfaceCulling - Whether to use backface culling or not.
   * @param {Vector3} target - The target vector that is used to store the method's result.
   * @return {?Vector3} The intersection point.
   */
  intersectTriangle(e, t, i, n, s) {
    Ac.subVectors(t, e), Na.subVectors(i, e), Cc.crossVectors(Ac, Na);
    let a = this.direction.dot(Cc), o;
    if (a > 0) {
      if (n) return null;
      o = 1;
    } else if (a < 0)
      o = -1, a = -a;
    else
      return null;
    Sn.subVectors(this.origin, e);
    const l = o * this.direction.dot(Na.crossVectors(Sn, Na));
    if (l < 0)
      return null;
    const c = o * this.direction.dot(Ac.cross(Sn));
    if (c < 0 || l + c > a)
      return null;
    const h = -o * Sn.dot(Cc);
    return h < 0 ? null : this.at(h / a, s);
  }
  /**
   * Transforms this ray with the given 4x4 transformation matrix.
   *
   * @param {Matrix4} matrix4 - The transformation matrix.
   * @return {Ray} A reference to this ray.
   */
  applyMatrix4(e) {
    return this.origin.applyMatrix4(e), this.direction.transformDirection(e), this;
  }
  /**
   * Returns `true` if this ray is equal with the given one.
   *
   * @param {Ray} ray - The ray to test for equality.
   * @return {boolean} Whether this ray is equal with the given one.
   */
  equals(e) {
    return e.origin.equals(this.origin) && e.direction.equals(this.direction);
  }
  /**
   * Returns a new ray with copied values from this instance.
   *
   * @return {Ray} A clone of this instance.
   */
  clone() {
    return new this.constructor().copy(this);
  }
}
class Ne {
  /**
   * Constructs a new 4x4 matrix. The arguments are supposed to be
   * in row-major order. If no arguments are provided, the constructor
   * initializes the matrix as an identity matrix.
   *
   * @param {number} [n11] - 1-1 matrix element.
   * @param {number} [n12] - 1-2 matrix element.
   * @param {number} [n13] - 1-3 matrix element.
   * @param {number} [n14] - 1-4 matrix element.
   * @param {number} [n21] - 2-1 matrix element.
   * @param {number} [n22] - 2-2 matrix element.
   * @param {number} [n23] - 2-3 matrix element.
   * @param {number} [n24] - 2-4 matrix element.
   * @param {number} [n31] - 3-1 matrix element.
   * @param {number} [n32] - 3-2 matrix element.
   * @param {number} [n33] - 3-3 matrix element.
   * @param {number} [n34] - 3-4 matrix element.
   * @param {number} [n41] - 4-1 matrix element.
   * @param {number} [n42] - 4-2 matrix element.
   * @param {number} [n43] - 4-3 matrix element.
   * @param {number} [n44] - 4-4 matrix element.
   */
  constructor(e, t, i, n, s, a, o, l, c, h, d, u, p, m, _, g) {
    Ne.prototype.isMatrix4 = !0, this.elements = [
      1,
      0,
      0,
      0,
      0,
      1,
      0,
      0,
      0,
      0,
      1,
      0,
      0,
      0,
      0,
      1
    ], e !== void 0 && this.set(e, t, i, n, s, a, o, l, c, h, d, u, p, m, _, g);
  }
  /**
   * Sets the elements of the matrix.The arguments are supposed to be
   * in row-major order.
   *
   * @param {number} [n11] - 1-1 matrix element.
   * @param {number} [n12] - 1-2 matrix element.
   * @param {number} [n13] - 1-3 matrix element.
   * @param {number} [n14] - 1-4 matrix element.
   * @param {number} [n21] - 2-1 matrix element.
   * @param {number} [n22] - 2-2 matrix element.
   * @param {number} [n23] - 2-3 matrix element.
   * @param {number} [n24] - 2-4 matrix element.
   * @param {number} [n31] - 3-1 matrix element.
   * @param {number} [n32] - 3-2 matrix element.
   * @param {number} [n33] - 3-3 matrix element.
   * @param {number} [n34] - 3-4 matrix element.
   * @param {number} [n41] - 4-1 matrix element.
   * @param {number} [n42] - 4-2 matrix element.
   * @param {number} [n43] - 4-3 matrix element.
   * @param {number} [n44] - 4-4 matrix element.
   * @return {Matrix4} A reference to this matrix.
   */
  set(e, t, i, n, s, a, o, l, c, h, d, u, p, m, _, g) {
    const f = this.elements;
    return f[0] = e, f[4] = t, f[8] = i, f[12] = n, f[1] = s, f[5] = a, f[9] = o, f[13] = l, f[2] = c, f[6] = h, f[10] = d, f[14] = u, f[3] = p, f[7] = m, f[11] = _, f[15] = g, this;
  }
  /**
   * Sets this matrix to the 4x4 identity matrix.
   *
   * @return {Matrix4} A reference to this matrix.
   */
  identity() {
    return this.set(
      1,
      0,
      0,
      0,
      0,
      1,
      0,
      0,
      0,
      0,
      1,
      0,
      0,
      0,
      0,
      1
    ), this;
  }
  /**
   * Returns a matrix with copied values from this instance.
   *
   * @return {Matrix4} A clone of this instance.
   */
  clone() {
    return new Ne().fromArray(this.elements);
  }
  /**
   * Copies the values of the given matrix to this instance.
   *
   * @param {Matrix4} m - The matrix to copy.
   * @return {Matrix4} A reference to this matrix.
   */
  copy(e) {
    const t = this.elements, i = e.elements;
    return t[0] = i[0], t[1] = i[1], t[2] = i[2], t[3] = i[3], t[4] = i[4], t[5] = i[5], t[6] = i[6], t[7] = i[7], t[8] = i[8], t[9] = i[9], t[10] = i[10], t[11] = i[11], t[12] = i[12], t[13] = i[13], t[14] = i[14], t[15] = i[15], this;
  }
  /**
   * Copies the translation component of the given matrix
   * into this matrix's translation component.
   *
   * @param {Matrix4} m - The matrix to copy the translation component.
   * @return {Matrix4} A reference to this matrix.
   */
  copyPosition(e) {
    const t = this.elements, i = e.elements;
    return t[12] = i[12], t[13] = i[13], t[14] = i[14], this;
  }
  /**
   * Set the upper 3x3 elements of this matrix to the values of given 3x3 matrix.
   *
   * @param {Matrix3} m - The 3x3 matrix.
   * @return {Matrix4} A reference to this matrix.
   */
  setFromMatrix3(e) {
    const t = e.elements;
    return this.set(
      t[0],
      t[3],
      t[6],
      0,
      t[1],
      t[4],
      t[7],
      0,
      t[2],
      t[5],
      t[8],
      0,
      0,
      0,
      0,
      1
    ), this;
  }
  /**
   * Extracts the basis of this matrix into the three axis vectors provided.
   *
   * @param {Vector3} xAxis - The basis's x axis.
   * @param {Vector3} yAxis - The basis's y axis.
   * @param {Vector3} zAxis - The basis's z axis.
   * @return {Matrix4} A reference to this matrix.
   */
  extractBasis(e, t, i) {
    return e.setFromMatrixColumn(this, 0), t.setFromMatrixColumn(this, 1), i.setFromMatrixColumn(this, 2), this;
  }
  /**
   * Sets the given basis vectors to this matrix.
   *
   * @param {Vector3} xAxis - The basis's x axis.
   * @param {Vector3} yAxis - The basis's y axis.
   * @param {Vector3} zAxis - The basis's z axis.
   * @return {Matrix4} A reference to this matrix.
   */
  makeBasis(e, t, i) {
    return this.set(
      e.x,
      t.x,
      i.x,
      0,
      e.y,
      t.y,
      i.y,
      0,
      e.z,
      t.z,
      i.z,
      0,
      0,
      0,
      0,
      1
    ), this;
  }
  /**
   * Extracts the rotation component of the given matrix
   * into this matrix's rotation component.
   *
   * Note: This method does not support reflection matrices.
   *
   * @param {Matrix4} m - The matrix.
   * @return {Matrix4} A reference to this matrix.
   */
  extractRotation(e) {
    const t = this.elements, i = e.elements, n = 1 / Ns.setFromMatrixColumn(e, 0).length(), s = 1 / Ns.setFromMatrixColumn(e, 1).length(), a = 1 / Ns.setFromMatrixColumn(e, 2).length();
    return t[0] = i[0] * n, t[1] = i[1] * n, t[2] = i[2] * n, t[3] = 0, t[4] = i[4] * s, t[5] = i[5] * s, t[6] = i[6] * s, t[7] = 0, t[8] = i[8] * a, t[9] = i[9] * a, t[10] = i[10] * a, t[11] = 0, t[12] = 0, t[13] = 0, t[14] = 0, t[15] = 1, this;
  }
  /**
   * Sets the rotation component (the upper left 3x3 matrix) of this matrix to
   * the rotation specified by the given Euler angles. The rest of
   * the matrix is set to the identity. Depending on the {@link Euler#order},
   * there are six possible outcomes. See [this page]{@link https://en.wikipedia.org/wiki/Euler_angles#Rotation_matrix}
   * for a complete list.
   *
   * @param {Euler} euler - The Euler angles.
   * @return {Matrix4} A reference to this matrix.
   */
  makeRotationFromEuler(e) {
    const t = this.elements, i = e.x, n = e.y, s = e.z, a = Math.cos(i), o = Math.sin(i), l = Math.cos(n), c = Math.sin(n), h = Math.cos(s), d = Math.sin(s);
    if (e.order === "XYZ") {
      const u = a * h, p = a * d, m = o * h, _ = o * d;
      t[0] = l * h, t[4] = -l * d, t[8] = c, t[1] = p + m * c, t[5] = u - _ * c, t[9] = -o * l, t[2] = _ - u * c, t[6] = m + p * c, t[10] = a * l;
    } else if (e.order === "YXZ") {
      const u = l * h, p = l * d, m = c * h, _ = c * d;
      t[0] = u + _ * o, t[4] = m * o - p, t[8] = a * c, t[1] = a * d, t[5] = a * h, t[9] = -o, t[2] = p * o - m, t[6] = _ + u * o, t[10] = a * l;
    } else if (e.order === "ZXY") {
      const u = l * h, p = l * d, m = c * h, _ = c * d;
      t[0] = u - _ * o, t[4] = -a * d, t[8] = m + p * o, t[1] = p + m * o, t[5] = a * h, t[9] = _ - u * o, t[2] = -a * c, t[6] = o, t[10] = a * l;
    } else if (e.order === "ZYX") {
      const u = a * h, p = a * d, m = o * h, _ = o * d;
      t[0] = l * h, t[4] = m * c - p, t[8] = u * c + _, t[1] = l * d, t[5] = _ * c + u, t[9] = p * c - m, t[2] = -c, t[6] = o * l, t[10] = a * l;
    } else if (e.order === "YZX") {
      const u = a * l, p = a * c, m = o * l, _ = o * c;
      t[0] = l * h, t[4] = _ - u * d, t[8] = m * d + p, t[1] = d, t[5] = a * h, t[9] = -o * h, t[2] = -c * h, t[6] = p * d + m, t[10] = u - _ * d;
    } else if (e.order === "XZY") {
      const u = a * l, p = a * c, m = o * l, _ = o * c;
      t[0] = l * h, t[4] = -d, t[8] = c * h, t[1] = u * d + _, t[5] = a * h, t[9] = p * d - m, t[2] = m * d - p, t[6] = o * h, t[10] = _ * d + u;
    }
    return t[3] = 0, t[7] = 0, t[11] = 0, t[12] = 0, t[13] = 0, t[14] = 0, t[15] = 1, this;
  }
  /**
   * Sets the rotation component of this matrix to the rotation specified by
   * the given Quaternion as outlined [here]{@link https://en.wikipedia.org/wiki/Rotation_matrix#Quaternion}
   * The rest of the matrix is set to the identity.
   *
   * @param {Quaternion} q - The Quaternion.
   * @return {Matrix4} A reference to this matrix.
   */
  makeRotationFromQuaternion(e) {
    return this.compose(z_, e, H_);
  }
  /**
   * Sets the rotation component of the transformation matrix, looking from `eye` towards
   * `target`, and oriented by the up-direction.
   *
   * @param {Vector3} eye - The eye vector.
   * @param {Vector3} target - The target vector.
   * @param {Vector3} up - The up vector.
   * @return {Matrix4} A reference to this matrix.
   */
  lookAt(e, t, i) {
    const n = this.elements;
    return vi.subVectors(e, t), vi.lengthSq() === 0 && (vi.z = 1), vi.normalize(), Mn.crossVectors(i, vi), Mn.lengthSq() === 0 && (Math.abs(i.z) === 1 ? vi.x += 1e-4 : vi.z += 1e-4, vi.normalize(), Mn.crossVectors(i, vi)), Mn.normalize(), Ua.crossVectors(vi, Mn), n[0] = Mn.x, n[4] = Ua.x, n[8] = vi.x, n[1] = Mn.y, n[5] = Ua.y, n[9] = vi.y, n[2] = Mn.z, n[6] = Ua.z, n[10] = vi.z, this;
  }
  /**
   * Post-multiplies this matrix by the given 4x4 matrix.
   *
   * @param {Matrix4} m - The matrix to multiply with.
   * @return {Matrix4} A reference to this matrix.
   */
  multiply(e) {
    return this.multiplyMatrices(this, e);
  }
  /**
   * Pre-multiplies this matrix by the given 4x4 matrix.
   *
   * @param {Matrix4} m - The matrix to multiply with.
   * @return {Matrix4} A reference to this matrix.
   */
  premultiply(e) {
    return this.multiplyMatrices(e, this);
  }
  /**
   * Multiples the given 4x4 matrices and stores the result
   * in this matrix.
   *
   * @param {Matrix4} a - The first matrix.
   * @param {Matrix4} b - The second matrix.
   * @return {Matrix4} A reference to this matrix.
   */
  multiplyMatrices(e, t) {
    const i = e.elements, n = t.elements, s = this.elements, a = i[0], o = i[4], l = i[8], c = i[12], h = i[1], d = i[5], u = i[9], p = i[13], m = i[2], _ = i[6], g = i[10], f = i[14], v = i[3], x = i[7], y = i[11], A = i[15], S = n[0], C = n[4], P = n[8], E = n[12], w = n[1], L = n[5], N = n[9], B = n[13], W = n[2], Z = n[6], X = n[10], ie = n[14], G = n[3], he = n[7], me = n[11], Se = n[15];
    return s[0] = a * S + o * w + l * W + c * G, s[4] = a * C + o * L + l * Z + c * he, s[8] = a * P + o * N + l * X + c * me, s[12] = a * E + o * B + l * ie + c * Se, s[1] = h * S + d * w + u * W + p * G, s[5] = h * C + d * L + u * Z + p * he, s[9] = h * P + d * N + u * X + p * me, s[13] = h * E + d * B + u * ie + p * Se, s[2] = m * S + _ * w + g * W + f * G, s[6] = m * C + _ * L + g * Z + f * he, s[10] = m * P + _ * N + g * X + f * me, s[14] = m * E + _ * B + g * ie + f * Se, s[3] = v * S + x * w + y * W + A * G, s[7] = v * C + x * L + y * Z + A * he, s[11] = v * P + x * N + y * X + A * me, s[15] = v * E + x * B + y * ie + A * Se, this;
  }
  /**
   * Multiplies every component of the matrix by the given scalar.
   *
   * @param {number} s - The scalar.
   * @return {Matrix4} A reference to this matrix.
   */
  multiplyScalar(e) {
    const t = this.elements;
    return t[0] *= e, t[4] *= e, t[8] *= e, t[12] *= e, t[1] *= e, t[5] *= e, t[9] *= e, t[13] *= e, t[2] *= e, t[6] *= e, t[10] *= e, t[14] *= e, t[3] *= e, t[7] *= e, t[11] *= e, t[15] *= e, this;
  }
  /**
   * Computes and returns the determinant of this matrix.
   *
   * Based on the method outlined [here]{@link http://www.euclideanspace.com/maths/algebra/matrix/functions/inverse/fourD/index.html}.
   *
   * @return {number} The determinant.
   */
  determinant() {
    const e = this.elements, t = e[0], i = e[4], n = e[8], s = e[12], a = e[1], o = e[5], l = e[9], c = e[13], h = e[2], d = e[6], u = e[10], p = e[14], m = e[3], _ = e[7], g = e[11], f = e[15];
    return m * (+s * l * d - n * c * d - s * o * u + i * c * u + n * o * p - i * l * p) + _ * (+t * l * p - t * c * u + s * a * u - n * a * p + n * c * h - s * l * h) + g * (+t * c * d - t * o * p - s * a * d + i * a * p + s * o * h - i * c * h) + f * (-n * o * h - t * l * d + t * o * u + n * a * d - i * a * u + i * l * h);
  }
  /**
   * Transposes this matrix in place.
   *
   * @return {Matrix4} A reference to this matrix.
   */
  transpose() {
    const e = this.elements;
    let t;
    return t = e[1], e[1] = e[4], e[4] = t, t = e[2], e[2] = e[8], e[8] = t, t = e[6], e[6] = e[9], e[9] = t, t = e[3], e[3] = e[12], e[12] = t, t = e[7], e[7] = e[13], e[13] = t, t = e[11], e[11] = e[14], e[14] = t, this;
  }
  /**
   * Sets the position component for this matrix from the given vector,
   * without affecting the rest of the matrix.
   *
   * @param {number|Vector3} x - The x component of the vector or alternatively the vector object.
   * @param {number} y - The y component of the vector.
   * @param {number} z - The z component of the vector.
   * @return {Matrix4} A reference to this matrix.
   */
  setPosition(e, t, i) {
    const n = this.elements;
    return e.isVector3 ? (n[12] = e.x, n[13] = e.y, n[14] = e.z) : (n[12] = e, n[13] = t, n[14] = i), this;
  }
  /**
   * Inverts this matrix, using the [analytic method]{@link https://en.wikipedia.org/wiki/Invertible_matrix#Analytic_solution}.
   * You can not invert with a determinant of zero. If you attempt this, the method produces
   * a zero matrix instead.
   *
   * @return {Matrix4} A reference to this matrix.
   */
  invert() {
    const e = this.elements, t = e[0], i = e[1], n = e[2], s = e[3], a = e[4], o = e[5], l = e[6], c = e[7], h = e[8], d = e[9], u = e[10], p = e[11], m = e[12], _ = e[13], g = e[14], f = e[15], v = d * g * c - _ * u * c + _ * l * p - o * g * p - d * l * f + o * u * f, x = m * u * c - h * g * c - m * l * p + a * g * p + h * l * f - a * u * f, y = h * _ * c - m * d * c + m * o * p - a * _ * p - h * o * f + a * d * f, A = m * d * l - h * _ * l - m * o * u + a * _ * u + h * o * g - a * d * g, S = t * v + i * x + n * y + s * A;
    if (S === 0) return this.set(0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0);
    const C = 1 / S;
    return e[0] = v * C, e[1] = (_ * u * s - d * g * s - _ * n * p + i * g * p + d * n * f - i * u * f) * C, e[2] = (o * g * s - _ * l * s + _ * n * c - i * g * c - o * n * f + i * l * f) * C, e[3] = (d * l * s - o * u * s - d * n * c + i * u * c + o * n * p - i * l * p) * C, e[4] = x * C, e[5] = (h * g * s - m * u * s + m * n * p - t * g * p - h * n * f + t * u * f) * C, e[6] = (m * l * s - a * g * s - m * n * c + t * g * c + a * n * f - t * l * f) * C, e[7] = (a * u * s - h * l * s + h * n * c - t * u * c - a * n * p + t * l * p) * C, e[8] = y * C, e[9] = (m * d * s - h * _ * s - m * i * p + t * _ * p + h * i * f - t * d * f) * C, e[10] = (a * _ * s - m * o * s + m * i * c - t * _ * c - a * i * f + t * o * f) * C, e[11] = (h * o * s - a * d * s - h * i * c + t * d * c + a * i * p - t * o * p) * C, e[12] = A * C, e[13] = (h * _ * n - m * d * n + m * i * u - t * _ * u - h * i * g + t * d * g) * C, e[14] = (m * o * n - a * _ * n - m * i * l + t * _ * l + a * i * g - t * o * g) * C, e[15] = (a * d * n - h * o * n + h * i * l - t * d * l - a * i * u + t * o * u) * C, this;
  }
  /**
   * Multiplies the columns of this matrix by the given vector.
   *
   * @param {Vector3} v - The scale vector.
   * @return {Matrix4} A reference to this matrix.
   */
  scale(e) {
    const t = this.elements, i = e.x, n = e.y, s = e.z;
    return t[0] *= i, t[4] *= n, t[8] *= s, t[1] *= i, t[5] *= n, t[9] *= s, t[2] *= i, t[6] *= n, t[10] *= s, t[3] *= i, t[7] *= n, t[11] *= s, this;
  }
  /**
   * Gets the maximum scale value of the three axes.
   *
   * @return {number} The maximum scale.
   */
  getMaxScaleOnAxis() {
    const e = this.elements, t = e[0] * e[0] + e[1] * e[1] + e[2] * e[2], i = e[4] * e[4] + e[5] * e[5] + e[6] * e[6], n = e[8] * e[8] + e[9] * e[9] + e[10] * e[10];
    return Math.sqrt(Math.max(t, i, n));
  }
  /**
   * Sets this matrix as a translation transform from the given vector.
   *
   * @param {number|Vector3} x - The amount to translate in the X axis or alternatively a translation vector.
   * @param {number} y - The amount to translate in the Y axis.
   * @param {number} z - The amount to translate in the z axis.
   * @return {Matrix4} A reference to this matrix.
   */
  makeTranslation(e, t, i) {
    return e.isVector3 ? this.set(
      1,
      0,
      0,
      e.x,
      0,
      1,
      0,
      e.y,
      0,
      0,
      1,
      e.z,
      0,
      0,
      0,
      1
    ) : this.set(
      1,
      0,
      0,
      e,
      0,
      1,
      0,
      t,
      0,
      0,
      1,
      i,
      0,
      0,
      0,
      1
    ), this;
  }
  /**
   * Sets this matrix as a rotational transformation around the X axis by
   * the given angle.
   *
   * @param {number} theta - The rotation in radians.
   * @return {Matrix4} A reference to this matrix.
   */
  makeRotationX(e) {
    const t = Math.cos(e), i = Math.sin(e);
    return this.set(
      1,
      0,
      0,
      0,
      0,
      t,
      -i,
      0,
      0,
      i,
      t,
      0,
      0,
      0,
      0,
      1
    ), this;
  }
  /**
   * Sets this matrix as a rotational transformation around the Y axis by
   * the given angle.
   *
   * @param {number} theta - The rotation in radians.
   * @return {Matrix4} A reference to this matrix.
   */
  makeRotationY(e) {
    const t = Math.cos(e), i = Math.sin(e);
    return this.set(
      t,
      0,
      i,
      0,
      0,
      1,
      0,
      0,
      -i,
      0,
      t,
      0,
      0,
      0,
      0,
      1
    ), this;
  }
  /**
   * Sets this matrix as a rotational transformation around the Z axis by
   * the given angle.
   *
   * @param {number} theta - The rotation in radians.
   * @return {Matrix4} A reference to this matrix.
   */
  makeRotationZ(e) {
    const t = Math.cos(e), i = Math.sin(e);
    return this.set(
      t,
      -i,
      0,
      0,
      i,
      t,
      0,
      0,
      0,
      0,
      1,
      0,
      0,
      0,
      0,
      1
    ), this;
  }
  /**
   * Sets this matrix as a rotational transformation around the given axis by
   * the given angle.
   *
   * This is a somewhat controversial but mathematically sound alternative to
   * rotating via Quaternions. See the discussion [here]{@link https://www.gamedev.net/articles/programming/math-and-physics/do-we-really-need-quaternions-r1199}.
   *
   * @param {Vector3} axis - The normalized rotation axis.
   * @param {number} angle - The rotation in radians.
   * @return {Matrix4} A reference to this matrix.
   */
  makeRotationAxis(e, t) {
    const i = Math.cos(t), n = Math.sin(t), s = 1 - i, a = e.x, o = e.y, l = e.z, c = s * a, h = s * o;
    return this.set(
      c * a + i,
      c * o - n * l,
      c * l + n * o,
      0,
      c * o + n * l,
      h * o + i,
      h * l - n * a,
      0,
      c * l - n * o,
      h * l + n * a,
      s * l * l + i,
      0,
      0,
      0,
      0,
      1
    ), this;
  }
  /**
   * Sets this matrix as a scale transformation.
   *
   * @param {number} x - The amount to scale in the X axis.
   * @param {number} y - The amount to scale in the Y axis.
   * @param {number} z - The amount to scale in the Z axis.
   * @return {Matrix4} A reference to this matrix.
   */
  makeScale(e, t, i) {
    return this.set(
      e,
      0,
      0,
      0,
      0,
      t,
      0,
      0,
      0,
      0,
      i,
      0,
      0,
      0,
      0,
      1
    ), this;
  }
  /**
   * Sets this matrix as a shear transformation.
   *
   * @param {number} xy - The amount to shear X by Y.
   * @param {number} xz - The amount to shear X by Z.
   * @param {number} yx - The amount to shear Y by X.
   * @param {number} yz - The amount to shear Y by Z.
   * @param {number} zx - The amount to shear Z by X.
   * @param {number} zy - The amount to shear Z by Y.
   * @return {Matrix4} A reference to this matrix.
   */
  makeShear(e, t, i, n, s, a) {
    return this.set(
      1,
      i,
      s,
      0,
      e,
      1,
      a,
      0,
      t,
      n,
      1,
      0,
      0,
      0,
      0,
      1
    ), this;
  }
  /**
   * Sets this matrix to the transformation composed of the given position,
   * rotation (Quaternion) and scale.
   *
   * @param {Vector3} position - The position vector.
   * @param {Quaternion} quaternion - The rotation as a Quaternion.
   * @param {Vector3} scale - The scale vector.
   * @return {Matrix4} A reference to this matrix.
   */
  compose(e, t, i) {
    const n = this.elements, s = t._x, a = t._y, o = t._z, l = t._w, c = s + s, h = a + a, d = o + o, u = s * c, p = s * h, m = s * d, _ = a * h, g = a * d, f = o * d, v = l * c, x = l * h, y = l * d, A = i.x, S = i.y, C = i.z;
    return n[0] = (1 - (_ + f)) * A, n[1] = (p + y) * A, n[2] = (m - x) * A, n[3] = 0, n[4] = (p - y) * S, n[5] = (1 - (u + f)) * S, n[6] = (g + v) * S, n[7] = 0, n[8] = (m + x) * C, n[9] = (g - v) * C, n[10] = (1 - (u + _)) * C, n[11] = 0, n[12] = e.x, n[13] = e.y, n[14] = e.z, n[15] = 1, this;
  }
  /**
   * Decomposes this matrix into its position, rotation and scale components
   * and provides the result in the given objects.
   *
   * Note: Not all matrices are decomposable in this way. For example, if an
   * object has a non-uniformly scaled parent, then the object's world matrix
   * may not be decomposable, and this method may not be appropriate.
   *
   * @param {Vector3} position - The position vector.
   * @param {Quaternion} quaternion - The rotation as a Quaternion.
   * @param {Vector3} scale - The scale vector.
   * @return {Matrix4} A reference to this matrix.
   */
  decompose(e, t, i) {
    const n = this.elements;
    let s = Ns.set(n[0], n[1], n[2]).length();
    const a = Ns.set(n[4], n[5], n[6]).length(), o = Ns.set(n[8], n[9], n[10]).length();
    this.determinant() < 0 && (s = -s), e.x = n[12], e.y = n[13], e.z = n[14], Oi.copy(this);
    const c = 1 / s, h = 1 / a, d = 1 / o;
    return Oi.elements[0] *= c, Oi.elements[1] *= c, Oi.elements[2] *= c, Oi.elements[4] *= h, Oi.elements[5] *= h, Oi.elements[6] *= h, Oi.elements[8] *= d, Oi.elements[9] *= d, Oi.elements[10] *= d, t.setFromRotationMatrix(Oi), i.x = s, i.y = a, i.z = o, this;
  }
  /**
  	 * Creates a perspective projection matrix. This is used internally by
  	 * {@link PerspectiveCamera#updateProjectionMatrix}.
  
  	 * @param {number} left - Left boundary of the viewing frustum at the near plane.
  	 * @param {number} right - Right boundary of the viewing frustum at the near plane.
  	 * @param {number} top - Top boundary of the viewing frustum at the near plane.
  	 * @param {number} bottom - Bottom boundary of the viewing frustum at the near plane.
  	 * @param {number} near - The distance from the camera to the near plane.
  	 * @param {number} far - The distance from the camera to the far plane.
  	 * @param {(WebGLCoordinateSystem|WebGPUCoordinateSystem)} [coordinateSystem=WebGLCoordinateSystem] - The coordinate system.
  	 * @param {boolean} [reversedDepth=false] - Whether to use a reversed depth.
  	 * @return {Matrix4} A reference to this matrix.
  	 */
  makePerspective(e, t, i, n, s, a, o = wi, l = !1) {
    const c = this.elements, h = 2 * s / (t - e), d = 2 * s / (i - n), u = (t + e) / (t - e), p = (i + n) / (i - n);
    let m, _;
    if (l)
      m = s / (a - s), _ = a * s / (a - s);
    else if (o === wi)
      m = -(a + s) / (a - s), _ = -2 * a * s / (a - s);
    else if (o === pr)
      m = -a / (a - s), _ = -a * s / (a - s);
    else
      throw new Error("THREE.Matrix4.makePerspective(): Invalid coordinate system: " + o);
    return c[0] = h, c[4] = 0, c[8] = u, c[12] = 0, c[1] = 0, c[5] = d, c[9] = p, c[13] = 0, c[2] = 0, c[6] = 0, c[10] = m, c[14] = _, c[3] = 0, c[7] = 0, c[11] = -1, c[15] = 0, this;
  }
  /**
  	 * Creates a orthographic projection matrix. This is used internally by
  	 * {@link OrthographicCamera#updateProjectionMatrix}.
  
  	 * @param {number} left - Left boundary of the viewing frustum at the near plane.
  	 * @param {number} right - Right boundary of the viewing frustum at the near plane.
  	 * @param {number} top - Top boundary of the viewing frustum at the near plane.
  	 * @param {number} bottom - Bottom boundary of the viewing frustum at the near plane.
  	 * @param {number} near - The distance from the camera to the near plane.
  	 * @param {number} far - The distance from the camera to the far plane.
  	 * @param {(WebGLCoordinateSystem|WebGPUCoordinateSystem)} [coordinateSystem=WebGLCoordinateSystem] - The coordinate system.
  	 * @param {boolean} [reversedDepth=false] - Whether to use a reversed depth.
  	 * @return {Matrix4} A reference to this matrix.
  	 */
  makeOrthographic(e, t, i, n, s, a, o = wi, l = !1) {
    const c = this.elements, h = 2 / (t - e), d = 2 / (i - n), u = -(t + e) / (t - e), p = -(i + n) / (i - n);
    let m, _;
    if (l)
      m = 1 / (a - s), _ = a / (a - s);
    else if (o === wi)
      m = -2 / (a - s), _ = -(a + s) / (a - s);
    else if (o === pr)
      m = -1 / (a - s), _ = -s / (a - s);
    else
      throw new Error("THREE.Matrix4.makeOrthographic(): Invalid coordinate system: " + o);
    return c[0] = h, c[4] = 0, c[8] = 0, c[12] = u, c[1] = 0, c[5] = d, c[9] = 0, c[13] = p, c[2] = 0, c[6] = 0, c[10] = m, c[14] = _, c[3] = 0, c[7] = 0, c[11] = 0, c[15] = 1, this;
  }
  /**
   * Returns `true` if this matrix is equal with the given one.
   *
   * @param {Matrix4} matrix - The matrix to test for equality.
   * @return {boolean} Whether this matrix is equal with the given one.
   */
  equals(e) {
    const t = this.elements, i = e.elements;
    for (let n = 0; n < 16; n++)
      if (t[n] !== i[n]) return !1;
    return !0;
  }
  /**
   * Sets the elements of the matrix from the given array.
   *
   * @param {Array<number>} array - The matrix elements in column-major order.
   * @param {number} [offset=0] - Index of the first element in the array.
   * @return {Matrix4} A reference to this matrix.
   */
  fromArray(e, t = 0) {
    for (let i = 0; i < 16; i++)
      this.elements[i] = e[i + t];
    return this;
  }
  /**
   * Writes the elements of this matrix to the given array. If no array is provided,
   * the method returns a new instance.
   *
   * @param {Array<number>} [array=[]] - The target array holding the matrix elements in column-major order.
   * @param {number} [offset=0] - Index of the first element in the array.
   * @return {Array<number>} The matrix elements in column-major order.
   */
  toArray(e = [], t = 0) {
    const i = this.elements;
    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], e;
  }
}
const Ns = /* @__PURE__ */ new b(), Oi = /* @__PURE__ */ new Ne(), z_ = /* @__PURE__ */ new b(0, 0, 0), H_ = /* @__PURE__ */ new b(1, 1, 1), Mn = /* @__PURE__ */ new b(), Ua = /* @__PURE__ */ new b(), vi = /* @__PURE__ */ new b(), au = /* @__PURE__ */ new Ne(), ou = /* @__PURE__ */ new ot();
class Ai {
  /**
   * Constructs a new euler instance.
   *
   * @param {number} [x=0] - The angle of the x axis in radians.
   * @param {number} [y=0] - The angle of the y axis in radians.
   * @param {number} [z=0] - The angle of the z axis in radians.
   * @param {string} [order=Euler.DEFAULT_ORDER] - A string representing the order that the rotations are applied.
   */
  constructor(e = 0, t = 0, i = 0, n = Ai.DEFAULT_ORDER) {
    this.isEuler = !0, this._x = e, this._y = t, this._z = i, this._order = n;
  }
  /**
   * The angle of the x axis in radians.
   *
   * @type {number}
   * @default 0
   */
  get x() {
    return this._x;
  }
  set x(e) {
    this._x = e, this._onChangeCallback();
  }
  /**
   * The angle of the y axis in radians.
   *
   * @type {number}
   * @default 0
   */
  get y() {
    return this._y;
  }
  set y(e) {
    this._y = e, this._onChangeCallback();
  }
  /**
   * The angle of the z axis in radians.
   *
   * @type {number}
   * @default 0
   */
  get z() {
    return this._z;
  }
  set z(e) {
    this._z = e, this._onChangeCallback();
  }
  /**
   * A string representing the order that the rotations are applied.
   *
   * @type {string}
   * @default 'XYZ'
   */
  get order() {
    return this._order;
  }
  set order(e) {
    this._order = e, this._onChangeCallback();
  }
  /**
   * Sets the Euler components.
   *
   * @param {number} x - The angle of the x axis in radians.
   * @param {number} y - The angle of the y axis in radians.
   * @param {number} z - The angle of the z axis in radians.
   * @param {string} [order] - A string representing the order that the rotations are applied.
   * @return {Euler} A reference to this Euler instance.
   */
  set(e, t, i, n = this._order) {
    return this._x = e, this._y = t, this._z = i, this._order = n, this._onChangeCallback(), this;
  }
  /**
   * Returns a new Euler instance with copied values from this instance.
   *
   * @return {Euler} A clone of this instance.
   */
  clone() {
    return new this.constructor(this._x, this._y, this._z, this._order);
  }
  /**
   * Copies the values of the given Euler instance to this instance.
   *
   * @param {Euler} euler - The Euler instance to copy.
   * @return {Euler} A reference to this Euler instance.
   */
  copy(e) {
    return this._x = e._x, this._y = e._y, this._z = e._z, this._order = e._order, this._onChangeCallback(), this;
  }
  /**
   * Sets the angles of this Euler instance from a pure rotation matrix.
   *
   * @param {Matrix4} m - A 4x4 matrix of which the upper 3x3 of matrix is a pure rotation matrix (i.e. unscaled).
   * @param {string} [order] - A string representing the order that the rotations are applied.
   * @param {boolean} [update=true] - Whether the internal `onChange` callback should be executed or not.
   * @return {Euler} A reference to this Euler instance.
   */
  setFromRotationMatrix(e, t = this._order, i = !0) {
    const n = e.elements, s = n[0], a = n[4], o = n[8], l = n[1], c = n[5], h = n[9], d = n[2], u = n[6], p = n[10];
    switch (t) {
      case "XYZ":
        this._y = Math.asin(Fe(o, -1, 1)), Math.abs(o) < 0.9999999 ? (this._x = Math.atan2(-h, p), this._z = Math.atan2(-a, s)) : (this._x = Math.atan2(u, c), this._z = 0);
        break;
      case "YXZ":
        this._x = Math.asin(-Fe(h, -1, 1)), Math.abs(h) < 0.9999999 ? (this._y = Math.atan2(o, p), this._z = Math.atan2(l, c)) : (this._y = Math.atan2(-d, s), this._z = 0);
        break;
      case "ZXY":
        this._x = Math.asin(Fe(u, -1, 1)), Math.abs(u) < 0.9999999 ? (this._y = Math.atan2(-d, p), this._z = Math.atan2(-a, c)) : (this._y = 0, this._z = Math.atan2(l, s));
        break;
      case "ZYX":
        this._y = Math.asin(-Fe(d, -1, 1)), Math.abs(d) < 0.9999999 ? (this._x = Math.atan2(u, p), this._z = Math.atan2(l, s)) : (this._x = 0, this._z = Math.atan2(-a, c));
        break;
      case "YZX":
        this._z = Math.asin(Fe(l, -1, 1)), Math.abs(l) < 0.9999999 ? (this._x = Math.atan2(-h, c), this._y = Math.atan2(-d, s)) : (this._x = 0, this._y = Math.atan2(o, p));
        break;
      case "XZY":
        this._z = Math.asin(-Fe(a, -1, 1)), Math.abs(a) < 0.9999999 ? (this._x = Math.atan2(u, c), this._y = Math.atan2(o, s)) : (this._x = Math.atan2(-h, p), this._y = 0);
        break;
      default:
        console.warn("THREE.Euler: .setFromRotationMatrix() encountered an unknown order: " + t);
    }
    return this._order = t, i === !0 && this._onChangeCallback(), this;
  }
  /**
   * Sets the angles of this Euler instance from a normalized quaternion.
   *
   * @param {Quaternion} q - A normalized Quaternion.
   * @param {string} [order] - A string representing the order that the rotations are applied.
   * @param {boolean} [update=true] - Whether the internal `onChange` callback should be executed or not.
   * @return {Euler} A reference to this Euler instance.
   */
  setFromQuaternion(e, t, i) {
    return au.makeRotationFromQuaternion(e), this.setFromRotationMatrix(au, t, i);
  }
  /**
   * Sets the angles of this Euler instance from the given vector.
   *
   * @param {Vector3} v - The vector.
   * @param {string} [order] - A string representing the order that the rotations are applied.
   * @return {Euler} A reference to this Euler instance.
   */
  setFromVector3(e, t = this._order) {
    return this.set(e.x, e.y, e.z, t);
  }
  /**
   * Resets the euler angle with a new order by creating a quaternion from this
   * euler angle and then setting this euler angle with the quaternion and the
   * new order.
   *
   * Warning: This discards revolution information.
   *
   * @param {string} [newOrder] - A string representing the new order that the rotations are applied.
   * @return {Euler} A reference to this Euler instance.
   */
  reorder(e) {
    return ou.setFromEuler(this), this.setFromQuaternion(ou, e);
  }
  /**
   * Returns `true` if this Euler instance is equal with the given one.
   *
   * @param {Euler} euler - The Euler instance to test for equality.
   * @return {boolean} Whether this Euler instance is equal with the given one.
   */
  equals(e) {
    return e._x === this._x && e._y === this._y && e._z === this._z && e._order === this._order;
  }
  /**
   * Sets this Euler instance's components to values from the given array. The first three
   * entries of the array are assign to the x,y and z components. An optional fourth entry
   * defines the Euler order.
   *
   * @param {Array<number,number,number,?string>} array - An array holding the Euler component values.
   * @return {Euler} A reference to this Euler instance.
   */
  fromArray(e) {
    return this._x = e[0], this._y = e[1], this._z = e[2], e[3] !== void 0 && (this._order = e[3]), this._onChangeCallback(), this;
  }
  /**
   * Writes the components of this Euler instance to the given array. If no array is provided,
   * the method returns a new instance.
   *
   * @param {Array<number,number,number,string>} [array=[]] - The target array holding the Euler components.
   * @param {number} [offset=0] - Index of the first element in the array.
   * @return {Array<number,number,number,string>} The Euler components.
   */
  toArray(e = [], t = 0) {
    return e[t] = this._x, e[t + 1] = this._y, e[t + 2] = this._z, e[t + 3] = this._order, e;
  }
  _onChange(e) {
    return this._onChangeCallback = e, this;
  }
  _onChangeCallback() {
  }
  *[Symbol.iterator]() {
    yield this._x, yield this._y, yield this._z, yield this._order;
  }
}
Ai.DEFAULT_ORDER = "XYZ";
class ql {
  /**
   * Constructs a new layers instance, with membership
   * initially set to layer `0`.
   */
  constructor() {
    this.mask = 1;
  }
  /**
   * Sets membership to the given layer, and remove membership all other layers.
   *
   * @param {number} layer - The layer to set.
   */
  set(e) {
    this.mask = (1 << e | 0) >>> 0;
  }
  /**
   * Adds membership of the given layer.
   *
   * @param {number} layer - The layer to enable.
   */
  enable(e) {
    this.mask |= 1 << e | 0;
  }
  /**
   * Adds membership to all layers.
   */
  enableAll() {
    this.mask = -1;
  }
  /**
   * Toggles the membership of the given layer.
   *
   * @param {number} layer - The layer to toggle.
   */
  toggle(e) {
    this.mask ^= 1 << e | 0;
  }
  /**
   * Removes membership of the given layer.
   *
   * @param {number} layer - The layer to enable.
   */
  disable(e) {
    this.mask &= ~(1 << e | 0);
  }
  /**
   * Removes the membership from all layers.
   */
  disableAll() {
    this.mask = 0;
  }
  /**
   * Returns `true` if this and the given layers object have at least one
   * layer in common.
   *
   * @param {Layers} layers - The layers to test.
   * @return {boolean } Whether this and the given layers object have at least one layer in common or not.
   */
  test(e) {
    return (this.mask & e.mask) !== 0;
  }
  /**
   * Returns `true` if the given layer is enabled.
   *
   * @param {number} layer - The layer to test.
   * @return {boolean } Whether the given layer is enabled or not.
   */
  isEnabled(e) {
    return (this.mask & (1 << e | 0)) !== 0;
  }
}
let V_ = 0;
const lu = /* @__PURE__ */ new b(), Us = /* @__PURE__ */ new ot(), ln = /* @__PURE__ */ new Ne(), Oa = /* @__PURE__ */ new b(), Rr = /* @__PURE__ */ new b(), G_ = /* @__PURE__ */ new b(), W_ = /* @__PURE__ */ new ot(), cu = /* @__PURE__ */ new b(1, 0, 0), hu = /* @__PURE__ */ new b(0, 1, 0), du = /* @__PURE__ */ new b(0, 0, 1), uu = { type: "added" }, X_ = { type: "removed" }, Os = { type: "childadded", child: null }, Rc = { type: "childremoved", child: null };
class tt extends sn {
  /**
   * Constructs a new 3D object.
   */
  constructor() {
    super(), this.isObject3D = !0, Object.defineProperty(this, "id", { value: V_++ }), this.uuid = Ti(), this.name = "", this.type = "Object3D", this.parent = null, this.children = [], this.up = tt.DEFAULT_UP.clone();
    const e = new b(), t = new Ai(), i = new ot(), n = new b(1, 1, 1);
    function s() {
      i.setFromEuler(t, !1);
    }
    function a() {
      t.setFromQuaternion(i, void 0, !1);
    }
    t._onChange(s), i._onChange(a), Object.defineProperties(this, {
      /**
       * Represents the object's local position.
       *
       * @name Object3D#position
       * @type {Vector3}
       * @default (0,0,0)
       */
      position: {
        configurable: !0,
        enumerable: !0,
        value: e
      },
      /**
       * Represents the object's local rotation as Euler angles, in radians.
       *
       * @name Object3D#rotation
       * @type {Euler}
       * @default (0,0,0)
       */
      rotation: {
        configurable: !0,
        enumerable: !0,
        value: t
      },
      /**
       * Represents the object's local rotation as Quaternions.
       *
       * @name Object3D#quaternion
       * @type {Quaternion}
       */
      quaternion: {
        configurable: !0,
        enumerable: !0,
        value: i
      },
      /**
       * Represents the object's local scale.
       *
       * @name Object3D#scale
       * @type {Vector3}
       * @default (1,1,1)
       */
      scale: {
        configurable: !0,
        enumerable: !0,
        value: n
      },
      /**
       * Represents the object's model-view matrix.
       *
       * @name Object3D#modelViewMatrix
       * @type {Matrix4}
       */
      modelViewMatrix: {
        value: new Ne()
      },
      /**
       * Represents the object's normal matrix.
       *
       * @name Object3D#normalMatrix
       * @type {Matrix3}
       */
      normalMatrix: {
        value: new He()
      }
    }), this.matrix = new Ne(), this.matrixWorld = new Ne(), this.matrixAutoUpdate = tt.DEFAULT_MATRIX_AUTO_UPDATE, this.matrixWorldAutoUpdate = tt.DEFAULT_MATRIX_WORLD_AUTO_UPDATE, this.matrixWorldNeedsUpdate = !1, this.layers = new ql(), this.visible = !0, this.castShadow = !1, this.receiveShadow = !1, this.frustumCulled = !0, this.renderOrder = 0, this.animations = [], this.customDepthMaterial = void 0, this.customDistanceMaterial = void 0, this.userData = {};
  }
  /**
   * A callback that is executed immediately before a 3D object is rendered to a shadow map.
   *
   * @param {Renderer|WebGLRenderer} renderer - The renderer.
   * @param {Object3D} object - The 3D object.
   * @param {Camera} camera - The camera that is used to render the scene.
   * @param {Camera} shadowCamera - The shadow camera.
   * @param {BufferGeometry} geometry - The 3D object's geometry.
   * @param {Material} depthMaterial - The depth material.
   * @param {Object} group - The geometry group data.
   */
  onBeforeShadow() {
  }
  /**
   * A callback that is executed immediately after a 3D object is rendered to a shadow map.
   *
   * @param {Renderer|WebGLRenderer} renderer - The renderer.
   * @param {Object3D} object - The 3D object.
   * @param {Camera} camera - The camera that is used to render the scene.
   * @param {Camera} shadowCamera - The shadow camera.
   * @param {BufferGeometry} geometry - The 3D object's geometry.
   * @param {Material} depthMaterial - The depth material.
   * @param {Object} group - The geometry group data.
   */
  onAfterShadow() {
  }
  /**
   * A callback that is executed immediately before a 3D object is rendered.
   *
   * @param {Renderer|WebGLRenderer} renderer - The renderer.
   * @param {Object3D} object - The 3D object.
   * @param {Camera} camera - The camera that is used to render the scene.
   * @param {BufferGeometry} geometry - The 3D object's geometry.
   * @param {Material} material - The 3D object's material.
   * @param {Object} group - The geometry group data.
   */
  onBeforeRender() {
  }
  /**
   * A callback that is executed immediately after a 3D object is rendered.
   *
   * @param {Renderer|WebGLRenderer} renderer - The renderer.
   * @param {Object3D} object - The 3D object.
   * @param {Camera} camera - The camera that is used to render the scene.
   * @param {BufferGeometry} geometry - The 3D object's geometry.
   * @param {Material} material - The 3D object's material.
   * @param {Object} group - The geometry group data.
   */
  onAfterRender() {
  }
  /**
   * Applies the given transformation matrix to the object and updates the object's position,
   * rotation and scale.
   *
   * @param {Matrix4} matrix - The transformation matrix.
   */
  applyMatrix4(e) {
    this.matrixAutoUpdate && this.updateMatrix(), this.matrix.premultiply(e), this.matrix.decompose(this.position, this.quaternion, this.scale);
  }
  /**
   * Applies a rotation represented by given the quaternion to the 3D object.
   *
   * @param {Quaternion} q - The quaternion.
   * @return {Object3D} A reference to this instance.
   */
  applyQuaternion(e) {
    return this.quaternion.premultiply(e), this;
  }
  /**
   * Sets the given rotation represented as an axis/angle couple to the 3D object.
   *
   * @param {Vector3} axis - The (normalized) axis vector.
   * @param {number} angle - The angle in radians.
   */
  setRotationFromAxisAngle(e, t) {
    this.quaternion.setFromAxisAngle(e, t);
  }
  /**
   * Sets the given rotation represented as Euler angles to the 3D object.
   *
   * @param {Euler} euler - The Euler angles.
   */
  setRotationFromEuler(e) {
    this.quaternion.setFromEuler(e, !0);
  }
  /**
   * Sets the given rotation represented as rotation matrix to the 3D object.
   *
   * @param {Matrix4} m - Although a 4x4 matrix is expected, the upper 3x3 portion must be
   * a pure rotation matrix (i.e, unscaled).
   */
  setRotationFromMatrix(e) {
    this.quaternion.setFromRotationMatrix(e);
  }
  /**
   * Sets the given rotation represented as a Quaternion to the 3D object.
   *
   * @param {Quaternion} q - The Quaternion
   */
  setRotationFromQuaternion(e) {
    this.quaternion.copy(e);
  }
  /**
   * Rotates the 3D object along an axis in local space.
   *
   * @param {Vector3} axis - The (normalized) axis vector.
   * @param {number} angle - The angle in radians.
   * @return {Object3D} A reference to this instance.
   */
  rotateOnAxis(e, t) {
    return Us.setFromAxisAngle(e, t), this.quaternion.multiply(Us), this;
  }
  /**
   * Rotates the 3D object along an axis in world space.
   *
   * @param {Vector3} axis - The (normalized) axis vector.
   * @param {number} angle - The angle in radians.
   * @return {Object3D} A reference to this instance.
   */
  rotateOnWorldAxis(e, t) {
    return Us.setFromAxisAngle(e, t), this.quaternion.premultiply(Us), this;
  }
  /**
   * Rotates the 3D object around its X axis in local space.
   *
   * @param {number} angle - The angle in radians.
   * @return {Object3D} A reference to this instance.
   */
  rotateX(e) {
    return this.rotateOnAxis(cu, e);
  }
  /**
   * Rotates the 3D object around its Y axis in local space.
   *
   * @param {number} angle - The angle in radians.
   * @return {Object3D} A reference to this instance.
   */
  rotateY(e) {
    return this.rotateOnAxis(hu, e);
  }
  /**
   * Rotates the 3D object around its Z axis in local space.
   *
   * @param {number} angle - The angle in radians.
   * @return {Object3D} A reference to this instance.
   */
  rotateZ(e) {
    return this.rotateOnAxis(du, e);
  }
  /**
   * Translate the 3D object by a distance along the given axis in local space.
   *
   * @param {Vector3} axis - The (normalized) axis vector.
   * @param {number} distance - The distance in world units.
   * @return {Object3D} A reference to this instance.
   */
  translateOnAxis(e, t) {
    return lu.copy(e).applyQuaternion(this.quaternion), this.position.add(lu.multiplyScalar(t)), this;
  }
  /**
   * Translate the 3D object by a distance along its X-axis in local space.
   *
   * @param {number} distance - The distance in world units.
   * @return {Object3D} A reference to this instance.
   */
  translateX(e) {
    return this.translateOnAxis(cu, e);
  }
  /**
   * Translate the 3D object by a distance along its Y-axis in local space.
   *
   * @param {number} distance - The distance in world units.
   * @return {Object3D} A reference to this instance.
   */
  translateY(e) {
    return this.translateOnAxis(hu, e);
  }
  /**
   * Translate the 3D object by a distance along its Z-axis in local space.
   *
   * @param {number} distance - The distance in world units.
   * @return {Object3D} A reference to this instance.
   */
  translateZ(e) {
    return this.translateOnAxis(du, e);
  }
  /**
   * Converts the given vector from this 3D object's local space to world space.
   *
   * @param {Vector3} vector - The vector to convert.
   * @return {Vector3} The converted vector.
   */
  localToWorld(e) {
    return this.updateWorldMatrix(!0, !1), e.applyMatrix4(this.matrixWorld);
  }
  /**
   * Converts the given vector from this 3D object's word space to local space.
   *
   * @param {Vector3} vector - The vector to convert.
   * @return {Vector3} The converted vector.
   */
  worldToLocal(e) {
    return this.updateWorldMatrix(!0, !1), e.applyMatrix4(ln.copy(this.matrixWorld).invert());
  }
  /**
   * Rotates the object to face a point in world space.
   *
   * This method does not support objects having non-uniformly-scaled parent(s).
   *
   * @param {number|Vector3} x - The x coordinate in world space. Alternatively, a vector representing a position in world space
   * @param {number} [y] - The y coordinate in world space.
   * @param {number} [z] - The z coordinate in world space.
   */
  lookAt(e, t, i) {
    e.isVector3 ? Oa.copy(e) : Oa.set(e, t, i);
    const n = this.parent;
    this.updateWorldMatrix(!0, !1), Rr.setFromMatrixPosition(this.matrixWorld), this.isCamera || this.isLight ? ln.lookAt(Rr, Oa, this.up) : ln.lookAt(Oa, Rr, this.up), this.quaternion.setFromRotationMatrix(ln), n && (ln.extractRotation(n.matrixWorld), Us.setFromRotationMatrix(ln), this.quaternion.premultiply(Us.invert()));
  }
  /**
   * Adds the given 3D object as a child to this 3D object. An arbitrary number of
   * objects may be added. Any current parent on an object passed in here will be
   * removed, since an object can have at most one parent.
   *
   * @fires Object3D#added
   * @fires Object3D#childadded
   * @param {Object3D} object - The 3D object to add.
   * @return {Object3D} A reference to this instance.
   */
  add(e) {
    if (arguments.length > 1) {
      for (let t = 0; t < arguments.length; t++)
        this.add(arguments[t]);
      return this;
    }
    return e === this ? (console.error("THREE.Object3D.add: object can't be added as a child of itself.", e), this) : (e && e.isObject3D ? (e.removeFromParent(), e.parent = this, this.children.push(e), e.dispatchEvent(uu), Os.child = e, this.dispatchEvent(Os), Os.child = null) : console.error("THREE.Object3D.add: object not an instance of THREE.Object3D.", e), this);
  }
  /**
   * Removes the given 3D object as child from this 3D object.
   * An arbitrary number of objects may be removed.
   *
   * @fires Object3D#removed
   * @fires Object3D#childremoved
   * @param {Object3D} object - The 3D object to remove.
   * @return {Object3D} A reference to this instance.
   */
  remove(e) {
    if (arguments.length > 1) {
      for (let i = 0; i < arguments.length; i++)
        this.remove(arguments[i]);
      return this;
    }
    const t = this.children.indexOf(e);
    return t !== -1 && (e.parent = null, this.children.splice(t, 1), e.dispatchEvent(X_), Rc.child = e, this.dispatchEvent(Rc), Rc.child = null), this;
  }
  /**
   * Removes this 3D object from its current parent.
   *
   * @fires Object3D#removed
   * @fires Object3D#childremoved
   * @return {Object3D} A reference to this instance.
   */
  removeFromParent() {
    const e = this.parent;
    return e !== null && e.remove(this), this;
  }
  /**
   * Removes all child objects.
   *
   * @fires Object3D#removed
   * @fires Object3D#childremoved
   * @return {Object3D} A reference to this instance.
   */
  clear() {
    return this.remove(...this.children);
  }
  /**
   * Adds the given 3D object as a child of this 3D object, while maintaining the object's world
   * transform. This method does not support scene graphs having non-uniformly-scaled nodes(s).
   *
   * @fires Object3D#added
   * @fires Object3D#childadded
   * @param {Object3D} object - The 3D object to attach.
   * @return {Object3D} A reference to this instance.
   */
  attach(e) {
    return this.updateWorldMatrix(!0, !1), ln.copy(this.matrixWorld).invert(), e.parent !== null && (e.parent.updateWorldMatrix(!0, !1), ln.multiply(e.parent.matrixWorld)), e.applyMatrix4(ln), e.removeFromParent(), e.parent = this, this.children.push(e), e.updateWorldMatrix(!1, !0), e.dispatchEvent(uu), Os.child = e, this.dispatchEvent(Os), Os.child = null, this;
  }
  /**
   * Searches through the 3D object and its children, starting with the 3D object
   * itself, and returns the first with a matching ID.
   *
   * @param {number} id - The id.
   * @return {Object3D|undefined} The found 3D object. Returns `undefined` if no 3D object has been found.
   */
  getObjectById(e) {
    return this.getObjectByProperty("id", e);
  }
  /**
   * Searches through the 3D object and its children, starting with the 3D object
   * itself, and returns the first with a matching name.
   *
   * @param {string} name - The name.
   * @return {Object3D|undefined} The found 3D object. Returns `undefined` if no 3D object has been found.
   */
  getObjectByName(e) {
    return this.getObjectByProperty("name", e);
  }
  /**
   * Searches through the 3D object and its children, starting with the 3D object
   * itself, and returns the first with a matching property value.
   *
   * @param {string} name - The name of the property.
   * @param {any} value - The value.
   * @return {Object3D|undefined} The found 3D object. Returns `undefined` if no 3D object has been found.
   */
  getObjectByProperty(e, t) {
    if (this[e] === t) return this;
    for (let i = 0, n = this.children.length; i < n; i++) {
      const a = this.children[i].getObjectByProperty(e, t);
      if (a !== void 0)
        return a;
    }
  }
  /**
   * Searches through the 3D object and its children, starting with the 3D object
   * itself, and returns all 3D objects with a matching property value.
   *
   * @param {string} name - The name of the property.
   * @param {any} value - The value.
   * @param {Array<Object3D>} result - The method stores the result in this array.
   * @return {Array<Object3D>} The found 3D objects.
   */
  getObjectsByProperty(e, t, i = []) {
    this[e] === t && i.push(this);
    const n = this.children;
    for (let s = 0, a = n.length; s < a; s++)
      n[s].getObjectsByProperty(e, t, i);
    return i;
  }
  /**
   * Returns a vector representing the position of the 3D object in world space.
   *
   * @param {Vector3} target - The target vector the result is stored to.
   * @return {Vector3} The 3D object's position in world space.
   */
  getWorldPosition(e) {
    return this.updateWorldMatrix(!0, !1), e.setFromMatrixPosition(this.matrixWorld);
  }
  /**
   * Returns a Quaternion representing the position of the 3D object in world space.
   *
   * @param {Quaternion} target - The target Quaternion the result is stored to.
   * @return {Quaternion} The 3D object's rotation in world space.
   */
  getWorldQuaternion(e) {
    return this.updateWorldMatrix(!0, !1), this.matrixWorld.decompose(Rr, e, G_), e;
  }
  /**
   * Returns a vector representing the scale of the 3D object in world space.
   *
   * @param {Vector3} target - The target vector the result is stored to.
   * @return {Vector3} The 3D object's scale in world space.
   */
  getWorldScale(e) {
    return this.updateWorldMatrix(!0, !1), this.matrixWorld.decompose(Rr, W_, e), e;
  }
  /**
   * Returns a vector representing the ("look") direction of the 3D object in world space.
   *
   * @param {Vector3} target - The target vector the result is stored to.
   * @return {Vector3} The 3D object's direction in world space.
   */
  getWorldDirection(e) {
    this.updateWorldMatrix(!0, !1);
    const t = this.matrixWorld.elements;
    return e.set(t[8], t[9], t[10]).normalize();
  }
  /**
   * Abstract method to get intersections between a casted ray and this
   * 3D object. Renderable 3D objects such as {@link Mesh}, {@link Line} or {@link Points}
   * implement this method in order to use raycasting.
   *
   * @abstract
   * @param {Raycaster} raycaster - The raycaster.
   * @param {Array<Object>} intersects - An array holding the result of the method.
   */
  raycast() {
  }
  /**
   * Executes the callback on this 3D object and all descendants.
   *
   * Note: Modifying the scene graph inside the callback is discouraged.
   *
   * @param {Function} callback - A callback function that allows to process the current 3D object.
   */
  traverse(e) {
    e(this);
    const t = this.children;
    for (let i = 0, n = t.length; i < n; i++)
      t[i].traverse(e);
  }
  /**
   * Like {@link Object3D#traverse}, but the callback will only be executed for visible 3D objects.
   * Descendants of invisible 3D objects are not traversed.
   *
   * Note: Modifying the scene graph inside the callback is discouraged.
   *
   * @param {Function} callback - A callback function that allows to process the current 3D object.
   */
  traverseVisible(e) {
    if (this.visible === !1) return;
    e(this);
    const t = this.children;
    for (let i = 0, n = t.length; i < n; i++)
      t[i].traverseVisible(e);
  }
  /**
   * Like {@link Object3D#traverse}, but the callback will only be executed for all ancestors.
   *
   * Note: Modifying the scene graph inside the callback is discouraged.
   *
   * @param {Function} callback - A callback function that allows to process the current 3D object.
   */
  traverseAncestors(e) {
    const t = this.parent;
    t !== null && (e(t), t.traverseAncestors(e));
  }
  /**
   * Updates the transformation matrix in local space by computing it from the current
   * position, rotation and scale values.
   */
  updateMatrix() {
    this.matrix.compose(this.position, this.quaternion, this.scale), this.matrixWorldNeedsUpdate = !0;
  }
  /**
   * Updates the transformation matrix in world space of this 3D objects and its descendants.
   *
   * To ensure correct results, this method also recomputes the 3D object's transformation matrix in
   * local space. The computation of the local and world matrix can be controlled with the
   * {@link Object3D#matrixAutoUpdate} and {@link Object3D#matrixWorldAutoUpdate} flags which are both
   * `true` by default.  Set these flags to `false` if you need more control over the update matrix process.
   *
   * @param {boolean} [force=false] - When set to `true`, a recomputation of world matrices is forced even
   * when {@link Object3D#matrixWorldAutoUpdate} is set to `false`.
   */
  updateMatrixWorld(e) {
    this.matrixAutoUpdate && this.updateMatrix(), (this.matrixWorldNeedsUpdate || e) && (this.matrixWorldAutoUpdate === !0 && (this.parent === null ? this.matrixWorld.copy(this.matrix) : this.matrixWorld.multiplyMatrices(this.parent.matrixWorld, this.matrix)), this.matrixWorldNeedsUpdate = !1, e = !0);
    const t = this.children;
    for (let i = 0, n = t.length; i < n; i++)
      t[i].updateMatrixWorld(e);
  }
  /**
   * An alternative version of {@link Object3D#updateMatrixWorld} with more control over the
   * update of ancestor and descendant nodes.
   *
   * @param {boolean} [updateParents=false] Whether ancestor nodes should be updated or not.
   * @param {boolean} [updateChildren=false] Whether descendant nodes should be updated or not.
   */
  updateWorldMatrix(e, t) {
    const i = this.parent;
    if (e === !0 && i !== null && i.updateWorldMatrix(!0, !1), this.matrixAutoUpdate && this.updateMatrix(), this.matrixWorldAutoUpdate === !0 && (this.parent === null ? this.matrixWorld.copy(this.matrix) : this.matrixWorld.multiplyMatrices(this.parent.matrixWorld, this.matrix)), t === !0) {
      const n = this.children;
      for (let s = 0, a = n.length; s < a; s++)
        n[s].updateWorldMatrix(!1, !0);
    }
  }
  /**
   * Serializes the 3D object into JSON.
   *
   * @param {?(Object|string)} meta - An optional value holding meta information about the serialization.
   * @return {Object} A JSON object representing the serialized 3D object.
   * @see {@link ObjectLoader#parse}
   */
  toJSON(e) {
    const t = e === void 0 || typeof e == "string", i = {};
    t && (e = {
      geometries: {},
      materials: {},
      textures: {},
      images: {},
      shapes: {},
      skeletons: {},
      animations: {},
      nodes: {}
    }, i.metadata = {
      version: 4.7,
      type: "Object",
      generator: "Object3D.toJSON"
    });
    const n = {};
    n.uuid = this.uuid, n.type = this.type, this.name !== "" && (n.name = this.name), this.castShadow === !0 && (n.castShadow = !0), this.receiveShadow === !0 && (n.receiveShadow = !0), this.visible === !1 && (n.visible = !1), this.frustumCulled === !1 && (n.frustumCulled = !1), this.renderOrder !== 0 && (n.renderOrder = this.renderOrder), Object.keys(this.userData).length > 0 && (n.userData = this.userData), n.layers = this.layers.mask, n.matrix = this.matrix.toArray(), n.up = this.up.toArray(), this.matrixAutoUpdate === !1 && (n.matrixAutoUpdate = !1), this.isInstancedMesh && (n.type = "InstancedMesh", n.count = this.count, n.instanceMatrix = this.instanceMatrix.toJSON(), this.instanceColor !== null && (n.instanceColor = this.instanceColor.toJSON())), this.isBatchedMesh && (n.type = "BatchedMesh", n.perObjectFrustumCulled = this.perObjectFrustumCulled, n.sortObjects = this.sortObjects, n.drawRanges = this._drawRanges, n.reservedRanges = this._reservedRanges, n.geometryInfo = this._geometryInfo.map((o) => ({
      ...o,
      boundingBox: o.boundingBox ? o.boundingBox.toJSON() : void 0,
      boundingSphere: o.boundingSphere ? o.boundingSphere.toJSON() : void 0
    })), n.instanceInfo = this._instanceInfo.map((o) => ({ ...o })), n.availableInstanceIds = this._availableInstanceIds.slice(), n.availableGeometryIds = this._availableGeometryIds.slice(), n.nextIndexStart = this._nextIndexStart, n.nextVertexStart = this._nextVertexStart, n.geometryCount = this._geometryCount, n.maxInstanceCount = this._maxInstanceCount, n.maxVertexCount = this._maxVertexCount, n.maxIndexCount = this._maxIndexCount, n.geometryInitialized = this._geometryInitialized, n.matricesTexture = this._matricesTexture.toJSON(e), n.indirectTexture = this._indirectTexture.toJSON(e), this._colorsTexture !== null && (n.colorsTexture = this._colorsTexture.toJSON(e)), this.boundingSphere !== null && (n.boundingSphere = this.boundingSphere.toJSON()), this.boundingBox !== null && (n.boundingBox = this.boundingBox.toJSON()));
    function s(o, l) {
      return o[l.uuid] === void 0 && (o[l.uuid] = l.toJSON(e)), l.uuid;
    }
    if (this.isScene)
      this.background && (this.background.isColor ? n.background = this.background.toJSON() : this.background.isTexture && (n.background = this.background.toJSON(e).uuid)), this.environment && this.environment.isTexture && this.environment.isRenderTargetTexture !== !0 && (n.environment = this.environment.toJSON(e).uuid);
    else if (this.isMesh || this.isLine || this.isPoints) {
      n.geometry = s(e.geometries, this.geometry);
      const o = this.geometry.parameters;
      if (o !== void 0 && o.shapes !== void 0) {
        const l = o.shapes;
        if (Array.isArray(l))
          for (let c = 0, h = l.length; c < h; c++) {
            const d = l[c];
            s(e.shapes, d);
          }
        else
          s(e.shapes, l);
      }
    }
    if (this.isSkinnedMesh && (n.bindMode = this.bindMode, n.bindMatrix = this.bindMatrix.toArray(), this.skeleton !== void 0 && (s(e.skeletons, this.skeleton), n.skeleton = this.skeleton.uuid)), this.material !== void 0)
      if (Array.isArray(this.material)) {
        const o = [];
        for (let l = 0, c = this.material.length; l < c; l++)
          o.push(s(e.materials, this.material[l]));
        n.material = o;
      } else
        n.material = s(e.materials, this.material);
    if (this.children.length > 0) {
      n.children = [];
      for (let o = 0; o < this.children.length; o++)
        n.children.push(this.children[o].toJSON(e).object);
    }
    if (this.animations.length > 0) {
      n.animations = [];
      for (let o = 0; o < this.animations.length; o++) {
        const l = this.animations[o];
        n.animations.push(s(e.animations, l));
      }
    }
    if (t) {
      const o = a(e.geometries), l = a(e.materials), c = a(e.textures), h = a(e.images), d = a(e.shapes), u = a(e.skeletons), p = a(e.animations), m = a(e.nodes);
      o.length > 0 && (i.geometries = o), l.length > 0 && (i.materials = l), c.length > 0 && (i.textures = c), h.length > 0 && (i.images = h), d.length > 0 && (i.shapes = d), u.length > 0 && (i.skeletons = u), p.length > 0 && (i.animations = p), m.length > 0 && (i.nodes = m);
    }
    return i.object = n, i;
    function a(o) {
      const l = [];
      for (const c in o) {
        const h = o[c];
        delete h.metadata, l.push(h);
      }
      return l;
    }
  }
  /**
   * Returns a new 3D object with copied values from this instance.
   *
   * @param {boolean} [recursive=true] - When set to `true`, descendants of the 3D object are also cloned.
   * @return {Object3D} A clone of this instance.
   */
  clone(e) {
    return new this.constructor().copy(this, e);
  }
  /**
   * Copies the values of the given 3D object to this instance.
   *
   * @param {Object3D} source - The 3D object to copy.
   * @param {boolean} [recursive=true] - When set to `true`, descendants of the 3D object are cloned.
   * @return {Object3D} A reference to this instance.
   */
  copy(e, t = !0) {
    if (this.name = e.name, this.up.copy(e.up), this.position.copy(e.position), this.rotation.order = e.rotation.order, this.quaternion.copy(e.quaternion), this.scale.copy(e.scale), this.matrix.copy(e.matrix), this.matrixWorld.copy(e.matrixWorld), this.matrixAutoUpdate = e.matrixAutoUpdate, this.matrixWorldAutoUpdate = e.matrixWorldAutoUpdate, this.matrixWorldNeedsUpdate = e.matrixWorldNeedsUpdate, this.layers.mask = e.layers.mask, this.visible = e.visible, this.castShadow = e.castShadow, this.receiveShadow = e.receiveShadow, this.frustumCulled = e.frustumCulled, this.renderOrder = e.renderOrder, this.animations = e.animations.slice(), this.userData = JSON.parse(JSON.stringify(e.userData)), t === !0)
      for (let i = 0; i < e.children.length; i++) {
        const n = e.children[i];
        this.add(n.clone());
      }
    return this;
  }
}
tt.DEFAULT_UP = /* @__PURE__ */ new b(0, 1, 0);
tt.DEFAULT_MATRIX_AUTO_UPDATE = !0;
tt.DEFAULT_MATRIX_WORLD_AUTO_UPDATE = !0;
const Fi = /* @__PURE__ */ new b(), cn = /* @__PURE__ */ new b(), Pc = /* @__PURE__ */ new b(), hn = /* @__PURE__ */ new b(), Fs = /* @__PURE__ */ new b(), Bs = /* @__PURE__ */ new b(), pu = /* @__PURE__ */ new b(), Lc = /* @__PURE__ */ new b(), Ic = /* @__PURE__ */ new b(), Dc = /* @__PURE__ */ new b(), Nc = /* @__PURE__ */ new Ye(), Uc = /* @__PURE__ */ new Ye(), Oc = /* @__PURE__ */ new Ye();
class pi {
  /**
   * Constructs a new triangle.
   *
   * @param {Vector3} [a=(0,0,0)] - The first corner of the triangle.
   * @param {Vector3} [b=(0,0,0)] - The second corner of the triangle.
   * @param {Vector3} [c=(0,0,0)] - The third corner of the triangle.
   */
  constructor(e = new b(), t = new b(), i = new b()) {
    this.a = e, this.b = t, this.c = i;
  }
  /**
   * Computes the normal vector of a triangle.
   *
   * @param {Vector3} a - The first corner of the triangle.
   * @param {Vector3} b - The second corner of the triangle.
   * @param {Vector3} c - The third corner of the triangle.
   * @param {Vector3} target - The target vector that is used to store the method's result.
   * @return {Vector3} The triangle's normal.
   */
  static getNormal(e, t, i, n) {
    n.subVectors(i, t), Fi.subVectors(e, t), n.cross(Fi);
    const s = n.lengthSq();
    return s > 0 ? n.multiplyScalar(1 / Math.sqrt(s)) : n.set(0, 0, 0);
  }
  /**
   * Computes a barycentric coordinates from the given vector.
   * Returns `null` if the triangle is degenerate.
   *
   * @param {Vector3} point - A point in 3D space.
   * @param {Vector3} a - The first corner of the triangle.
   * @param {Vector3} b - The second corner of the triangle.
   * @param {Vector3} c - The third corner of the triangle.
   * @param {Vector3} target - The target vector that is used to store the method's result.
   * @return {?Vector3} The barycentric coordinates for the given point
   */
  static getBarycoord(e, t, i, n, s) {
    Fi.subVectors(n, t), cn.subVectors(i, t), Pc.subVectors(e, t);
    const a = Fi.dot(Fi), o = Fi.dot(cn), l = Fi.dot(Pc), c = cn.dot(cn), h = cn.dot(Pc), d = a * c - o * o;
    if (d === 0)
      return s.set(0, 0, 0), null;
    const u = 1 / d, p = (c * l - o * h) * u, m = (a * h - o * l) * u;
    return s.set(1 - p - m, m, p);
  }
  /**
   * Returns `true` if the given point, when projected onto the plane of the
   * triangle, lies within the triangle.
   *
   * @param {Vector3} point - The point in 3D space to test.
   * @param {Vector3} a - The first corner of the triangle.
   * @param {Vector3} b - The second corner of the triangle.
   * @param {Vector3} c - The third corner of the triangle.
   * @return {boolean} Whether the given point, when projected onto the plane of the
   * triangle, lies within the triangle or not.
   */
  static containsPoint(e, t, i, n) {
    return this.getBarycoord(e, t, i, n, hn) === null ? !1 : hn.x >= 0 && hn.y >= 0 && hn.x + hn.y <= 1;
  }
  /**
   * Computes the value barycentrically interpolated for the given point on the
   * triangle. Returns `null` if the triangle is degenerate.
   *
   * @param {Vector3} point - Position of interpolated point.
   * @param {Vector3} p1 - The first corner of the triangle.
   * @param {Vector3} p2 - The second corner of the triangle.
   * @param {Vector3} p3 - The third corner of the triangle.
   * @param {Vector3} v1 - Value to interpolate of first vertex.
   * @param {Vector3} v2 - Value to interpolate of second vertex.
   * @param {Vector3} v3 - Value to interpolate of third vertex.
   * @param {Vector3} target - The target vector that is used to store the method's result.
   * @return {?Vector3} The interpolated value.
   */
  static getInterpolation(e, t, i, n, s, a, o, l) {
    return this.getBarycoord(e, t, i, n, hn) === null ? (l.x = 0, l.y = 0, "z" in l && (l.z = 0), "w" in l && (l.w = 0), null) : (l.setScalar(0), l.addScaledVector(s, hn.x), l.addScaledVector(a, hn.y), l.addScaledVector(o, hn.z), l);
  }
  /**
   * Computes the value barycentrically interpolated for the given attribute and indices.
   *
   * @param {BufferAttribute} attr - The attribute to interpolate.
   * @param {number} i1 - Index of first vertex.
   * @param {number} i2 - Index of second vertex.
   * @param {number} i3 - Index of third vertex.
   * @param {Vector3} barycoord - The barycoordinate value to use to interpolate.
   * @param {Vector3} target - The target vector that is used to store the method's result.
   * @return {Vector3} The interpolated attribute value.
   */
  static getInterpolatedAttribute(e, t, i, n, s, a) {
    return Nc.setScalar(0), Uc.setScalar(0), Oc.setScalar(0), Nc.fromBufferAttribute(e, t), Uc.fromBufferAttribute(e, i), Oc.fromBufferAttribute(e, n), a.setScalar(0), a.addScaledVector(Nc, s.x), a.addScaledVector(Uc, s.y), a.addScaledVector(Oc, s.z), a;
  }
  /**
   * Returns `true` if the triangle is oriented towards the given direction.
   *
   * @param {Vector3} a - The first corner of the triangle.
   * @param {Vector3} b - The second corner of the triangle.
   * @param {Vector3} c - The third corner of the triangle.
   * @param {Vector3} direction - The (normalized) direction vector.
   * @return {boolean} Whether the triangle is oriented towards the given direction or not.
   */
  static isFrontFacing(e, t, i, n) {
    return Fi.subVectors(i, t), cn.subVectors(e, t), Fi.cross(cn).dot(n) < 0;
  }
  /**
   * Sets the triangle's vertices by copying the given values.
   *
   * @param {Vector3} a - The first corner of the triangle.
   * @param {Vector3} b - The second corner of the triangle.
   * @param {Vector3} c - The third corner of the triangle.
   * @return {Triangle} A reference to this triangle.
   */
  set(e, t, i) {
    return this.a.copy(e), this.b.copy(t), this.c.copy(i), this;
  }
  /**
   * Sets the triangle's vertices by copying the given array values.
   *
   * @param {Array<Vector3>} points - An array with 3D points.
   * @param {number} i0 - The array index representing the first corner of the triangle.
   * @param {number} i1 - The array index representing the second corner of the triangle.
   * @param {number} i2 - The array index representing the third corner of the triangle.
   * @return {Triangle} A reference to this triangle.
   */
  setFromPointsAndIndices(e, t, i, n) {
    return this.a.copy(e[t]), this.b.copy(e[i]), this.c.copy(e[n]), this;
  }
  /**
   * Sets the triangle's vertices by copying the given attribute values.
   *
   * @param {BufferAttribute} attribute - A buffer attribute with 3D points data.
   * @param {number} i0 - The attribute index representing the first corner of the triangle.
   * @param {number} i1 - The attribute index representing the second corner of the triangle.
   * @param {number} i2 - The attribute index representing the third corner of the triangle.
   * @return {Triangle} A reference to this triangle.
   */
  setFromAttributeAndIndices(e, t, i, n) {
    return this.a.fromBufferAttribute(e, t), this.b.fromBufferAttribute(e, i), this.c.fromBufferAttribute(e, n), this;
  }
  /**
   * Returns a new triangle with copied values from this instance.
   *
   * @return {Triangle} A clone of this instance.
   */
  clone() {
    return new this.constructor().copy(this);
  }
  /**
   * Copies the values of the given triangle to this instance.
   *
   * @param {Triangle} triangle - The triangle to copy.
   * @return {Triangle} A reference to this triangle.
   */
  copy(e) {
    return this.a.copy(e.a), this.b.copy(e.b), this.c.copy(e.c), this;
  }
  /**
   * Computes the area of the triangle.
   *
   * @return {number} The triangle's area.
   */
  getArea() {
    return Fi.subVectors(this.c, this.b), cn.subVectors(this.a, this.b), Fi.cross(cn).length() * 0.5;
  }
  /**
   * Computes the midpoint of the triangle.
   *
   * @param {Vector3} target - The target vector that is used to store the method's result.
   * @return {Vector3} The triangle's midpoint.
   */
  getMidpoint(e) {
    return e.addVectors(this.a, this.b).add(this.c).multiplyScalar(1 / 3);
  }
  /**
   * Computes the normal of the triangle.
   *
   * @param {Vector3} target - The target vector that is used to store the method's result.
   * @return {Vector3} The triangle's normal.
   */
  getNormal(e) {
    return pi.getNormal(this.a, this.b, this.c, e);
  }
  /**
   * Computes a plane the triangle lies within.
   *
   * @param {Plane} target - The target vector that is used to store the method's result.
   * @return {Plane} The plane the triangle lies within.
   */
  getPlane(e) {
    return e.setFromCoplanarPoints(this.a, this.b, this.c);
  }
  /**
   * Computes a barycentric coordinates from the given vector.
   * Returns `null` if the triangle is degenerate.
   *
   * @param {Vector3} point - A point in 3D space.
   * @param {Vector3} target - The target vector that is used to store the method's result.
   * @return {?Vector3} The barycentric coordinates for the given point
   */
  getBarycoord(e, t) {
    return pi.getBarycoord(e, this.a, this.b, this.c, t);
  }
  /**
   * Computes the value barycentrically interpolated for the given point on the
   * triangle. Returns `null` if the triangle is degenerate.
   *
   * @param {Vector3} point - Position of interpolated point.
   * @param {Vector3} v1 - Value to interpolate of first vertex.
   * @param {Vector3} v2 - Value to interpolate of second vertex.
   * @param {Vector3} v3 - Value to interpolate of third vertex.
   * @param {Vector3} target - The target vector that is used to store the method's result.
   * @return {?Vector3} The interpolated value.
   */
  getInterpolation(e, t, i, n, s) {
    return pi.getInterpolation(e, this.a, this.b, this.c, t, i, n, s);
  }
  /**
   * Returns `true` if the given point, when projected onto the plane of the
   * triangle, lies within the triangle.
   *
   * @param {Vector3} point - The point in 3D space to test.
   * @return {boolean} Whether the given point, when projected onto the plane of the
   * triangle, lies within the triangle or not.
   */
  containsPoint(e) {
    return pi.containsPoint(e, this.a, this.b, this.c);
  }
  /**
   * Returns `true` if the triangle is oriented towards the given direction.
   *
   * @param {Vector3} direction - The (normalized) direction vector.
   * @return {boolean} Whether the triangle is oriented towards the given direction or not.
   */
  isFrontFacing(e) {
    return pi.isFrontFacing(this.a, this.b, this.c, e);
  }
  /**
   * Returns `true` if this triangle intersects with the given box.
   *
   * @param {Box3} box - The box to intersect.
   * @return {boolean} Whether this triangle intersects with the given box or not.
   */
  intersectsBox(e) {
    return e.intersectsTriangle(this);
  }
  /**
   * Returns the closest point on the triangle to the given point.
   *
   * @param {Vector3} p - The point to compute the closest point for.
   * @param {Vector3} target - The target vector that is used to store the method's result.
   * @return {Vector3} The closest point on the triangle.
   */
  closestPointToPoint(e, t) {
    const i = this.a, n = this.b, s = this.c;
    let a, o;
    Fs.subVectors(n, i), Bs.subVectors(s, i), Lc.subVectors(e, i);
    const l = Fs.dot(Lc), c = Bs.dot(Lc);
    if (l <= 0 && c <= 0)
      return t.copy(i);
    Ic.subVectors(e, n);
    const h = Fs.dot(Ic), d = Bs.dot(Ic);
    if (h >= 0 && d <= h)
      return t.copy(n);
    const u = l * d - h * c;
    if (u <= 0 && l >= 0 && h <= 0)
      return a = l / (l - h), t.copy(i).addScaledVector(Fs, a);
    Dc.subVectors(e, s);
    const p = Fs.dot(Dc), m = Bs.dot(Dc);
    if (m >= 0 && p <= m)
      return t.copy(s);
    const _ = p * c - l * m;
    if (_ <= 0 && c >= 0 && m <= 0)
      return o = c / (c - m), t.copy(i).addScaledVector(Bs, o);
    const g = h * m - p * d;
    if (g <= 0 && d - h >= 0 && p - m >= 0)
      return pu.subVectors(s, n), o = (d - h) / (d - h + (p - m)), t.copy(n).addScaledVector(pu, o);
    const f = 1 / (g + _ + u);
    return a = _ * f, o = u * f, t.copy(i).addScaledVector(Fs, a).addScaledVector(Bs, o);
  }
  /**
   * Returns `true` if this triangle is equal with the given one.
   *
   * @param {Triangle} triangle - The triangle to test for equality.
   * @return {boolean} Whether this triangle is equal with the given one.
   */
  equals(e) {
    return e.a.equals(this.a) && e.b.equals(this.b) && e.c.equals(this.c);
  }
}
const dm = {
  aliceblue: 15792383,
  antiquewhite: 16444375,
  aqua: 65535,
  aquamarine: 8388564,
  azure: 15794175,
  beige: 16119260,
  bisque: 16770244,
  black: 0,
  blanchedalmond: 16772045,
  blue: 255,
  blueviolet: 9055202,
  brown: 10824234,
  burlywood: 14596231,
  cadetblue: 6266528,
  chartreuse: 8388352,
  chocolate: 13789470,
  coral: 16744272,
  cornflowerblue: 6591981,
  cornsilk: 16775388,
  crimson: 14423100,
  cyan: 65535,
  darkblue: 139,
  darkcyan: 35723,
  darkgoldenrod: 12092939,
  darkgray: 11119017,
  darkgreen: 25600,
  darkgrey: 11119017,
  darkkhaki: 12433259,
  darkmagenta: 9109643,
  darkolivegreen: 5597999,
  darkorange: 16747520,
  darkorchid: 10040012,
  darkred: 9109504,
  darksalmon: 15308410,
  darkseagreen: 9419919,
  darkslateblue: 4734347,
  darkslategray: 3100495,
  darkslategrey: 3100495,
  darkturquoise: 52945,
  darkviolet: 9699539,
  deeppink: 16716947,
  deepskyblue: 49151,
  dimgray: 6908265,
  dimgrey: 6908265,
  dodgerblue: 2003199,
  firebrick: 11674146,
  floralwhite: 16775920,
  forestgreen: 2263842,
  fuchsia: 16711935,
  gainsboro: 14474460,
  ghostwhite: 16316671,
  gold: 16766720,
  goldenrod: 14329120,
  gray: 8421504,
  green: 32768,
  greenyellow: 11403055,
  grey: 8421504,
  honeydew: 15794160,
  hotpink: 16738740,
  indianred: 13458524,
  indigo: 4915330,
  ivory: 16777200,
  khaki: 15787660,
  lavender: 15132410,
  lavenderblush: 16773365,
  lawngreen: 8190976,
  lemonchiffon: 16775885,
  lightblue: 11393254,
  lightcoral: 15761536,
  lightcyan: 14745599,
  lightgoldenrodyellow: 16448210,
  lightgray: 13882323,
  lightgreen: 9498256,
  lightgrey: 13882323,
  lightpink: 16758465,
  lightsalmon: 16752762,
  lightseagreen: 2142890,
  lightskyblue: 8900346,
  lightslategray: 7833753,
  lightslategrey: 7833753,
  lightsteelblue: 11584734,
  lightyellow: 16777184,
  lime: 65280,
  limegreen: 3329330,
  linen: 16445670,
  magenta: 16711935,
  maroon: 8388608,
  mediumaquamarine: 6737322,
  mediumblue: 205,
  mediumorchid: 12211667,
  mediumpurple: 9662683,
  mediumseagreen: 3978097,
  mediumslateblue: 8087790,
  mediumspringgreen: 64154,
  mediumturquoise: 4772300,
  mediumvioletred: 13047173,
  midnightblue: 1644912,
  mintcream: 16121850,
  mistyrose: 16770273,
  moccasin: 16770229,
  navajowhite: 16768685,
  navy: 128,
  oldlace: 16643558,
  olive: 8421376,
  olivedrab: 7048739,
  orange: 16753920,
  orangered: 16729344,
  orchid: 14315734,
  palegoldenrod: 15657130,
  palegreen: 10025880,
  paleturquoise: 11529966,
  palevioletred: 14381203,
  papayawhip: 16773077,
  peachpuff: 16767673,
  peru: 13468991,
  pink: 16761035,
  plum: 14524637,
  powderblue: 11591910,
  purple: 8388736,
  rebeccapurple: 6697881,
  red: 16711680,
  rosybrown: 12357519,
  royalblue: 4286945,
  saddlebrown: 9127187,
  salmon: 16416882,
  sandybrown: 16032864,
  seagreen: 3050327,
  seashell: 16774638,
  sienna: 10506797,
  silver: 12632256,
  skyblue: 8900331,
  slateblue: 6970061,
  slategray: 7372944,
  slategrey: 7372944,
  snow: 16775930,
  springgreen: 65407,
  steelblue: 4620980,
  tan: 13808780,
  teal: 32896,
  thistle: 14204888,
  tomato: 16737095,
  turquoise: 4251856,
  violet: 15631086,
  wheat: 16113331,
  white: 16777215,
  whitesmoke: 16119285,
  yellow: 16776960,
  yellowgreen: 10145074
}, wn = { h: 0, s: 0, l: 0 }, Fa = { h: 0, s: 0, l: 0 };
function Fc(r, e, t) {
  return t < 0 && (t += 1), t > 1 && (t -= 1), t < 1 / 6 ? r + (e - r) * 6 * t : t < 1 / 2 ? e : t < 2 / 3 ? r + (e - r) * 6 * (2 / 3 - t) : r;
}
class oe {
  /**
   * Constructs a new color.
   *
   * Note that standard method of specifying color in three.js is with a hexadecimal triplet,
   * and that method is used throughout the rest of the documentation.
   *
   * @param {(number|string|Color)} [r] - The red component of the color. If `g` and `b` are
   * not provided, it can be hexadecimal triplet, a CSS-style string or another `Color` instance.
   * @param {number} [g] - The green component.
   * @param {number} [b] - The blue component.
   */
  constructor(e, t, i) {
    return this.isColor = !0, this.r = 1, this.g = 1, this.b = 1, this.set(e, t, i);
  }
  /**
   * Sets the colors's components from the given values.
   *
   * @param {(number|string|Color)} [r] - The red component of the color. If `g` and `b` are
   * not provided, it can be hexadecimal triplet, a CSS-style string or another `Color` instance.
   * @param {number} [g] - The green component.
   * @param {number} [b] - The blue component.
   * @return {Color} A reference to this color.
   */
  set(e, t, i) {
    if (t === void 0 && i === void 0) {
      const n = e;
      n && n.isColor ? this.copy(n) : typeof n == "number" ? this.setHex(n) : typeof n == "string" && this.setStyle(n);
    } else
      this.setRGB(e, t, i);
    return this;
  }
  /**
   * Sets the colors's components to the given scalar value.
   *
   * @param {number} scalar - The scalar value.
   * @return {Color} A reference to this color.
   */
  setScalar(e) {
    return this.r = e, this.g = e, this.b = e, this;
  }
  /**
   * Sets this color from a hexadecimal value.
   *
   * @param {number} hex - The hexadecimal value.
   * @param {string} [colorSpace=SRGBColorSpace] - The color space.
   * @return {Color} A reference to this color.
   */
  setHex(e, t = Qt) {
    return e = Math.floor(e), this.r = (e >> 16 & 255) / 255, this.g = (e >> 8 & 255) / 255, this.b = (e & 255) / 255, et.colorSpaceToWorking(this, t), this;
  }
  /**
   * Sets this color from RGB values.
   *
   * @param {number} r - Red channel value between `0.0` and `1.0`.
   * @param {number} g - Green channel value between `0.0` and `1.0`.
   * @param {number} b - Blue channel value between `0.0` and `1.0`.
   * @param {string} [colorSpace=ColorManagement.workingColorSpace] - The color space.
   * @return {Color} A reference to this color.
   */
  setRGB(e, t, i, n = et.workingColorSpace) {
    return this.r = e, this.g = t, this.b = i, et.colorSpaceToWorking(this, n), this;
  }
  /**
   * Sets this color from RGB values.
   *
   * @param {number} h - Hue value between `0.0` and `1.0`.
   * @param {number} s - Saturation value between `0.0` and `1.0`.
   * @param {number} l - Lightness value between `0.0` and `1.0`.
   * @param {string} [colorSpace=ColorManagement.workingColorSpace] - The color space.
   * @return {Color} A reference to this color.
   */
  setHSL(e, t, i, n = et.workingColorSpace) {
    if (e = ld(e, 1), t = Fe(t, 0, 1), i = Fe(i, 0, 1), t === 0)
      this.r = this.g = this.b = i;
    else {
      const s = i <= 0.5 ? i * (1 + t) : i + t - i * t, a = 2 * i - s;
      this.r = Fc(a, s, e + 1 / 3), this.g = Fc(a, s, e), this.b = Fc(a, s, e - 1 / 3);
    }
    return et.colorSpaceToWorking(this, n), this;
  }
  /**
   * Sets this color from a CSS-style string. For example, `rgb(250, 0,0)`,
   * `rgb(100%, 0%, 0%)`, `hsl(0, 100%, 50%)`, `#ff0000`, `#f00`, or `red` ( or
   * any [X11 color name]{@link https://en.wikipedia.org/wiki/X11_color_names#Color_name_chart} -
   * all 140 color names are supported).
   *
   * @param {string} style - Color as a CSS-style string.
   * @param {string} [colorSpace=SRGBColorSpace] - The color space.
   * @return {Color} A reference to this color.
   */
  setStyle(e, t = Qt) {
    function i(s) {
      s !== void 0 && parseFloat(s) < 1 && console.warn("THREE.Color: Alpha component of " + e + " will be ignored.");
    }
    let n;
    if (n = /^(\w+)\(([^\)]*)\)/.exec(e)) {
      let s;
      const a = n[1], o = n[2];
      switch (a) {
        case "rgb":
        case "rgba":
          if (s = /^\s*(\d+)\s*,\s*(\d+)\s*,\s*(\d+)\s*(?:,\s*(\d*\.?\d+)\s*)?$/.exec(o))
            return i(s[4]), this.setRGB(
              Math.min(255, parseInt(s[1], 10)) / 255,
              Math.min(255, parseInt(s[2], 10)) / 255,
              Math.min(255, parseInt(s[3], 10)) / 255,
              t
            );
          if (s = /^\s*(\d+)\%\s*,\s*(\d+)\%\s*,\s*(\d+)\%\s*(?:,\s*(\d*\.?\d+)\s*)?$/.exec(o))
            return i(s[4]), this.setRGB(
              Math.min(100, parseInt(s[1], 10)) / 100,
              Math.min(100, parseInt(s[2], 10)) / 100,
              Math.min(100, parseInt(s[3], 10)) / 100,
              t
            );
          break;
        case "hsl":
        case "hsla":
          if (s = /^\s*(\d*\.?\d+)\s*,\s*(\d*\.?\d+)\%\s*,\s*(\d*\.?\d+)\%\s*(?:,\s*(\d*\.?\d+)\s*)?$/.exec(o))
            return i(s[4]), this.setHSL(
              parseFloat(s[1]) / 360,
              parseFloat(s[2]) / 100,
              parseFloat(s[3]) / 100,
              t
            );
          break;
        default:
          console.warn("THREE.Color: Unknown color model " + e);
      }
    } else if (n = /^\#([A-Fa-f\d]+)$/.exec(e)) {
      const s = n[1], a = s.length;
      if (a === 3)
        return this.setRGB(
          parseInt(s.charAt(0), 16) / 15,
          parseInt(s.charAt(1), 16) / 15,
          parseInt(s.charAt(2), 16) / 15,
          t
        );
      if (a === 6)
        return this.setHex(parseInt(s, 16), t);
      console.warn("THREE.Color: Invalid hex color " + e);
    } else if (e && e.length > 0)
      return this.setColorName(e, t);
    return this;
  }
  /**
   * Sets this color from a color name. Faster than {@link Color#setStyle} if
   * you don't need the other CSS-style formats.
   *
   * For convenience, the list of names is exposed in `Color.NAMES` as a hash.
   * ```js
   * Color.NAMES.aliceblue // returns 0xF0F8FF
   * ```
   *
   * @param {string} style - The color name.
   * @param {string} [colorSpace=SRGBColorSpace] - The color space.
   * @return {Color} A reference to this color.
   */
  setColorName(e, t = Qt) {
    const i = dm[e.toLowerCase()];
    return i !== void 0 ? this.setHex(i, t) : console.warn("THREE.Color: Unknown color " + e), this;
  }
  /**
   * Returns a new color with copied values from this instance.
   *
   * @return {Color} A clone of this instance.
   */
  clone() {
    return new this.constructor(this.r, this.g, this.b);
  }
  /**
   * Copies the values of the given color to this instance.
   *
   * @param {Color} color - The color to copy.
   * @return {Color} A reference to this color.
   */
  copy(e) {
    return this.r = e.r, this.g = e.g, this.b = e.b, this;
  }
  /**
   * Copies the given color into this color, and then converts this color from
   * `SRGBColorSpace` to `LinearSRGBColorSpace`.
   *
   * @param {Color} color - The color to copy/convert.
   * @return {Color} A reference to this color.
   */
  copySRGBToLinear(e) {
    return this.r = gn(e.r), this.g = gn(e.g), this.b = gn(e.b), this;
  }
  /**
   * Copies the given color into this color, and then converts this color from
   * `LinearSRGBColorSpace` to `SRGBColorSpace`.
   *
   * @param {Color} color - The color to copy/convert.
   * @return {Color} A reference to this color.
   */
  copyLinearToSRGB(e) {
    return this.r = ar(e.r), this.g = ar(e.g), this.b = ar(e.b), this;
  }
  /**
   * Converts this color from `SRGBColorSpace` to `LinearSRGBColorSpace`.
   *
   * @return {Color} A reference to this color.
   */
  convertSRGBToLinear() {
    return this.copySRGBToLinear(this), this;
  }
  /**
   * Converts this color from `LinearSRGBColorSpace` to `SRGBColorSpace`.
   *
   * @return {Color} A reference to this color.
   */
  convertLinearToSRGB() {
    return this.copyLinearToSRGB(this), this;
  }
  /**
   * Returns the hexadecimal value of this color.
   *
   * @param {string} [colorSpace=SRGBColorSpace] - The color space.
   * @return {number} The hexadecimal value.
   */
  getHex(e = Qt) {
    return et.workingToColorSpace(Yt.copy(this), e), Math.round(Fe(Yt.r * 255, 0, 255)) * 65536 + Math.round(Fe(Yt.g * 255, 0, 255)) * 256 + Math.round(Fe(Yt.b * 255, 0, 255));
  }
  /**
   * Returns the hexadecimal value of this color as a string (for example, 'FFFFFF').
   *
   * @param {string} [colorSpace=SRGBColorSpace] - The color space.
   * @return {string} The hexadecimal value as a string.
   */
  getHexString(e = Qt) {
    return ("000000" + this.getHex(e).toString(16)).slice(-6);
  }
  /**
   * Converts the colors RGB values into the HSL format and stores them into the
   * given target object.
   *
   * @param {{h:number,s:number,l:number}} target - The target object that is used to store the method's result.
   * @param {string} [colorSpace=ColorManagement.workingColorSpace] - The color space.
   * @return {{h:number,s:number,l:number}} The HSL representation of this color.
   */
  getHSL(e, t = et.workingColorSpace) {
    et.workingToColorSpace(Yt.copy(this), t);
    const i = Yt.r, n = Yt.g, s = Yt.b, a = Math.max(i, n, s), o = Math.min(i, n, s);
    let l, c;
    const h = (o + a) / 2;
    if (o === a)
      l = 0, c = 0;
    else {
      const d = a - o;
      switch (c = h <= 0.5 ? d / (a + o) : d / (2 - a - o), a) {
        case i:
          l = (n - s) / d + (n < s ? 6 : 0);
          break;
        case n:
          l = (s - i) / d + 2;
          break;
        case s:
          l = (i - n) / d + 4;
          break;
      }
      l /= 6;
    }
    return e.h = l, e.s = c, e.l = h, e;
  }
  /**
   * Returns the RGB values of this color and stores them into the given target object.
   *
   * @param {Color} target - The target color that is used to store the method's result.
   * @param {string} [colorSpace=ColorManagement.workingColorSpace] - The color space.
   * @return {Color} The RGB representation of this color.
   */
  getRGB(e, t = et.workingColorSpace) {
    return et.workingToColorSpace(Yt.copy(this), t), e.r = Yt.r, e.g = Yt.g, e.b = Yt.b, e;
  }
  /**
   * Returns the value of this color as a CSS style string. Example: `rgb(255,0,0)`.
   *
   * @param {string} [colorSpace=SRGBColorSpace] - The color space.
   * @return {string} The CSS representation of this color.
   */
  getStyle(e = Qt) {
    et.workingToColorSpace(Yt.copy(this), e);
    const t = Yt.r, i = Yt.g, n = Yt.b;
    return e !== Qt ? `color(${e} ${t.toFixed(3)} ${i.toFixed(3)} ${n.toFixed(3)})` : `rgb(${Math.round(t * 255)},${Math.round(i * 255)},${Math.round(n * 255)})`;
  }
  /**
   * Adds the given HSL values to this color's values.
   * Internally, this converts the color's RGB values to HSL, adds HSL
   * and then converts the color back to RGB.
   *
   * @param {number} h - Hue value between `0.0` and `1.0`.
   * @param {number} s - Saturation value between `0.0` and `1.0`.
   * @param {number} l - Lightness value between `0.0` and `1.0`.
   * @return {Color} A reference to this color.
   */
  offsetHSL(e, t, i) {
    return this.getHSL(wn), this.setHSL(wn.h + e, wn.s + t, wn.l + i);
  }
  /**
   * Adds the RGB values of the given color to the RGB values of this color.
   *
   * @param {Color} color - The color to add.
   * @return {Color} A reference to this color.
   */
  add(e) {
    return this.r += e.r, this.g += e.g, this.b += e.b, this;
  }
  /**
   * Adds the RGB values of the given colors and stores the result in this instance.
   *
   * @param {Color} color1 - The first color.
   * @param {Color} color2 - The second color.
   * @return {Color} A reference to this color.
   */
  addColors(e, t) {
    return this.r = e.r + t.r, this.g = e.g + t.g, this.b = e.b + t.b, this;
  }
  /**
   * Adds the given scalar value to the RGB values of this color.
   *
   * @param {number} s - The scalar to add.
   * @return {Color} A reference to this color.
   */
  addScalar(e) {
    return this.r += e, this.g += e, this.b += e, this;
  }
  /**
   * Subtracts the RGB values of the given color from the RGB values of this color.
   *
   * @param {Color} color - The color to subtract.
   * @return {Color} A reference to this color.
   */
  sub(e) {
    return this.r = Math.max(0, this.r - e.r), this.g = Math.max(0, this.g - e.g), this.b = Math.max(0, this.b - e.b), this;
  }
  /**
   * Multiplies the RGB values of the given color with the RGB values of this color.
   *
   * @param {Color} color - The color to multiply.
   * @return {Color} A reference to this color.
   */
  multiply(e) {
    return this.r *= e.r, this.g *= e.g, this.b *= e.b, this;
  }
  /**
   * Multiplies the given scalar value with the RGB values of this color.
   *
   * @param {number} s - The scalar to multiply.
   * @return {Color} A reference to this color.
   */
  multiplyScalar(e) {
    return this.r *= e, this.g *= e, this.b *= e, this;
  }
  /**
   * Linearly interpolates this color's RGB values toward the RGB values of the
   * given color. The alpha argument can be thought of as the ratio between
   * the two colors, where `0.0` is this color and `1.0` is the first argument.
   *
   * @param {Color} color - The color to converge on.
   * @param {number} alpha - The interpolation factor in the closed interval `[0,1]`.
   * @return {Color} A reference to this color.
   */
  lerp(e, t) {
    return this.r += (e.r - this.r) * t, this.g += (e.g - this.g) * t, this.b += (e.b - this.b) * t, this;
  }
  /**
   * Linearly interpolates between the given colors and stores the result in this instance.
   * The alpha argument can be thought of as the ratio between the two colors, where `0.0`
   * is the first and `1.0` is the second color.
   *
   * @param {Color} color1 - The first color.
   * @param {Color} color2 - The second color.
   * @param {number} alpha - The interpolation factor in the closed interval `[0,1]`.
   * @return {Color} A reference to this color.
   */
  lerpColors(e, t, i) {
    return this.r = e.r + (t.r - e.r) * i, this.g = e.g + (t.g - e.g) * i, this.b = e.b + (t.b - e.b) * i, this;
  }
  /**
   * Linearly interpolates this color's HSL values toward the HSL values of the
   * given color. It differs from {@link Color#lerp} by not interpolating straight
   * from one color to the other, but instead going through all the hues in between
   * those two colors. The alpha argument can be thought of as the ratio between
   * the two colors, where 0.0 is this color and 1.0 is the first argument.
   *
   * @param {Color} color - The color to converge on.
   * @param {number} alpha - The interpolation factor in the closed interval `[0,1]`.
   * @return {Color} A reference to this color.
   */
  lerpHSL(e, t) {
    this.getHSL(wn), e.getHSL(Fa);
    const i = Jr(wn.h, Fa.h, t), n = Jr(wn.s, Fa.s, t), s = Jr(wn.l, Fa.l, t);
    return this.setHSL(i, n, s), this;
  }
  /**
   * Sets the color's RGB components from the given 3D vector.
   *
   * @param {Vector3} v - The vector to set.
   * @return {Color} A reference to this color.
   */
  setFromVector3(e) {
    return this.r = e.x, this.g = e.y, this.b = e.z, this;
  }
  /**
   * Transforms this color with the given 3x3 matrix.
   *
   * @param {Matrix3} m - The matrix.
   * @return {Color} A reference to this color.
   */
  applyMatrix3(e) {
    const t = this.r, i = this.g, n = this.b, s = e.elements;
    return this.r = s[0] * t + s[3] * i + s[6] * n, this.g = s[1] * t + s[4] * i + s[7] * n, this.b = s[2] * t + s[5] * i + s[8] * n, this;
  }
  /**
   * Returns `true` if this color is equal with the given one.
   *
   * @param {Color} c - The color to test for equality.
   * @return {boolean} Whether this bounding color is equal with the given one.
   */
  equals(e) {
    return e.r === this.r && e.g === this.g && e.b === this.b;
  }
  /**
   * Sets this color's RGB components from the given array.
   *
   * @param {Array<number>} array - An array holding the RGB values.
   * @param {number} [offset=0] - The offset into the array.
   * @return {Color} A reference to this color.
   */
  fromArray(e, t = 0) {
    return this.r = e[t], this.g = e[t + 1], this.b = e[t + 2], this;
  }
  /**
   * Writes the RGB components of this color to the given array. If no array is provided,
   * the method returns a new instance.
   *
   * @param {Array<number>} [array=[]] - The target array holding the color components.
   * @param {number} [offset=0] - Index of the first element in the array.
   * @return {Array<number>} The color components.
   */
  toArray(e = [], t = 0) {
    return e[t] = this.r, e[t + 1] = this.g, e[t + 2] = this.b, e;
  }
  /**
   * Sets the components of this color from the given buffer attribute.
   *
   * @param {BufferAttribute} attribute - The buffer attribute holding color data.
   * @param {number} index - The index into the attribute.
   * @return {Color} A reference to this color.
   */
  fromBufferAttribute(e, t) {
    return this.r = e.getX(t), this.g = e.getY(t), this.b = e.getZ(t), this;
  }
  /**
   * This methods defines the serialization result of this class. Returns the color
   * as a hexadecimal value.
   *
   * @return {number} The hexadecimal value.
   */
  toJSON() {
    return this.getHex();
  }
  *[Symbol.iterator]() {
    yield this.r, yield this.g, yield this.b;
  }
}
const Yt = /* @__PURE__ */ new oe();
oe.NAMES = dm;
let q_ = 0;
class qt extends sn {
  /**
   * Constructs a new material.
   */
  constructor() {
    super(), this.isMaterial = !0, Object.defineProperty(this, "id", { value: q_++ }), this.uuid = Ti(), this.name = "", this.type = "Material", this.blending = Dn, this.side = Di, this.vertexColors = !1, this.opacity = 1, this.transparent = !1, this.alphaHash = !1, this.blendSrc = qo, this.blendDst = Zo, this.blendEquation = Ln, this.blendSrcAlpha = null, this.blendDstAlpha = null, this.blendEquationAlpha = null, this.blendColor = new oe(0, 0, 0), this.blendAlpha = 0, this.depthFunc = vs, this.depthTest = !0, this.depthWrite = !0, this.stencilWriteMask = 255, this.stencilFunc = ca, this.stencilRef = 0, this.stencilFuncMask = 255, this.stencilFail = os, this.stencilZFail = os, this.stencilZPass = os, this.stencilWrite = !1, this.clippingPlanes = null, this.clipIntersection = !1, this.clipShadows = !1, this.shadowSide = null, this.colorWrite = !0, this.precision = null, this.polygonOffset = !1, this.polygonOffsetFactor = 0, this.polygonOffsetUnits = 0, this.dithering = !1, this.alphaToCoverage = !1, this.premultipliedAlpha = !1, this.forceSinglePass = !1, this.allowOverride = !0, this.visible = !0, this.toneMapped = !0, this.userData = {}, this.version = 0, this._alphaTest = 0;
  }
  /**
   * Sets the alpha value to be used when running an alpha test. The material
   * will not be rendered if the opacity is lower than this value.
   *
   * @type {number}
   * @readonly
   * @default 0
   */
  get alphaTest() {
    return this._alphaTest;
  }
  set alphaTest(e) {
    this._alphaTest > 0 != e > 0 && this.version++, this._alphaTest = e;
  }
  /**
   * An optional callback that is executed immediately before the material is used to render a 3D object.
   *
   * This method can only be used when rendering with {@link WebGLRenderer}.
   *
   * @param {WebGLRenderer} renderer - The renderer.
   * @param {Scene} scene - The scene.
   * @param {Camera} camera - The camera that is used to render the scene.
   * @param {BufferGeometry} geometry - The 3D object's geometry.
   * @param {Object3D} object - The 3D object.
   * @param {Object} group - The geometry group data.
   */
  onBeforeRender() {
  }
  /**
   * An optional callback that is executed immediately before the shader
   * program is compiled. This function is called with the shader source code
   * as a parameter. Useful for the modification of built-in materials.
   *
   * This method can only be used when rendering with {@link WebGLRenderer}. The
   * recommended approach when customizing materials is to use `WebGPURenderer` with the new
   * Node Material system and [TSL]{@link https://github.com/mrdoob/three.js/wiki/Three.js-Shading-Language}.
   *
   * @param {{vertexShader:string,fragmentShader:string,uniforms:Object}} shaderobject - The object holds the uniforms and the vertex and fragment shader source.
   * @param {WebGLRenderer} renderer - A reference to the renderer.
   */
  onBeforeCompile() {
  }
  /**
   * In case {@link Material#onBeforeCompile} is used, this callback can be used to identify
   * values of settings used in `onBeforeCompile()`, so three.js can reuse a cached
   * shader or recompile the shader for this material as needed.
   *
   * This method can only be used when rendering with {@link WebGLRenderer}.
   *
   * @return {string} The custom program cache key.
   */
  customProgramCacheKey() {
    return this.onBeforeCompile.toString();
  }
  /**
   * This method can be used to set default values from parameter objects.
   * It is a generic implementation so it can be used with different types
   * of materials.
   *
   * @param {Object} [values] - The material values to set.
   */
  setValues(e) {
    if (e !== void 0)
      for (const t in e) {
        const i = e[t];
        if (i === void 0) {
          console.warn(`THREE.Material: parameter '${t}' has value of undefined.`);
          continue;
        }
        const n = this[t];
        if (n === void 0) {
          console.warn(`THREE.Material: '${t}' is not a property of THREE.${this.type}.`);
          continue;
        }
        n && n.isColor ? n.set(i) : n && n.isVector3 && i && i.isVector3 ? n.copy(i) : this[t] = i;
      }
  }
  /**
   * Serializes the material into JSON.
   *
   * @param {?(Object|string)} meta - An optional value holding meta information about the serialization.
   * @return {Object} A JSON object representing the serialized material.
   * @see {@link ObjectLoader#parse}
   */
  toJSON(e) {
    const t = e === void 0 || typeof e == "string";
    t && (e = {
      textures: {},
      images: {}
    });
    const i = {
      metadata: {
        version: 4.7,
        type: "Material",
        generator: "Material.toJSON"
      }
    };
    i.uuid = this.uuid, i.type = this.type, this.name !== "" && (i.name = this.name), this.color && this.color.isColor && (i.color = this.color.getHex()), this.roughness !== void 0 && (i.roughness = this.roughness), this.metalness !== void 0 && (i.metalness = this.metalness), this.sheen !== void 0 && (i.sheen = this.sheen), this.sheenColor && this.sheenColor.isColor && (i.sheenColor = this.sheenColor.getHex()), this.sheenRoughness !== void 0 && (i.sheenRoughness = this.sheenRoughness), this.emissive && this.emissive.isColor && (i.emissive = this.emissive.getHex()), this.emissiveIntensity !== void 0 && this.emissiveIntensity !== 1 && (i.emissiveIntensity = this.emissiveIntensity), this.specular && this.specular.isColor && (i.specular = this.specular.getHex()), this.specularIntensity !== void 0 && (i.specularIntensity = this.specularIntensity), this.specularColor && this.specularColor.isColor && (i.specularColor = this.specularColor.getHex()), this.shininess !== void 0 && (i.shininess = this.shininess), this.clearcoat !== void 0 && (i.clearcoat = this.clearcoat), this.clearcoatRoughness !== void 0 && (i.clearcoatRoughness = this.clearcoatRoughness), this.clearcoatMap && this.clearcoatMap.isTexture && (i.clearcoatMap = this.clearcoatMap.toJSON(e).uuid), this.clearcoatRoughnessMap && this.clearcoatRoughnessMap.isTexture && (i.clearcoatRoughnessMap = this.clearcoatRoughnessMap.toJSON(e).uuid), this.clearcoatNormalMap && this.clearcoatNormalMap.isTexture && (i.clearcoatNormalMap = this.clearcoatNormalMap.toJSON(e).uuid, i.clearcoatNormalScale = this.clearcoatNormalScale.toArray()), this.sheenColorMap && this.sheenColorMap.isTexture && (i.sheenColorMap = this.sheenColorMap.toJSON(e).uuid), this.sheenRoughnessMap && this.sheenRoughnessMap.isTexture && (i.sheenRoughnessMap = this.sheenRoughnessMap.toJSON(e).uuid), this.dispersion !== void 0 && (i.dispersion = this.dispersion), this.iridescence !== void 0 && (i.iridescence = this.iridescence), this.iridescenceIOR !== void 0 && (i.iridescenceIOR = this.iridescenceIOR), this.iridescenceThicknessRange !== void 0 && (i.iridescenceThicknessRange = this.iridescenceThicknessRange), this.iridescenceMap && this.iridescenceMap.isTexture && (i.iridescenceMap = this.iridescenceMap.toJSON(e).uuid), this.iridescenceThicknessMap && this.iridescenceThicknessMap.isTexture && (i.iridescenceThicknessMap = this.iridescenceThicknessMap.toJSON(e).uuid), this.anisotropy !== void 0 && (i.anisotropy = this.anisotropy), this.anisotropyRotation !== void 0 && (i.anisotropyRotation = this.anisotropyRotation), this.anisotropyMap && this.anisotropyMap.isTexture && (i.anisotropyMap = this.anisotropyMap.toJSON(e).uuid), this.map && this.map.isTexture && (i.map = this.map.toJSON(e).uuid), this.matcap && this.matcap.isTexture && (i.matcap = this.matcap.toJSON(e).uuid), this.alphaMap && this.alphaMap.isTexture && (i.alphaMap = this.alphaMap.toJSON(e).uuid), this.lightMap && this.lightMap.isTexture && (i.lightMap = this.lightMap.toJSON(e).uuid, i.lightMapIntensity = this.lightMapIntensity), this.aoMap && this.aoMap.isTexture && (i.aoMap = this.aoMap.toJSON(e).uuid, i.aoMapIntensity = this.aoMapIntensity), this.bumpMap && this.bumpMap.isTexture && (i.bumpMap = this.bumpMap.toJSON(e).uuid, i.bumpScale = this.bumpScale), this.normalMap && this.normalMap.isTexture && (i.normalMap = this.normalMap.toJSON(e).uuid, i.normalMapType = this.normalMapType, i.normalScale = this.normalScale.toArray()), this.displacementMap && this.displacementMap.isTexture && (i.displacementMap = this.displacementMap.toJSON(e).uuid, i.displacementScale = this.displacementScale, i.displacementBias = this.displacementBias), this.roughnessMap && this.roughnessMap.isTexture && (i.roughnessMap = this.roughnessMap.toJSON(e).uuid), this.metalnessMap && this.metalnessMap.isTexture && (i.metalnessMap = this.metalnessMap.toJSON(e).uuid), this.emissiveMap && this.emissiveMap.isTexture && (i.emissiveMap = this.emissiveMap.toJSON(e).uuid), this.specularMap && this.specularMap.isTexture && (i.specularMap = this.specularMap.toJSON(e).uuid), this.specularIntensityMap && this.specularIntensityMap.isTexture && (i.specularIntensityMap = this.specularIntensityMap.toJSON(e).uuid), this.specularColorMap && this.specularColorMap.isTexture && (i.specularColorMap = this.specularColorMap.toJSON(e).uuid), this.envMap && this.envMap.isTexture && (i.envMap = this.envMap.toJSON(e).uuid, this.combine !== void 0 && (i.combine = this.combine)), this.envMapRotation !== void 0 && (i.envMapRotation = this.envMapRotation.toArray()), this.envMapIntensity !== void 0 && (i.envMapIntensity = this.envMapIntensity), this.reflectivity !== void 0 && (i.reflectivity = this.reflectivity), this.refractionRatio !== void 0 && (i.refractionRatio = this.refractionRatio), this.gradientMap && this.gradientMap.isTexture && (i.gradientMap = this.gradientMap.toJSON(e).uuid), this.transmission !== void 0 && (i.transmission = this.transmission), this.transmissionMap && this.transmissionMap.isTexture && (i.transmissionMap = this.transmissionMap.toJSON(e).uuid), this.thickness !== void 0 && (i.thickness = this.thickness), this.thicknessMap && this.thicknessMap.isTexture && (i.thicknessMap = this.thicknessMap.toJSON(e).uuid), this.attenuationDistance !== void 0 && this.attenuationDistance !== 1 / 0 && (i.attenuationDistance = this.attenuationDistance), this.attenuationColor !== void 0 && (i.attenuationColor = this.attenuationColor.getHex()), this.size !== void 0 && (i.size = this.size), this.shadowSide !== null && (i.shadowSide = this.shadowSide), this.sizeAttenuation !== void 0 && (i.sizeAttenuation = this.sizeAttenuation), this.blending !== Dn && (i.blending = this.blending), this.side !== Di && (i.side = this.side), this.vertexColors === !0 && (i.vertexColors = !0), this.opacity < 1 && (i.opacity = this.opacity), this.transparent === !0 && (i.transparent = !0), this.blendSrc !== qo && (i.blendSrc = this.blendSrc), this.blendDst !== Zo && (i.blendDst = this.blendDst), this.blendEquation !== Ln && (i.blendEquation = this.blendEquation), this.blendSrcAlpha !== null && (i.blendSrcAlpha = this.blendSrcAlpha), this.blendDstAlpha !== null && (i.blendDstAlpha = this.blendDstAlpha), this.blendEquationAlpha !== null && (i.blendEquationAlpha = this.blendEquationAlpha), this.blendColor && this.blendColor.isColor && (i.blendColor = this.blendColor.getHex()), this.blendAlpha !== 0 && (i.blendAlpha = this.blendAlpha), this.depthFunc !== vs && (i.depthFunc = this.depthFunc), this.depthTest === !1 && (i.depthTest = this.depthTest), this.depthWrite === !1 && (i.depthWrite = this.depthWrite), this.colorWrite === !1 && (i.colorWrite = this.colorWrite), this.stencilWriteMask !== 255 && (i.stencilWriteMask = this.stencilWriteMask), this.stencilFunc !== ca && (i.stencilFunc = this.stencilFunc), this.stencilRef !== 0 && (i.stencilRef = this.stencilRef), this.stencilFuncMask !== 255 && (i.stencilFuncMask = this.stencilFuncMask), this.stencilFail !== os && (i.stencilFail = this.stencilFail), this.stencilZFail !== os && (i.stencilZFail = this.stencilZFail), this.stencilZPass !== os && (i.stencilZPass = this.stencilZPass), this.stencilWrite === !0 && (i.stencilWrite = this.stencilWrite), this.rotation !== void 0 && this.rotation !== 0 && (i.rotation = this.rotation), this.polygonOffset === !0 && (i.polygonOffset = !0), this.polygonOffsetFactor !== 0 && (i.polygonOffsetFactor = this.polygonOffsetFactor), this.polygonOffsetUnits !== 0 && (i.polygonOffsetUnits = this.polygonOffsetUnits), this.linewidth !== void 0 && this.linewidth !== 1 && (i.linewidth = this.linewidth), this.dashSize !== void 0 && (i.dashSize = this.dashSize), this.gapSize !== void 0 && (i.gapSize = this.gapSize), this.scale !== void 0 && (i.scale = this.scale), this.dithering === !0 && (i.dithering = !0), this.alphaTest > 0 && (i.alphaTest = this.alphaTest), this.alphaHash === !0 && (i.alphaHash = !0), this.alphaToCoverage === !0 && (i.alphaToCoverage = !0), this.premultipliedAlpha === !0 && (i.premultipliedAlpha = !0), this.forceSinglePass === !0 && (i.forceSinglePass = !0), this.wireframe === !0 && (i.wireframe = !0), this.wireframeLinewidth > 1 && (i.wireframeLinewidth = this.wireframeLinewidth), this.wireframeLinecap !== "round" && (i.wireframeLinecap = this.wireframeLinecap), this.wireframeLinejoin !== "round" && (i.wireframeLinejoin = this.wireframeLinejoin), this.flatShading === !0 && (i.flatShading = !0), this.visible === !1 && (i.visible = !1), this.toneMapped === !1 && (i.toneMapped = !1), this.fog === !1 && (i.fog = !1), Object.keys(this.userData).length > 0 && (i.userData = this.userData);
    function n(s) {
      const a = [];
      for (const o in s) {
        const l = s[o];
        delete l.metadata, a.push(l);
      }
      return a;
    }
    if (t) {
      const s = n(e.textures), a = n(e.images);
      s.length > 0 && (i.textures = s), a.length > 0 && (i.images = a);
    }
    return i;
  }
  /**
   * Returns a new material with copied values from this instance.
   *
   * @return {Material} A clone of this instance.
   */
  clone() {
    return new this.constructor().copy(this);
  }
  /**
   * Copies the values of the given material to this instance.
   *
   * @param {Material} source - The material to copy.
   * @return {Material} A reference to this instance.
   */
  copy(e) {
    this.name = e.name, this.blending = e.blending, this.side = e.side, this.vertexColors = e.vertexColors, this.opacity = e.opacity, this.transparent = e.transparent, this.blendSrc = e.blendSrc, this.blendDst = e.blendDst, this.blendEquation = e.blendEquation, this.blendSrcAlpha = e.blendSrcAlpha, this.blendDstAlpha = e.blendDstAlpha, this.blendEquationAlpha = e.blendEquationAlpha, this.blendColor.copy(e.blendColor), this.blendAlpha = e.blendAlpha, this.depthFunc = e.depthFunc, this.depthTest = e.depthTest, this.depthWrite = e.depthWrite, this.stencilWriteMask = e.stencilWriteMask, this.stencilFunc = e.stencilFunc, this.stencilRef = e.stencilRef, this.stencilFuncMask = e.stencilFuncMask, this.stencilFail = e.stencilFail, this.stencilZFail = e.stencilZFail, this.stencilZPass = e.stencilZPass, this.stencilWrite = e.stencilWrite;
    const t = e.clippingPlanes;
    let i = null;
    if (t !== null) {
      const n = t.length;
      i = new Array(n);
      for (let s = 0; s !== n; ++s)
        i[s] = t[s].clone();
    }
    return this.clippingPlanes = i, this.clipIntersection = e.clipIntersection, this.clipShadows = e.clipShadows, this.shadowSide = e.shadowSide, this.colorWrite = e.colorWrite, this.precision = e.precision, this.polygonOffset = e.polygonOffset, this.polygonOffsetFactor = e.polygonOffsetFactor, this.polygonOffsetUnits = e.polygonOffsetUnits, this.dithering = e.dithering, this.alphaTest = e.alphaTest, this.alphaHash = e.alphaHash, this.alphaToCoverage = e.alphaToCoverage, this.premultipliedAlpha = e.premultipliedAlpha, this.forceSinglePass = e.forceSinglePass, this.visible = e.visible, this.toneMapped = e.toneMapped, this.userData = JSON.parse(JSON.stringify(e.userData)), this;
  }
  /**
   * Frees the GPU-related resources allocated by this instance. Call this
   * method whenever this instance is no longer used in your app.
   *
   * @fires Material#dispose
   */
  dispose() {
    this.dispatchEvent({ type: "dispose" });
  }
  /**
   * Setting this property to `true` indicates the engine the material
   * needs to be recompiled.
   *
   * @type {boolean}
   * @default false
   * @param {boolean} value
   */
  set needsUpdate(e) {
    e === !0 && this.version++;
  }
}
class Ht extends qt {
  /**
   * Constructs a new mesh basic material.
   *
   * @param {Object} [parameters] - An object with one or more properties
   * defining the material's appearance. Any property of the material
   * (including any property from inherited materials) can be passed
   * in here. Color values can be passed any type of value accepted
   * by {@link Color#set}.
   */
  constructor(e) {
    super(), this.isMeshBasicMaterial = !0, this.type = "MeshBasicMaterial", this.color = new oe(16777215), this.map = null, this.lightMap = null, this.lightMapIntensity = 1, this.aoMap = null, this.aoMapIntensity = 1, this.specularMap = null, this.alphaMap = null, this.envMap = null, this.envMapRotation = new Ai(), this.combine = xa, this.reflectivity = 1, this.refractionRatio = 0.98, this.wireframe = !1, this.wireframeLinewidth = 1, this.wireframeLinecap = "round", this.wireframeLinejoin = "round", this.fog = !0, this.setValues(e);
  }
  copy(e) {
    return super.copy(e), this.color.copy(e.color), this.map = e.map, this.lightMap = e.lightMap, this.lightMapIntensity = e.lightMapIntensity, this.aoMap = e.aoMap, this.aoMapIntensity = e.aoMapIntensity, this.specularMap = e.specularMap, this.alphaMap = e.alphaMap, this.envMap = e.envMap, this.envMapRotation.copy(e.envMapRotation), this.combine = e.combine, this.reflectivity = e.reflectivity, this.refractionRatio = e.refractionRatio, this.wireframe = e.wireframe, this.wireframeLinewidth = e.wireframeLinewidth, this.wireframeLinecap = e.wireframeLinecap, this.wireframeLinejoin = e.wireframeLinejoin, this.fog = e.fog, this;
  }
}
const pn = /* @__PURE__ */ Z_();
function Z_() {
  const r = new ArrayBuffer(4), e = new Float32Array(r), t = new Uint32Array(r), i = new Uint32Array(512), n = new Uint32Array(512);
  for (let l = 0; l < 256; ++l) {
    const c = l - 127;
    c < -27 ? (i[l] = 0, i[l | 256] = 32768, n[l] = 24, n[l | 256] = 24) : c < -14 ? (i[l] = 1024 >> -c - 14, i[l | 256] = 1024 >> -c - 14 | 32768, n[l] = -c - 1, n[l | 256] = -c - 1) : c <= 15 ? (i[l] = c + 15 << 10, i[l | 256] = c + 15 << 10 | 32768, n[l] = 13, n[l | 256] = 13) : c < 128 ? (i[l] = 31744, i[l | 256] = 64512, n[l] = 24, n[l | 256] = 24) : (i[l] = 31744, i[l | 256] = 64512, n[l] = 13, n[l | 256] = 13);
  }
  const s = new Uint32Array(2048), a = new Uint32Array(64), o = new Uint32Array(64);
  for (let l = 1; l < 1024; ++l) {
    let c = l << 13, h = 0;
    for (; !(c & 8388608); )
      c <<= 1, h -= 8388608;
    c &= -8388609, h += 947912704, s[l] = c | h;
  }
  for (let l = 1024; l < 2048; ++l)
    s[l] = 939524096 + (l - 1024 << 13);
  for (let l = 1; l < 31; ++l)
    a[l] = l << 23;
  a[31] = 1199570944, a[32] = 2147483648;
  for (let l = 33; l < 63; ++l)
    a[l] = 2147483648 + (l - 32 << 23);
  a[63] = 3347054592;
  for (let l = 1; l < 64; ++l)
    l !== 32 && (o[l] = 1024);
  return {
    floatView: e,
    uint32View: t,
    baseTable: i,
    shiftTable: n,
    mantissaTable: s,
    exponentTable: a,
    offsetTable: o
  };
}
function ui(r) {
  Math.abs(r) > 65504 && console.warn("THREE.DataUtils.toHalfFloat(): Value out of range."), r = Fe(r, -65504, 65504), pn.floatView[0] = r;
  const e = pn.uint32View[0], t = e >> 23 & 511;
  return pn.baseTable[t] + ((e & 8388607) >> pn.shiftTable[t]);
}
function Gr(r) {
  const e = r >> 10;
  return pn.uint32View[0] = pn.mantissaTable[pn.offsetTable[e] + (r & 1023)] + pn.exponentTable[e], pn.floatView[0];
}
class Y_ {
  /**
   * Returns a half precision floating point value (FP16) from the given single
   * precision floating point value (FP32).
   *
   * @param {number} val - A single precision floating point value.
   * @return {number} The FP16 value.
   */
  static toHalfFloat(e) {
    return ui(e);
  }
  /**
   * Returns a single precision floating point value (FP32) from the given half
   * precision floating point value (FP16).
   *
   * @param {number} val - A half precision floating point value.
   * @return {number} The FP32 value.
   */
  static fromHalfFloat(e) {
    return Gr(e);
  }
}
const Dt = /* @__PURE__ */ new b(), Ba = /* @__PURE__ */ new H();
let j_ = 0;
class it {
  /**
   * Constructs a new buffer attribute.
   *
   * @param {TypedArray} array - The array holding the attribute data.
   * @param {number} itemSize - The item size.
   * @param {boolean} [normalized=false] - Whether the data are normalized or not.
   */
  constructor(e, t, i = !1) {
    if (Array.isArray(e))
      throw new TypeError("THREE.BufferAttribute: array should be a Typed Array.");
    this.isBufferAttribute = !0, Object.defineProperty(this, "id", { value: j_++ }), this.name = "", this.array = e, this.itemSize = t, this.count = e !== void 0 ? e.length / t : 0, this.normalized = i, this.usage = ha, this.updateRanges = [], this.gpuType = mi, this.version = 0;
  }
  /**
   * A callback function that is executed after the renderer has transferred the attribute
   * array data to the GPU.
   */
  onUploadCallback() {
  }
  /**
   * Flag to indicate that this attribute has changed and should be re-sent to
   * the GPU. Set this to `true` when you modify the value of the array.
   *
   * @type {number}
   * @default false
   * @param {boolean} value
   */
  set needsUpdate(e) {
    e === !0 && this.version++;
  }
  /**
   * Sets the usage of this buffer attribute.
   *
   * @param {(StaticDrawUsage|DynamicDrawUsage|StreamDrawUsage|StaticReadUsage|DynamicReadUsage|StreamReadUsage|StaticCopyUsage|DynamicCopyUsage|StreamCopyUsage)} value - The usage to set.
   * @return {BufferAttribute} A reference to this buffer attribute.
   */
  setUsage(e) {
    return this.usage = e, this;
  }
  /**
   * Adds a range of data in the data array to be updated on the GPU.
   *
   * @param {number} start - Position at which to start update.
   * @param {number} count - The number of components to update.
   */
  addUpdateRange(e, t) {
    this.updateRanges.push({ start: e, count: t });
  }
  /**
   * Clears the update ranges.
   */
  clearUpdateRanges() {
    this.updateRanges.length = 0;
  }
  /**
   * Copies the values of the given buffer attribute to this instance.
   *
   * @param {BufferAttribute} source - The buffer attribute to copy.
   * @return {BufferAttribute} A reference to this instance.
   */
  copy(e) {
    return this.name = e.name, this.array = new e.array.constructor(e.array), this.itemSize = e.itemSize, this.count = e.count, this.normalized = e.normalized, this.usage = e.usage, this.gpuType = e.gpuType, this;
  }
  /**
   * Copies a vector from the given buffer attribute to this one. The start
   * and destination position in the attribute buffers are represented by the
   * given indices.
   *
   * @param {number} index1 - The destination index into this buffer attribute.
   * @param {BufferAttribute} attribute - The buffer attribute to copy from.
   * @param {number} index2 - The source index into the given buffer attribute.
   * @return {BufferAttribute} A reference to this instance.
   */
  copyAt(e, t, i) {
    e *= this.itemSize, i *= t.itemSize;
    for (let n = 0, s = this.itemSize; n < s; n++)
      this.array[e + n] = t.array[i + n];
    return this;
  }
  /**
   * Copies the given array data into this buffer attribute.
   *
   * @param {(TypedArray|Array)} array - The array to copy.
   * @return {BufferAttribute} A reference to this instance.
   */
  copyArray(e) {
    return this.array.set(e), this;
  }
  /**
   * Applies the given 3x3 matrix to the given attribute. Works with
   * item size `2` and `3`.
   *
   * @param {Matrix3} m - The matrix to apply.
   * @return {BufferAttribute} A reference to this instance.
   */
  applyMatrix3(e) {
    if (this.itemSize === 2)
      for (let t = 0, i = this.count; t < i; t++)
        Ba.fromBufferAttribute(this, t), Ba.applyMatrix3(e), this.setXY(t, Ba.x, Ba.y);
    else if (this.itemSize === 3)
      for (let t = 0, i = this.count; t < i; t++)
        Dt.fromBufferAttribute(this, t), Dt.applyMatrix3(e), this.setXYZ(t, Dt.x, Dt.y, Dt.z);
    return this;
  }
  /**
   * Applies the given 4x4 matrix to the given attribute. Only works with
   * item size `3`.
   *
   * @param {Matrix4} m - The matrix to apply.
   * @return {BufferAttribute} A reference to this instance.
   */
  applyMatrix4(e) {
    for (let t = 0, i = this.count; t < i; t++)
      Dt.fromBufferAttribute(this, t), Dt.applyMatrix4(e), this.setXYZ(t, Dt.x, Dt.y, Dt.z);
    return this;
  }
  /**
   * Applies the given 3x3 normal matrix to the given attribute. Only works with
   * item size `3`.
   *
   * @param {Matrix3} m - The normal matrix to apply.
   * @return {BufferAttribute} A reference to this instance.
   */
  applyNormalMatrix(e) {
    for (let t = 0, i = this.count; t < i; t++)
      Dt.fromBufferAttribute(this, t), Dt.applyNormalMatrix(e), this.setXYZ(t, Dt.x, Dt.y, Dt.z);
    return this;
  }
  /**
   * Applies the given 4x4 matrix to the given attribute. Only works with
   * item size `3` and with direction vectors.
   *
   * @param {Matrix4} m - The matrix to apply.
   * @return {BufferAttribute} A reference to this instance.
   */
  transformDirection(e) {
    for (let t = 0, i = this.count; t < i; t++)
      Dt.fromBufferAttribute(this, t), Dt.transformDirection(e), this.setXYZ(t, Dt.x, Dt.y, Dt.z);
    return this;
  }
  /**
   * Sets the given array data in the buffer attribute.
   *
   * @param {(TypedArray|Array)} value - The array data to set.
   * @param {number} [offset=0] - The offset in this buffer attribute's array.
   * @return {BufferAttribute} A reference to this instance.
   */
  set(e, t = 0) {
    return this.array.set(e, t), this;
  }
  /**
   * Returns the given component of the vector at the given index.
   *
   * @param {number} index - The index into the buffer attribute.
   * @param {number} component - The component index.
   * @return {number} The returned value.
   */
  getComponent(e, t) {
    let i = this.array[e * this.itemSize + t];
    return this.normalized && (i = ai(i, this.array)), i;
  }
  /**
   * Sets the given value to the given component of the vector at the given index.
   *
   * @param {number} index - The index into the buffer attribute.
   * @param {number} component - The component index.
   * @param {number} value - The value to set.
   * @return {BufferAttribute} A reference to this instance.
   */
  setComponent(e, t, i) {
    return this.normalized && (i = Xe(i, this.array)), this.array[e * this.itemSize + t] = i, this;
  }
  /**
   * Returns the x component of the vector at the given index.
   *
   * @param {number} index - The index into the buffer attribute.
   * @return {number} The x component.
   */
  getX(e) {
    let t = this.array[e * this.itemSize];
    return this.normalized && (t = ai(t, this.array)), t;
  }
  /**
   * Sets the x component of the vector at the given index.
   *
   * @param {number} index - The index into the buffer attribute.
   * @param {number} x - The value to set.
   * @return {BufferAttribute} A reference to this instance.
   */
  setX(e, t) {
    return this.normalized && (t = Xe(t, this.array)), this.array[e * this.itemSize] = t, this;
  }
  /**
   * Returns the y component of the vector at the given index.
   *
   * @param {number} index - The index into the buffer attribute.
   * @return {number} The y component.
   */
  getY(e) {
    let t = this.array[e * this.itemSize + 1];
    return this.normalized && (t = ai(t, this.array)), t;
  }
  /**
   * Sets the y component of the vector at the given index.
   *
   * @param {number} index - The index into the buffer attribute.
   * @param {number} y - The value to set.
   * @return {BufferAttribute} A reference to this instance.
   */
  setY(e, t) {
    return this.normalized && (t = Xe(t, this.array)), this.array[e * this.itemSize + 1] = t, this;
  }
  /**
   * Returns the z component of the vector at the given index.
   *
   * @param {number} index - The index into the buffer attribute.
   * @return {number} The z component.
   */
  getZ(e) {
    let t = this.array[e * this.itemSize + 2];
    return this.normalized && (t = ai(t, this.array)), t;
  }
  /**
   * Sets the z component of the vector at the given index.
   *
   * @param {number} index - The index into the buffer attribute.
   * @param {number} z - The value to set.
   * @return {BufferAttribute} A reference to this instance.
   */
  setZ(e, t) {
    return this.normalized && (t = Xe(t, this.array)), this.array[e * this.itemSize + 2] = t, this;
  }
  /**
   * Returns the w component of the vector at the given index.
   *
   * @param {number} index - The index into the buffer attribute.
   * @return {number} The w component.
   */
  getW(e) {
    let t = this.array[e * this.itemSize + 3];
    return this.normalized && (t = ai(t, this.array)), t;
  }
  /**
   * Sets the w component of the vector at the given index.
   *
   * @param {number} index - The index into the buffer attribute.
   * @param {number} w - The value to set.
   * @return {BufferAttribute} A reference to this instance.
   */
  setW(e, t) {
    return this.normalized && (t = Xe(t, this.array)), this.array[e * this.itemSize + 3] = t, this;
  }
  /**
   * Sets the x and y component of the vector at the given index.
   *
   * @param {number} index - The index into the buffer attribute.
   * @param {number} x - The value for the x component to set.
   * @param {number} y - The value for the y component to set.
   * @return {BufferAttribute} A reference to this instance.
   */
  setXY(e, t, i) {
    return e *= this.itemSize, this.normalized && (t = Xe(t, this.array), i = Xe(i, this.array)), this.array[e + 0] = t, this.array[e + 1] = i, this;
  }
  /**
   * Sets the x, y and z component of the vector at the given index.
   *
   * @param {number} index - The index into the buffer attribute.
   * @param {number} x - The value for the x component to set.
   * @param {number} y - The value for the y component to set.
   * @param {number} z - The value for the z component to set.
   * @return {BufferAttribute} A reference to this instance.
   */
  setXYZ(e, t, i, n) {
    return e *= this.itemSize, this.normalized && (t = Xe(t, this.array), i = Xe(i, this.array), n = Xe(n, this.array)), this.array[e + 0] = t, this.array[e + 1] = i, this.array[e + 2] = n, this;
  }
  /**
   * Sets the x, y, z and w component of the vector at the given index.
   *
   * @param {number} index - The index into the buffer attribute.
   * @param {number} x - The value for the x component to set.
   * @param {number} y - The value for the y component to set.
   * @param {number} z - The value for the z component to set.
   * @param {number} w - The value for the w component to set.
   * @return {BufferAttribute} A reference to this instance.
   */
  setXYZW(e, t, i, n, s) {
    return e *= this.itemSize, this.normalized && (t = Xe(t, this.array), i = Xe(i, this.array), n = Xe(n, this.array), s = Xe(s, this.array)), this.array[e + 0] = t, this.array[e + 1] = i, this.array[e + 2] = n, this.array[e + 3] = s, this;
  }
  /**
   * Sets the given callback function that is executed after the Renderer has transferred
   * the attribute array data to the GPU. Can be used to perform clean-up operations after
   * the upload when attribute data are not needed anymore on the CPU side.
   *
   * @param {Function} callback - The `onUpload()` callback.
   * @return {BufferAttribute} A reference to this instance.
   */
  onUpload(e) {
    return this.onUploadCallback = e, this;
  }
  /**
   * Returns a new buffer attribute with copied values from this instance.
   *
   * @return {BufferAttribute} A clone of this instance.
   */
  clone() {
    return new this.constructor(this.array, this.itemSize).copy(this);
  }
  /**
   * Serializes the buffer attribute into JSON.
   *
   * @return {Object} A JSON object representing the serialized buffer attribute.
   */
  toJSON() {
    const e = {
      itemSize: this.itemSize,
      type: this.array.constructor.name,
      array: Array.from(this.array),
      normalized: this.normalized
    };
    return this.name !== "" && (e.name = this.name), this.usage !== ha && (e.usage = this.usage), e;
  }
}
class $_ extends it {
  /**
   * Constructs a new buffer attribute.
   *
   * @param {(Array<number>|Int8Array)} array - The array holding the attribute data.
   * @param {number} itemSize - The item size.
   * @param {boolean} [normalized=false] - Whether the data are normalized or not.
   */
  constructor(e, t, i) {
    super(new Int8Array(e), t, i);
  }
}
class K_ extends it {
  /**
   * Constructs a new buffer attribute.
   *
   * @param {(Array<number>|Uint8Array)} array - The array holding the attribute data.
   * @param {number} itemSize - The item size.
   * @param {boolean} [normalized=false] - Whether the data are normalized or not.
   */
  constructor(e, t, i) {
    super(new Uint8Array(e), t, i);
  }
}
class J_ extends it {
  /**
   * Constructs a new buffer attribute.
   *
   * @param {(Array<number>|Uint8ClampedArray)} array - The array holding the attribute data.
   * @param {number} itemSize - The item size.
   * @param {boolean} [normalized=false] - Whether the data are normalized or not.
   */
  constructor(e, t, i) {
    super(new Uint8ClampedArray(e), t, i);
  }
}
class Q_ extends it {
  /**
   * Constructs a new buffer attribute.
   *
   * @param {(Array<number>|Int16Array)} array - The array holding the attribute data.
   * @param {number} itemSize - The item size.
   * @param {boolean} [normalized=false] - Whether the data are normalized or not.
   */
  constructor(e, t, i) {
    super(new Int16Array(e), t, i);
  }
}
class hd extends it {
  /**
   * Constructs a new buffer attribute.
   *
   * @param {(Array<number>|Uint16Array)} array - The array holding the attribute data.
   * @param {number} itemSize - The item size.
   * @param {boolean} [normalized=false] - Whether the data are normalized or not.
   */
  constructor(e, t, i) {
    super(new Uint16Array(e), t, i);
  }
}
class ey extends it {
  /**
   * Constructs a new buffer attribute.
   *
   * @param {(Array<number>|Int32Array)} array - The array holding the attribute data.
   * @param {number} itemSize - The item size.
   * @param {boolean} [normalized=false] - Whether the data are normalized or not.
   */
  constructor(e, t, i) {
    super(new Int32Array(e), t, i);
  }
}
class dd extends it {
  /**
   * Constructs a new buffer attribute.
   *
   * @param {(Array<number>|Uint32Array)} array - The array holding the attribute data.
   * @param {number} itemSize - The item size.
   * @param {boolean} [normalized=false] - Whether the data are normalized or not.
   */
  constructor(e, t, i) {
    super(new Uint32Array(e), t, i);
  }
}
class ty extends it {
  /**
   * Constructs a new buffer attribute.
   *
   * @param {(Array<number>|Uint16Array)} array - The array holding the attribute data.
   * @param {number} itemSize - The item size.
   * @param {boolean} [normalized=false] - Whether the data are normalized or not.
   */
  constructor(e, t, i) {
    super(new Uint16Array(e), t, i), this.isFloat16BufferAttribute = !0;
  }
  getX(e) {
    let t = Gr(this.array[e * this.itemSize]);
    return this.normalized && (t = ai(t, this.array)), t;
  }
  setX(e, t) {
    return this.normalized && (t = Xe(t, this.array)), this.array[e * this.itemSize] = ui(t), this;
  }
  getY(e) {
    let t = Gr(this.array[e * this.itemSize + 1]);
    return this.normalized && (t = ai(t, this.array)), t;
  }
  setY(e, t) {
    return this.normalized && (t = Xe(t, this.array)), this.array[e * this.itemSize + 1] = ui(t), this;
  }
  getZ(e) {
    let t = Gr(this.array[e * this.itemSize + 2]);
    return this.normalized && (t = ai(t, this.array)), t;
  }
  setZ(e, t) {
    return this.normalized && (t = Xe(t, this.array)), this.array[e * this.itemSize + 2] = ui(t), this;
  }
  getW(e) {
    let t = Gr(this.array[e * this.itemSize + 3]);
    return this.normalized && (t = ai(t, this.array)), t;
  }
  setW(e, t) {
    return this.normalized && (t = Xe(t, this.array)), this.array[e * this.itemSize + 3] = ui(t), this;
  }
  setXY(e, t, i) {
    return e *= this.itemSize, this.normalized && (t = Xe(t, this.array), i = Xe(i, this.array)), this.array[e + 0] = ui(t), this.array[e + 1] = ui(i), this;
  }
  setXYZ(e, t, i, n) {
    return e *= this.itemSize, this.normalized && (t = Xe(t, this.array), i = Xe(i, this.array), n = Xe(n, this.array)), this.array[e + 0] = ui(t), this.array[e + 1] = ui(i), this.array[e + 2] = ui(n), this;
  }
  setXYZW(e, t, i, n, s) {
    return e *= this.itemSize, this.normalized && (t = Xe(t, this.array), i = Xe(i, this.array), n = Xe(n, this.array), s = Xe(s, this.array)), this.array[e + 0] = ui(t), this.array[e + 1] = ui(i), this.array[e + 2] = ui(n), this.array[e + 3] = ui(s), this;
  }
}
class ve extends it {
  /**
   * Constructs a new buffer attribute.
   *
   * @param {(Array<number>|Float32Array)} array - The array holding the attribute data.
   * @param {number} itemSize - The item size.
   * @param {boolean} [normalized=false] - Whether the data are normalized or not.
   */
  constructor(e, t, i) {
    super(new Float32Array(e), t, i);
  }
}
let iy = 0;
const Li = /* @__PURE__ */ new Ne(), Bc = /* @__PURE__ */ new tt(), ks = /* @__PURE__ */ new b(), xi = /* @__PURE__ */ new Tt(), Pr = /* @__PURE__ */ new Tt(), Bt = /* @__PURE__ */ new b();
class Ue extends sn {
  /**
   * Constructs a new geometry.
   */
  constructor() {
    super(), this.isBufferGeometry = !0, Object.defineProperty(this, "id", { value: iy++ }), this.uuid = Ti(), this.name = "", this.type = "BufferGeometry", this.index = null, this.indirect = null, this.attributes = {}, this.morphAttributes = {}, this.morphTargetsRelative = !1, this.groups = [], this.boundingBox = null, this.boundingSphere = null, this.drawRange = { start: 0, count: 1 / 0 }, this.userData = {};
  }
  /**
   * Returns the index of this geometry.
   *
   * @return {?BufferAttribute} The index. Returns `null` if no index is defined.
   */
  getIndex() {
    return this.index;
  }
  /**
   * Sets the given index to this geometry.
   *
   * @param {Array<number>|BufferAttribute} index - The index to set.
   * @return {BufferGeometry} A reference to this instance.
   */
  setIndex(e) {
    return Array.isArray(e) ? this.index = new (lm(e) ? dd : hd)(e, 1) : this.index = e, this;
  }
  /**
   * Sets the given indirect attribute to this geometry.
   *
   * @param {BufferAttribute} indirect - The attribute holding indirect draw calls.
   * @return {BufferGeometry} A reference to this instance.
   */
  setIndirect(e) {
    return this.indirect = e, this;
  }
  /**
   * Returns the indirect attribute of this geometry.
   *
   * @return {?BufferAttribute} The indirect attribute. Returns `null` if no indirect attribute is defined.
   */
  getIndirect() {
    return this.indirect;
  }
  /**
   * Returns the buffer attribute for the given name.
   *
   * @param {string} name - The attribute name.
   * @return {BufferAttribute|InterleavedBufferAttribute|undefined} The buffer attribute.
   * Returns `undefined` if not attribute has been found.
   */
  getAttribute(e) {
    return this.attributes[e];
  }
  /**
   * Sets the given attribute for the given name.
   *
   * @param {string} name - The attribute name.
   * @param {BufferAttribute|InterleavedBufferAttribute} attribute - The attribute to set.
   * @return {BufferGeometry} A reference to this instance.
   */
  setAttribute(e, t) {
    return this.attributes[e] = t, this;
  }
  /**
   * Deletes the attribute for the given name.
   *
   * @param {string} name - The attribute name to delete.
   * @return {BufferGeometry} A reference to this instance.
   */
  deleteAttribute(e) {
    return delete this.attributes[e], this;
  }
  /**
   * Returns `true` if this geometry has an attribute for the given name.
   *
   * @param {string} name - The attribute name.
   * @return {boolean} Whether this geometry has an attribute for the given name or not.
   */
  hasAttribute(e) {
    return this.attributes[e] !== void 0;
  }
  /**
   * Adds a group to this geometry.
   *
   * @param {number} start - The first element in this draw call. That is the first
   * vertex for non-indexed geometry, otherwise the first triangle index.
   * @param {number} count - Specifies how many vertices (or indices) are part of this group.
   * @param {number} [materialIndex=0] - The material array index to use.
   */
  addGroup(e, t, i = 0) {
    this.groups.push({
      start: e,
      count: t,
      materialIndex: i
    });
  }
  /**
   * Clears all groups.
   */
  clearGroups() {
    this.groups = [];
  }
  /**
   * Sets the draw range for this geometry.
   *
   * @param {number} start - The first vertex for non-indexed geometry, otherwise the first triangle index.
   * @param {number} count - For non-indexed BufferGeometry, `count` is the number of vertices to render.
   * For indexed BufferGeometry, `count` is the number of indices to render.
   */
  setDrawRange(e, t) {
    this.drawRange.start = e, this.drawRange.count = t;
  }
  /**
   * Applies the given 4x4 transformation matrix to the geometry.
   *
   * @param {Matrix4} matrix - The matrix to apply.
   * @return {BufferGeometry} A reference to this instance.
   */
  applyMatrix4(e) {
    const t = this.attributes.position;
    t !== void 0 && (t.applyMatrix4(e), t.needsUpdate = !0);
    const i = this.attributes.normal;
    if (i !== void 0) {
      const s = new He().getNormalMatrix(e);
      i.applyNormalMatrix(s), i.needsUpdate = !0;
    }
    const n = this.attributes.tangent;
    return n !== void 0 && (n.transformDirection(e), n.needsUpdate = !0), this.boundingBox !== null && this.computeBoundingBox(), this.boundingSphere !== null && this.computeBoundingSphere(), this;
  }
  /**
   * Applies the rotation represented by the Quaternion to the geometry.
   *
   * @param {Quaternion} q - The Quaternion to apply.
   * @return {BufferGeometry} A reference to this instance.
   */
  applyQuaternion(e) {
    return Li.makeRotationFromQuaternion(e), this.applyMatrix4(Li), this;
  }
  /**
   * Rotates the geometry about the X axis. This is typically done as a one time
   * operation, and not during a loop. Use {@link Object3D#rotation} for typical
   * real-time mesh rotation.
   *
   * @param {number} angle - The angle in radians.
   * @return {BufferGeometry} A reference to this instance.
   */
  rotateX(e) {
    return Li.makeRotationX(e), this.applyMatrix4(Li), this;
  }
  /**
   * Rotates the geometry about the Y axis. This is typically done as a one time
   * operation, and not during a loop. Use {@link Object3D#rotation} for typical
   * real-time mesh rotation.
   *
   * @param {number} angle - The angle in radians.
   * @return {BufferGeometry} A reference to this instance.
   */
  rotateY(e) {
    return Li.makeRotationY(e), this.applyMatrix4(Li), this;
  }
  /**
   * Rotates the geometry about the Z axis. This is typically done as a one time
   * operation, and not during a loop. Use {@link Object3D#rotation} for typical
   * real-time mesh rotation.
   *
   * @param {number} angle - The angle in radians.
   * @return {BufferGeometry} A reference to this instance.
   */
  rotateZ(e) {
    return Li.makeRotationZ(e), this.applyMatrix4(Li), this;
  }
  /**
   * Translates the geometry. This is typically done as a one time
   * operation, and not during a loop. Use {@link Object3D#position} for typical
   * real-time mesh rotation.
   *
   * @param {number} x - The x offset.
   * @param {number} y - The y offset.
   * @param {number} z - The z offset.
   * @return {BufferGeometry} A reference to this instance.
   */
  translate(e, t, i) {
    return Li.makeTranslation(e, t, i), this.applyMatrix4(Li), this;
  }
  /**
   * Scales the geometry. This is typically done as a one time
   * operation, and not during a loop. Use {@link Object3D#scale} for typical
   * real-time mesh rotation.
   *
   * @param {number} x - The x scale.
   * @param {number} y - The y scale.
   * @param {number} z - The z scale.
   * @return {BufferGeometry} A reference to this instance.
   */
  scale(e, t, i) {
    return Li.makeScale(e, t, i), this.applyMatrix4(Li), this;
  }
  /**
   * Rotates the geometry to face a point in 3D space. This is typically done as a one time
   * operation, and not during a loop. Use {@link Object3D#lookAt} for typical
   * real-time mesh rotation.
   *
   * @param {Vector3} vector - The target point.
   * @return {BufferGeometry} A reference to this instance.
   */
  lookAt(e) {
    return Bc.lookAt(e), Bc.updateMatrix(), this.applyMatrix4(Bc.matrix), this;
  }
  /**
   * Center the geometry based on its bounding box.
   *
   * @return {BufferGeometry} A reference to this instance.
   */
  center() {
    return this.computeBoundingBox(), this.boundingBox.getCenter(ks).negate(), this.translate(ks.x, ks.y, ks.z), this;
  }
  /**
   * Defines a geometry by creating a `position` attribute based on the given array of points. The array
   * can hold 2D or 3D vectors. When using two-dimensional data, the `z` coordinate for all vertices is
   * set to `0`.
   *
   * If the method is used with an existing `position` attribute, the vertex data are overwritten with the
   * data from the array. The length of the array must match the vertex count.
   *
   * @param {Array<Vector2>|Array<Vector3>} points - The points.
   * @return {BufferGeometry} A reference to this instance.
   */
  setFromPoints(e) {
    const t = this.getAttribute("position");
    if (t === void 0) {
      const i = [];
      for (let n = 0, s = e.length; n < s; n++) {
        const a = e[n];
        i.push(a.x, a.y, a.z || 0);
      }
      this.setAttribute("position", new ve(i, 3));
    } else {
      const i = Math.min(e.length, t.count);
      for (let n = 0; n < i; n++) {
        const s = e[n];
        t.setXYZ(n, s.x, s.y, s.z || 0);
      }
      e.length > t.count && console.warn("THREE.BufferGeometry: Buffer size too small for points data. Use .dispose() and create a new geometry."), t.needsUpdate = !0;
    }
    return this;
  }
  /**
   * Computes the bounding box of the geometry, and updates the `boundingBox` member.
   * The bounding box is not computed by the engine; it must be computed by your app.
   * You may need to recompute the bounding box if the geometry vertices are modified.
   */
  computeBoundingBox() {
    this.boundingBox === null && (this.boundingBox = new Tt());
    const e = this.attributes.position, t = this.morphAttributes.position;
    if (e && e.isGLBufferAttribute) {
      console.error("THREE.BufferGeometry.computeBoundingBox(): GLBufferAttribute requires a manual bounding box.", this), this.boundingBox.set(
        new b(-1 / 0, -1 / 0, -1 / 0),
        new b(1 / 0, 1 / 0, 1 / 0)
      );
      return;
    }
    if (e !== void 0) {
      if (this.boundingBox.setFromBufferAttribute(e), t)
        for (let i = 0, n = t.length; i < n; i++) {
          const s = t[i];
          xi.setFromBufferAttribute(s), this.morphTargetsRelative ? (Bt.addVectors(this.boundingBox.min, xi.min), this.boundingBox.expandByPoint(Bt), Bt.addVectors(this.boundingBox.max, xi.max), this.boundingBox.expandByPoint(Bt)) : (this.boundingBox.expandByPoint(xi.min), this.boundingBox.expandByPoint(xi.max));
        }
    } else
      this.boundingBox.makeEmpty();
    (isNaN(this.boundingBox.min.x) || isNaN(this.boundingBox.min.y) || isNaN(this.boundingBox.min.z)) && console.error('THREE.BufferGeometry.computeBoundingBox(): Computed min/max have NaN values. The "position" attribute is likely to have NaN values.', this);
  }
  /**
   * Computes the bounding sphere of the geometry, and updates the `boundingSphere` member.
   * The engine automatically computes the bounding sphere when it is needed, e.g., for ray casting or view frustum culling.
   * You may need to recompute the bounding sphere if the geometry vertices are modified.
   */
  computeBoundingSphere() {
    this.boundingSphere === null && (this.boundingSphere = new Lt());
    const e = this.attributes.position, t = this.morphAttributes.position;
    if (e && e.isGLBufferAttribute) {
      console.error("THREE.BufferGeometry.computeBoundingSphere(): GLBufferAttribute requires a manual bounding sphere.", this), this.boundingSphere.set(new b(), 1 / 0);
      return;
    }
    if (e) {
      const i = this.boundingSphere.center;
      if (xi.setFromBufferAttribute(e), t)
        for (let s = 0, a = t.length; s < a; s++) {
          const o = t[s];
          Pr.setFromBufferAttribute(o), this.morphTargetsRelative ? (Bt.addVectors(xi.min, Pr.min), xi.expandByPoint(Bt), Bt.addVectors(xi.max, Pr.max), xi.expandByPoint(Bt)) : (xi.expandByPoint(Pr.min), xi.expandByPoint(Pr.max));
        }
      xi.getCenter(i);
      let n = 0;
      for (let s = 0, a = e.count; s < a; s++)
        Bt.fromBufferAttribute(e, s), n = Math.max(n, i.distanceToSquared(Bt));
      if (t)
        for (let s = 0, a = t.length; s < a; s++) {
          const o = t[s], l = this.morphTargetsRelative;
          for (let c = 0, h = o.count; c < h; c++)
            Bt.fromBufferAttribute(o, c), l && (ks.fromBufferAttribute(e, c), Bt.add(ks)), n = Math.max(n, i.distanceToSquared(Bt));
        }
      this.boundingSphere.radius = Math.sqrt(n), isNaN(this.boundingSphere.radius) && console.error('THREE.BufferGeometry.computeBoundingSphere(): Computed radius is NaN. The "position" attribute is likely to have NaN values.', this);
    }
  }
  /**
   * Calculates and adds a tangent attribute to this geometry.
   *
   * The computation is only supported for indexed geometries and if position, normal, and uv attributes
   * are defined. When using a tangent space normal map, prefer the MikkTSpace algorithm provided by
   * {@link BufferGeometryUtils#computeMikkTSpaceTangents} instead.
   */
  computeTangents() {
    const e = this.index, t = this.attributes;
    if (e === null || t.position === void 0 || t.normal === void 0 || t.uv === void 0) {
      console.error("THREE.BufferGeometry: .computeTangents() failed. Missing required attributes (index, position, normal or uv)");
      return;
    }
    const i = t.position, n = t.normal, s = t.uv;
    this.hasAttribute("tangent") === !1 && this.setAttribute("tangent", new it(new Float32Array(4 * i.count), 4));
    const a = this.getAttribute("tangent"), o = [], l = [];
    for (let P = 0; P < i.count; P++)
      o[P] = new b(), l[P] = new b();
    const c = new b(), h = new b(), d = new b(), u = new H(), p = new H(), m = new H(), _ = new b(), g = new b();
    function f(P, E, w) {
      c.fromBufferAttribute(i, P), h.fromBufferAttribute(i, E), d.fromBufferAttribute(i, w), u.fromBufferAttribute(s, P), p.fromBufferAttribute(s, E), m.fromBufferAttribute(s, w), h.sub(c), d.sub(c), p.sub(u), m.sub(u);
      const L = 1 / (p.x * m.y - m.x * p.y);
      isFinite(L) && (_.copy(h).multiplyScalar(m.y).addScaledVector(d, -p.y).multiplyScalar(L), g.copy(d).multiplyScalar(p.x).addScaledVector(h, -m.x).multiplyScalar(L), o[P].add(_), o[E].add(_), o[w].add(_), l[P].add(g), l[E].add(g), l[w].add(g));
    }
    let v = this.groups;
    v.length === 0 && (v = [{
      start: 0,
      count: e.count
    }]);
    for (let P = 0, E = v.length; P < E; ++P) {
      const w = v[P], L = w.start, N = w.count;
      for (let B = L, W = L + N; B < W; B += 3)
        f(
          e.getX(B + 0),
          e.getX(B + 1),
          e.getX(B + 2)
        );
    }
    const x = new b(), y = new b(), A = new b(), S = new b();
    function C(P) {
      A.fromBufferAttribute(n, P), S.copy(A);
      const E = o[P];
      x.copy(E), x.sub(A.multiplyScalar(A.dot(E))).normalize(), y.crossVectors(S, E);
      const L = y.dot(l[P]) < 0 ? -1 : 1;
      a.setXYZW(P, x.x, x.y, x.z, L);
    }
    for (let P = 0, E = v.length; P < E; ++P) {
      const w = v[P], L = w.start, N = w.count;
      for (let B = L, W = L + N; B < W; B += 3)
        C(e.getX(B + 0)), C(e.getX(B + 1)), C(e.getX(B + 2));
    }
  }
  /**
   * Computes vertex normals for the given vertex data. For indexed geometries, the method sets
   * each vertex normal to be the average of the face normals of the faces that share that vertex.
   * For non-indexed geometries, vertices are not shared, and the method sets each vertex normal
   * to be the same as the face normal.
   */
  computeVertexNormals() {
    const e = this.index, t = this.getAttribute("position");
    if (t !== void 0) {
      let i = this.getAttribute("normal");
      if (i === void 0)
        i = new it(new Float32Array(t.count * 3), 3), this.setAttribute("normal", i);
      else
        for (let u = 0, p = i.count; u < p; u++)
          i.setXYZ(u, 0, 0, 0);
      const n = new b(), s = new b(), a = new b(), o = new b(), l = new b(), c = new b(), h = new b(), d = new b();
      if (e)
        for (let u = 0, p = e.count; u < p; u += 3) {
          const m = e.getX(u + 0), _ = e.getX(u + 1), g = e.getX(u + 2);
          n.fromBufferAttribute(t, m), s.fromBufferAttribute(t, _), a.fromBufferAttribute(t, g), h.subVectors(a, s), d.subVectors(n, s), h.cross(d), o.fromBufferAttribute(i, m), l.fromBufferAttribute(i, _), c.fromBufferAttribute(i, g), o.add(h), l.add(h), c.add(h), i.setXYZ(m, o.x, o.y, o.z), i.setXYZ(_, l.x, l.y, l.z), i.setXYZ(g, c.x, c.y, c.z);
        }
      else
        for (let u = 0, p = t.count; u < p; u += 3)
          n.fromBufferAttribute(t, u + 0), s.fromBufferAttribute(t, u + 1), a.fromBufferAttribute(t, u + 2), h.subVectors(a, s), d.subVectors(n, s), h.cross(d), i.setXYZ(u + 0, h.x, h.y, h.z), i.setXYZ(u + 1, h.x, h.y, h.z), i.setXYZ(u + 2, h.x, h.y, h.z);
      this.normalizeNormals(), i.needsUpdate = !0;
    }
  }
  /**
   * Ensures every normal vector in a geometry will have a magnitude of `1`. This will
   * correct lighting on the geometry surfaces.
   */
  normalizeNormals() {
    const e = this.attributes.normal;
    for (let t = 0, i = e.count; t < i; t++)
      Bt.fromBufferAttribute(e, t), Bt.normalize(), e.setXYZ(t, Bt.x, Bt.y, Bt.z);
  }
  /**
   * Return a new non-index version of this indexed geometry. If the geometry
   * is already non-indexed, the method is a NOOP.
   *
   * @return {BufferGeometry} The non-indexed version of this indexed geometry.
   */
  toNonIndexed() {
    function e(o, l) {
      const c = o.array, h = o.itemSize, d = o.normalized, u = new c.constructor(l.length * h);
      let p = 0, m = 0;
      for (let _ = 0, g = l.length; _ < g; _++) {
        o.isInterleavedBufferAttribute ? p = l[_] * o.data.stride + o.offset : p = l[_] * h;
        for (let f = 0; f < h; f++)
          u[m++] = c[p++];
      }
      return new it(u, h, d);
    }
    if (this.index === null)
      return console.warn("THREE.BufferGeometry.toNonIndexed(): BufferGeometry is already non-indexed."), this;
    const t = new Ue(), i = this.index.array, n = this.attributes;
    for (const o in n) {
      const l = n[o], c = e(l, i);
      t.setAttribute(o, c);
    }
    const s = this.morphAttributes;
    for (const o in s) {
      const l = [], c = s[o];
      for (let h = 0, d = c.length; h < d; h++) {
        const u = c[h], p = e(u, i);
        l.push(p);
      }
      t.morphAttributes[o] = l;
    }
    t.morphTargetsRelative = this.morphTargetsRelative;
    const a = this.groups;
    for (let o = 0, l = a.length; o < l; o++) {
      const c = a[o];
      t.addGroup(c.start, c.count, c.materialIndex);
    }
    return t;
  }
  /**
   * Serializes the geometry into JSON.
   *
   * @return {Object} A JSON object representing the serialized geometry.
   */
  toJSON() {
    const e = {
      metadata: {
        version: 4.7,
        type: "BufferGeometry",
        generator: "BufferGeometry.toJSON"
      }
    };
    if (e.uuid = this.uuid, e.type = this.type, this.name !== "" && (e.name = this.name), Object.keys(this.userData).length > 0 && (e.userData = this.userData), this.parameters !== void 0) {
      const l = this.parameters;
      for (const c in l)
        l[c] !== void 0 && (e[c] = l[c]);
      return e;
    }
    e.data = { attributes: {} };
    const t = this.index;
    t !== null && (e.data.index = {
      type: t.array.constructor.name,
      array: Array.prototype.slice.call(t.array)
    });
    const i = this.attributes;
    for (const l in i) {
      const c = i[l];
      e.data.attributes[l] = c.toJSON(e.data);
    }
    const n = {};
    let s = !1;
    for (const l in this.morphAttributes) {
      const c = this.morphAttributes[l], h = [];
      for (let d = 0, u = c.length; d < u; d++) {
        const p = c[d];
        h.push(p.toJSON(e.data));
      }
      h.length > 0 && (n[l] = h, s = !0);
    }
    s && (e.data.morphAttributes = n, e.data.morphTargetsRelative = this.morphTargetsRelative);
    const a = this.groups;
    a.length > 0 && (e.data.groups = JSON.parse(JSON.stringify(a)));
    const o = this.boundingSphere;
    return o !== null && (e.data.boundingSphere = o.toJSON()), e;
  }
  /**
   * Returns a new geometry with copied values from this instance.
   *
   * @return {BufferGeometry} A clone of this instance.
   */
  clone() {
    return new this.constructor().copy(this);
  }
  /**
   * Copies the values of the given geometry to this instance.
   *
   * @param {BufferGeometry} source - The geometry to copy.
   * @return {BufferGeometry} A reference to this instance.
   */
  copy(e) {
    this.index = null, this.attributes = {}, this.morphAttributes = {}, this.groups = [], this.boundingBox = null, this.boundingSphere = null;
    const t = {};
    this.name = e.name;
    const i = e.index;
    i !== null && this.setIndex(i.clone());
    const n = e.attributes;
    for (const c in n) {
      const h = n[c];
      this.setAttribute(c, h.clone(t));
    }
    const s = e.morphAttributes;
    for (const c in s) {
      const h = [], d = s[c];
      for (let u = 0, p = d.length; u < p; u++)
        h.push(d[u].clone(t));
      this.morphAttributes[c] = h;
    }
    this.morphTargetsRelative = e.morphTargetsRelative;
    const a = e.groups;
    for (let c = 0, h = a.length; c < h; c++) {
      const d = a[c];
      this.addGroup(d.start, d.count, d.materialIndex);
    }
    const o = e.boundingBox;
    o !== null && (this.boundingBox = o.clone());
    const l = e.boundingSphere;
    return l !== null && (this.boundingSphere = l.clone()), this.drawRange.start = e.drawRange.start, this.drawRange.count = e.drawRange.count, this.userData = e.userData, this;
  }
  /**
   * Frees the GPU-related resources allocated by this instance. Call this
   * method whenever this instance is no longer used in your app.
   *
   * @fires BufferGeometry#dispose
   */
  dispose() {
    this.dispatchEvent({ type: "dispose" });
  }
}
const fu = /* @__PURE__ */ new Ne(), Yn = /* @__PURE__ */ new ws(), ka = /* @__PURE__ */ new Lt(), mu = /* @__PURE__ */ new b(), za = /* @__PURE__ */ new b(), Ha = /* @__PURE__ */ new b(), Va = /* @__PURE__ */ new b(), kc = /* @__PURE__ */ new b(), Ga = /* @__PURE__ */ new b(), gu = /* @__PURE__ */ new b(), Wa = /* @__PURE__ */ new b();
class Je extends tt {
  /**
   * Constructs a new mesh.
   *
   * @param {BufferGeometry} [geometry] - The mesh geometry.
   * @param {Material|Array<Material>} [material] - The mesh material.
   */
  constructor(e = new Ue(), t = new Ht()) {
    super(), this.isMesh = !0, this.type = "Mesh", this.geometry = e, this.material = t, this.morphTargetDictionary = void 0, this.morphTargetInfluences = void 0, this.count = 1, this.updateMorphTargets();
  }
  copy(e, t) {
    return super.copy(e, t), e.morphTargetInfluences !== void 0 && (this.morphTargetInfluences = e.morphTargetInfluences.slice()), e.morphTargetDictionary !== void 0 && (this.morphTargetDictionary = Object.assign({}, e.morphTargetDictionary)), this.material = Array.isArray(e.material) ? e.material.slice() : e.material, this.geometry = e.geometry, this;
  }
  /**
   * Sets the values of {@link Mesh#morphTargetDictionary} and {@link Mesh#morphTargetInfluences}
   * to make sure existing morph targets can influence this 3D object.
   */
  updateMorphTargets() {
    const t = this.geometry.morphAttributes, i = Object.keys(t);
    if (i.length > 0) {
      const n = t[i[0]];
      if (n !== void 0) {
        this.morphTargetInfluences = [], this.morphTargetDictionary = {};
        for (let s = 0, a = n.length; s < a; s++) {
          const o = n[s].name || String(s);
          this.morphTargetInfluences.push(0), this.morphTargetDictionary[o] = s;
        }
      }
    }
  }
  /**
   * Returns the local-space position of the vertex at the given index, taking into
   * account the current animation state of both morph targets and skinning.
   *
   * @param {number} index - The vertex index.
   * @param {Vector3} target - The target object that is used to store the method's result.
   * @return {Vector3} The vertex position in local space.
   */
  getVertexPosition(e, t) {
    const i = this.geometry, n = i.attributes.position, s = i.morphAttributes.position, a = i.morphTargetsRelative;
    t.fromBufferAttribute(n, e);
    const o = this.morphTargetInfluences;
    if (s && o) {
      Ga.set(0, 0, 0);
      for (let l = 0, c = s.length; l < c; l++) {
        const h = o[l], d = s[l];
        h !== 0 && (kc.fromBufferAttribute(d, e), a ? Ga.addScaledVector(kc, h) : Ga.addScaledVector(kc.sub(t), h));
      }
      t.add(Ga);
    }
    return t;
  }
  /**
   * Computes intersection points between a casted ray and this line.
   *
   * @param {Raycaster} raycaster - The raycaster.
   * @param {Array<Object>} intersects - The target array that holds the intersection points.
   */
  raycast(e, t) {
    const i = this.geometry, n = this.material, s = this.matrixWorld;
    n !== void 0 && (i.boundingSphere === null && i.computeBoundingSphere(), ka.copy(i.boundingSphere), ka.applyMatrix4(s), Yn.copy(e.ray).recast(e.near), !(ka.containsPoint(Yn.origin) === !1 && (Yn.intersectSphere(ka, mu) === null || Yn.origin.distanceToSquared(mu) > (e.far - e.near) ** 2)) && (fu.copy(s).invert(), Yn.copy(e.ray).applyMatrix4(fu), !(i.boundingBox !== null && Yn.intersectsBox(i.boundingBox) === !1) && this._computeIntersections(e, t, Yn)));
  }
  _computeIntersections(e, t, i) {
    let n;
    const s = this.geometry, a = this.material, o = s.index, l = s.attributes.position, c = s.attributes.uv, h = s.attributes.uv1, d = s.attributes.normal, u = s.groups, p = s.drawRange;
    if (o !== null)
      if (Array.isArray(a))
        for (let m = 0, _ = u.length; m < _; m++) {
          const g = u[m], f = a[g.materialIndex], v = Math.max(g.start, p.start), x = Math.min(o.count, Math.min(g.start + g.count, p.start + p.count));
          for (let y = v, A = x; y < A; y += 3) {
            const S = o.getX(y), C = o.getX(y + 1), P = o.getX(y + 2);
            n = Xa(this, f, e, i, c, h, d, S, C, P), n && (n.faceIndex = Math.floor(y / 3), n.face.materialIndex = g.materialIndex, t.push(n));
          }
        }
      else {
        const m = Math.max(0, p.start), _ = Math.min(o.count, p.start + p.count);
        for (let g = m, f = _; g < f; g += 3) {
          const v = o.getX(g), x = o.getX(g + 1), y = o.getX(g + 2);
          n = Xa(this, a, e, i, c, h, d, v, x, y), n && (n.faceIndex = Math.floor(g / 3), t.push(n));
        }
      }
    else if (l !== void 0)
      if (Array.isArray(a))
        for (let m = 0, _ = u.length; m < _; m++) {
          const g = u[m], f = a[g.materialIndex], v = Math.max(g.start, p.start), x = Math.min(l.count, Math.min(g.start + g.count, p.start + p.count));
          for (let y = v, A = x; y < A; y += 3) {
            const S = y, C = y + 1, P = y + 2;
            n = Xa(this, f, e, i, c, h, d, S, C, P), n && (n.faceIndex = Math.floor(y / 3), n.face.materialIndex = g.materialIndex, t.push(n));
          }
        }
      else {
        const m = Math.max(0, p.start), _ = Math.min(l.count, p.start + p.count);
        for (let g = m, f = _; g < f; g += 3) {
          const v = g, x = g + 1, y = g + 2;
          n = Xa(this, a, e, i, c, h, d, v, x, y), n && (n.faceIndex = Math.floor(g / 3), t.push(n));
        }
      }
  }
}
function ny(r, e, t, i, n, s, a, o) {
  let l;
  if (e.side === zt ? l = i.intersectTriangle(a, s, n, !0, o) : l = i.intersectTriangle(n, s, a, e.side === Di, o), l === null) return null;
  Wa.copy(o), Wa.applyMatrix4(r.matrixWorld);
  const c = t.ray.origin.distanceTo(Wa);
  return c < t.near || c > t.far ? null : {
    distance: c,
    point: Wa.clone(),
    object: r
  };
}
function Xa(r, e, t, i, n, s, a, o, l, c) {
  r.getVertexPosition(o, za), r.getVertexPosition(l, Ha), r.getVertexPosition(c, Va);
  const h = ny(r, e, t, i, za, Ha, Va, gu);
  if (h) {
    const d = new b();
    pi.getBarycoord(gu, za, Ha, Va, d), n && (h.uv = pi.getInterpolatedAttribute(n, o, l, c, d, new H())), s && (h.uv1 = pi.getInterpolatedAttribute(s, o, l, c, d, new H())), a && (h.normal = pi.getInterpolatedAttribute(a, o, l, c, d, new b()), h.normal.dot(i.direction) > 0 && h.normal.multiplyScalar(-1));
    const u = {
      a: o,
      b: l,
      c,
      normal: new b(),
      materialIndex: 0
    };
    pi.getNormal(za, Ha, Va, u.normal), h.face = u, h.barycoord = d;
  }
  return h;
}
class Es extends Ue {
  /**
   * Constructs a new box geometry.
   *
   * @param {number} [width=1] - The width. That is, the length of the edges parallel to the X axis.
   * @param {number} [height=1] - The height. That is, the length of the edges parallel to the Y axis.
   * @param {number} [depth=1] - The depth. That is, the length of the edges parallel to the Z axis.
   * @param {number} [widthSegments=1] - Number of segmented rectangular faces along the width of the sides.
   * @param {number} [heightSegments=1] - Number of segmented rectangular faces along the height of the sides.
   * @param {number} [depthSegments=1] - Number of segmented rectangular faces along the depth of the sides.
   */
  constructor(e = 1, t = 1, i = 1, n = 1, s = 1, a = 1) {
    super(), this.type = "BoxGeometry", this.parameters = {
      width: e,
      height: t,
      depth: i,
      widthSegments: n,
      heightSegments: s,
      depthSegments: a
    };
    const o = this;
    n = Math.floor(n), s = Math.floor(s), a = Math.floor(a);
    const l = [], c = [], h = [], d = [];
    let u = 0, p = 0;
    m("z", "y", "x", -1, -1, i, t, e, a, s, 0), m("z", "y", "x", 1, -1, i, t, -e, a, s, 1), m("x", "z", "y", 1, 1, e, i, t, n, a, 2), m("x", "z", "y", 1, -1, e, i, -t, n, a, 3), m("x", "y", "z", 1, -1, e, t, i, n, s, 4), m("x", "y", "z", -1, -1, e, t, -i, n, s, 5), this.setIndex(l), this.setAttribute("position", new ve(c, 3)), this.setAttribute("normal", new ve(h, 3)), this.setAttribute("uv", new ve(d, 2));
    function m(_, g, f, v, x, y, A, S, C, P, E) {
      const w = y / C, L = A / P, N = y / 2, B = A / 2, W = S / 2, Z = C + 1, X = P + 1;
      let ie = 0, G = 0;
      const he = new b();
      for (let me = 0; me < X; me++) {
        const Se = me * L - B;
        for (let We = 0; We < Z; We++) {
          const Qe = We * w - N;
          he[_] = Qe * v, he[g] = Se * x, he[f] = W, c.push(he.x, he.y, he.z), he[_] = 0, he[g] = 0, he[f] = S > 0 ? 1 : -1, h.push(he.x, he.y, he.z), d.push(We / C), d.push(1 - me / P), ie += 1;
        }
      }
      for (let me = 0; me < P; me++)
        for (let Se = 0; Se < C; Se++) {
          const We = u + Se + Z * me, Qe = u + Se + Z * (me + 1), ht = u + (Se + 1) + Z * (me + 1), nt = u + (Se + 1) + Z * me;
          l.push(We, Qe, nt), l.push(Qe, ht, nt), G += 6;
        }
      o.addGroup(p, G, E), p += G, u += ie;
    }
  }
  copy(e) {
    return super.copy(e), this.parameters = Object.assign({}, e.parameters), this;
  }
  /**
   * Factory method for creating an instance of this class from the given
   * JSON object.
   *
   * @param {Object} data - A JSON object representing the serialized geometry.
   * @return {BoxGeometry} A new instance.
   */
  static fromJSON(e) {
    return new Es(e.width, e.height, e.depth, e.widthSegments, e.heightSegments, e.depthSegments);
  }
}
function mr(r) {
  const e = {};
  for (const t in r) {
    e[t] = {};
    for (const i in r[t]) {
      const n = r[t][i];
      n && (n.isColor || n.isMatrix3 || n.isMatrix4 || n.isVector2 || n.isVector3 || n.isVector4 || n.isTexture || n.isQuaternion) ? n.isRenderTargetTexture ? (console.warn("UniformsUtils: Textures of render targets cannot be cloned via cloneUniforms() or mergeUniforms()."), e[t][i] = null) : e[t][i] = n.clone() : Array.isArray(n) ? e[t][i] = n.slice() : e[t][i] = n;
    }
  }
  return e;
}
function ni(r) {
  const e = {};
  for (let t = 0; t < r.length; t++) {
    const i = mr(r[t]);
    for (const n in i)
      e[n] = i[n];
  }
  return e;
}
function sy(r) {
  const e = [];
  for (let t = 0; t < r.length; t++)
    e.push(r[t].clone());
  return e;
}
function um(r) {
  const e = r.getRenderTarget();
  return e === null ? r.outputColorSpace : e.isXRRenderTarget === !0 ? e.texture.colorSpace : et.workingColorSpace;
}
const Zl = { clone: mr, merge: ni };
var ry = `void main() {
	gl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 );
}`, ay = `void main() {
	gl_FragColor = vec4( 1.0, 0.0, 0.0, 1.0 );
}`;
class Ci extends qt {
  /**
   * Constructs a new shader material.
   *
   * @param {Object} [parameters] - An object with one or more properties
   * defining the material's appearance. Any property of the material
   * (including any property from inherited materials) can be passed
   * in here. Color values can be passed any type of value accepted
   * by {@link Color#set}.
   */
  constructor(e) {
    super(), this.isShaderMaterial = !0, this.type = "ShaderMaterial", this.defines = {}, this.uniforms = {}, this.uniformsGroups = [], this.vertexShader = ry, this.fragmentShader = ay, this.linewidth = 1, this.wireframe = !1, this.wireframeLinewidth = 1, this.fog = !1, this.lights = !1, this.clipping = !1, this.forceSinglePass = !0, this.extensions = {
      clipCullDistance: !1,
      // set to use vertex shader clipping
      multiDraw: !1
      // set to use vertex shader multi_draw / enable gl_DrawID
    }, this.defaultAttributeValues = {
      color: [1, 1, 1],
      uv: [0, 0],
      uv1: [0, 0]
    }, this.index0AttributeName = void 0, this.uniformsNeedUpdate = !1, this.glslVersion = null, e !== void 0 && this.setValues(e);
  }
  copy(e) {
    return super.copy(e), this.fragmentShader = e.fragmentShader, this.vertexShader = e.vertexShader, this.uniforms = mr(e.uniforms), this.uniformsGroups = sy(e.uniformsGroups), this.defines = Object.assign({}, e.defines), this.wireframe = e.wireframe, this.wireframeLinewidth = e.wireframeLinewidth, this.fog = e.fog, this.lights = e.lights, this.clipping = e.clipping, this.extensions = Object.assign({}, e.extensions), this.glslVersion = e.glslVersion, this;
  }
  toJSON(e) {
    const t = super.toJSON(e);
    t.glslVersion = this.glslVersion, t.uniforms = {};
    for (const n in this.uniforms) {
      const a = this.uniforms[n].value;
      a && a.isTexture ? t.uniforms[n] = {
        type: "t",
        value: a.toJSON(e).uuid
      } : a && a.isColor ? t.uniforms[n] = {
        type: "c",
        value: a.getHex()
      } : a && a.isVector2 ? t.uniforms[n] = {
        type: "v2",
        value: a.toArray()
      } : a && a.isVector3 ? t.uniforms[n] = {
        type: "v3",
        value: a.toArray()
      } : a && a.isVector4 ? t.uniforms[n] = {
        type: "v4",
        value: a.toArray()
      } : a && a.isMatrix3 ? t.uniforms[n] = {
        type: "m3",
        value: a.toArray()
      } : a && a.isMatrix4 ? t.uniforms[n] = {
        type: "m4",
        value: a.toArray()
      } : t.uniforms[n] = {
        value: a
      };
    }
    Object.keys(this.defines).length > 0 && (t.defines = this.defines), t.vertexShader = this.vertexShader, t.fragmentShader = this.fragmentShader, t.lights = this.lights, t.clipping = this.clipping;
    const i = {};
    for (const n in this.extensions)
      this.extensions[n] === !0 && (i[n] = !0);
    return Object.keys(i).length > 0 && (t.extensions = i), t;
  }
}
let Yl = class extends tt {
  /**
   * Constructs a new camera.
   */
  constructor() {
    super(), this.isCamera = !0, this.type = "Camera", this.matrixWorldInverse = new Ne(), this.projectionMatrix = new Ne(), this.projectionMatrixInverse = new Ne(), this.coordinateSystem = wi, this._reversedDepth = !1;
  }
  /**
   * The flag that indicates whether the camera uses a reversed depth buffer.
   *
   * @type {boolean}
   * @default false
   */
  get reversedDepth() {
    return this._reversedDepth;
  }
  copy(e, t) {
    return super.copy(e, t), this.matrixWorldInverse.copy(e.matrixWorldInverse), this.projectionMatrix.copy(e.projectionMatrix), this.projectionMatrixInverse.copy(e.projectionMatrixInverse), this.coordinateSystem = e.coordinateSystem, this;
  }
  /**
   * Returns a vector representing the ("look") direction of the 3D object in world space.
   *
   * This method is overwritten since cameras have a different forward vector compared to other
   * 3D objects. A camera looks down its local, negative z-axis by default.
   *
   * @param {Vector3} target - The target vector the result is stored to.
   * @return {Vector3} The 3D object's direction in world space.
   */
  getWorldDirection(e) {
    return super.getWorldDirection(e).negate();
  }
  updateMatrixWorld(e) {
    super.updateMatrixWorld(e), this.matrixWorldInverse.copy(this.matrixWorld).invert();
  }
  updateWorldMatrix(e, t) {
    super.updateWorldMatrix(e, t), this.matrixWorldInverse.copy(this.matrixWorld).invert();
  }
  clone() {
    return new this.constructor().copy(this);
  }
};
const En = /* @__PURE__ */ new b(), _u = /* @__PURE__ */ new H(), yu = /* @__PURE__ */ new H();
class kt extends Yl {
  /**
   * Constructs a new perspective camera.
   *
   * @param {number} [fov=50] - The vertical field of view.
   * @param {number} [aspect=1] - The aspect ratio.
   * @param {number} [near=0.1] - The camera's near plane.
   * @param {number} [far=2000] - The camera's far plane.
   */
  constructor(e = 50, t = 1, i = 0.1, n = 2e3) {
    super(), this.isPerspectiveCamera = !0, this.type = "PerspectiveCamera", this.fov = e, this.zoom = 1, this.near = i, this.far = n, this.focus = 10, this.aspect = t, this.view = null, this.filmGauge = 35, this.filmOffset = 0, this.updateProjectionMatrix();
  }
  copy(e, t) {
    return super.copy(e, t), this.fov = e.fov, this.zoom = e.zoom, this.near = e.near, this.far = e.far, this.focus = e.focus, this.aspect = e.aspect, this.view = e.view === null ? null : Object.assign({}, e.view), this.filmGauge = e.filmGauge, this.filmOffset = e.filmOffset, this;
  }
  /**
   * Sets the FOV by focal length in respect to the current {@link PerspectiveCamera#filmGauge}.
   *
   * The default film gauge is 35, so that the focal length can be specified for
   * a 35mm (full frame) camera.
   *
   * @param {number} focalLength - Values for focal length and film gauge must have the same unit.
   */
  setFocalLength(e) {
    const t = 0.5 * this.getFilmHeight() / e;
    this.fov = fr * 2 * Math.atan(t), this.updateProjectionMatrix();
  }
  /**
   * Returns the focal length from the current {@link PerspectiveCamera#fov} and
   * {@link PerspectiveCamera#filmGauge}.
   *
   * @return {number} The computed focal length.
   */
  getFocalLength() {
    const e = Math.tan(ms * 0.5 * this.fov);
    return 0.5 * this.getFilmHeight() / e;
  }
  /**
   * Returns the current vertical field of view angle in degrees considering {@link PerspectiveCamera#zoom}.
   *
   * @return {number} The effective FOV.
   */
  getEffectiveFOV() {
    return fr * 2 * Math.atan(
      Math.tan(ms * 0.5 * this.fov) / this.zoom
    );
  }
  /**
   * Returns the width of the image on the film. If {@link PerspectiveCamera#aspect} is greater than or
   * equal to one (landscape format), the result equals {@link PerspectiveCamera#filmGauge}.
   *
   * @return {number} The film width.
   */
  getFilmWidth() {
    return this.filmGauge * Math.min(this.aspect, 1);
  }
  /**
   * Returns the height of the image on the film. If {@link PerspectiveCamera#aspect} is greater than or
   * equal to one (landscape format), the result equals {@link PerspectiveCamera#filmGauge}.
   *
   * @return {number} The film width.
   */
  getFilmHeight() {
    return this.filmGauge / Math.max(this.aspect, 1);
  }
  /**
   * Computes the 2D bounds of the camera's viewable rectangle at a given distance along the viewing direction.
   * Sets `minTarget` and `maxTarget` to the coordinates of the lower-left and upper-right corners of the view rectangle.
   *
   * @param {number} distance - The viewing distance.
   * @param {Vector2} minTarget - The lower-left corner of the view rectangle is written into this vector.
   * @param {Vector2} maxTarget - The upper-right corner of the view rectangle is written into this vector.
   */
  getViewBounds(e, t, i) {
    En.set(-1, -1, 0.5).applyMatrix4(this.projectionMatrixInverse), t.set(En.x, En.y).multiplyScalar(-e / En.z), En.set(1, 1, 0.5).applyMatrix4(this.projectionMatrixInverse), i.set(En.x, En.y).multiplyScalar(-e / En.z);
  }
  /**
   * Computes the width and height of the camera's viewable rectangle at a given distance along the viewing direction.
   *
   * @param {number} distance - The viewing distance.
   * @param {Vector2} target - The target vector that is used to store result where x is width and y is height.
   * @returns {Vector2} The view size.
   */
  getViewSize(e, t) {
    return this.getViewBounds(e, _u, yu), t.subVectors(yu, _u);
  }
  /**
   * Sets an offset in a larger frustum. This is useful for multi-window or
   * multi-monitor/multi-machine setups.
   *
   * For example, if you have 3x2 monitors and each monitor is 1920x1080 and
   * the monitors are in grid like this
   *```
   *   +---+---+---+
   *   | A | B | C |
   *   +---+---+---+
   *   | D | E | F |
   *   +---+---+---+
   *```
   * then for each monitor you would call it like this:
   *```js
   * const w = 1920;
   * const h = 1080;
   * const fullWidth = w * 3;
   * const fullHeight = h * 2;
   *
   * // --A--
   * camera.setViewOffset( fullWidth, fullHeight, w * 0, h * 0, w, h );
   * // --B--
   * camera.setViewOffset( fullWidth, fullHeight, w * 1, h * 0, w, h );
   * // --C--
   * camera.setViewOffset( fullWidth, fullHeight, w * 2, h * 0, w, h );
   * // --D--
   * camera.setViewOffset( fullWidth, fullHeight, w * 0, h * 1, w, h );
   * // --E--
   * camera.setViewOffset( fullWidth, fullHeight, w * 1, h * 1, w, h );
   * // --F--
   * camera.setViewOffset( fullWidth, fullHeight, w * 2, h * 1, w, h );
   * ```
   *
   * Note there is no reason monitors have to be the same size or in a grid.
   *
   * @param {number} fullWidth - The full width of multiview setup.
   * @param {number} fullHeight - The full height of multiview setup.
   * @param {number} x - The horizontal offset of the subcamera.
   * @param {number} y - The vertical offset of the subcamera.
   * @param {number} width - The width of subcamera.
   * @param {number} height - The height of subcamera.
   */
  setViewOffset(e, t, i, n, s, a) {
    this.aspect = e / t, this.view === null && (this.view = {
      enabled: !0,
      fullWidth: 1,
      fullHeight: 1,
      offsetX: 0,
      offsetY: 0,
      width: 1,
      height: 1
    }), this.view.enabled = !0, this.view.fullWidth = e, this.view.fullHeight = t, this.view.offsetX = i, this.view.offsetY = n, this.view.width = s, this.view.height = a, this.updateProjectionMatrix();
  }
  /**
   * Removes the view offset from the projection matrix.
   */
  clearViewOffset() {
    this.view !== null && (this.view.enabled = !1), this.updateProjectionMatrix();
  }
  /**
   * Updates the camera's projection matrix. Must be called after any change of
   * camera properties.
   */
  updateProjectionMatrix() {
    const e = this.near;
    let t = e * Math.tan(ms * 0.5 * this.fov) / this.zoom, i = 2 * t, n = this.aspect * i, s = -0.5 * n;
    const a = this.view;
    if (this.view !== null && this.view.enabled) {
      const l = a.fullWidth, c = a.fullHeight;
      s += a.offsetX * n / l, t -= a.offsetY * i / c, n *= a.width / l, i *= a.height / c;
    }
    const o = this.filmOffset;
    o !== 0 && (s += e * o / this.getFilmWidth()), this.projectionMatrix.makePerspective(s, s + n, t, t - i, e, this.far, this.coordinateSystem, this.reversedDepth), this.projectionMatrixInverse.copy(this.projectionMatrix).invert();
  }
  toJSON(e) {
    const t = super.toJSON(e);
    return t.object.fov = this.fov, t.object.zoom = this.zoom, t.object.near = this.near, t.object.far = this.far, t.object.focus = this.focus, t.object.aspect = this.aspect, this.view !== null && (t.object.view = Object.assign({}, this.view)), t.object.filmGauge = this.filmGauge, t.object.filmOffset = this.filmOffset, t;
  }
}
const zs = -90, Hs = 1;
class pm extends tt {
  /**
   * Constructs a new cube camera.
   *
   * @param {number} near - The camera's near plane.
   * @param {number} far - The camera's far plane.
   * @param {WebGLCubeRenderTarget} renderTarget - The cube render target.
   */
  constructor(e, t, i) {
    super(), this.type = "CubeCamera", this.renderTarget = i, this.coordinateSystem = null, this.activeMipmapLevel = 0;
    const n = new kt(zs, Hs, e, t);
    n.layers = this.layers, this.add(n);
    const s = new kt(zs, Hs, e, t);
    s.layers = this.layers, this.add(s);
    const a = new kt(zs, Hs, e, t);
    a.layers = this.layers, this.add(a);
    const o = new kt(zs, Hs, e, t);
    o.layers = this.layers, this.add(o);
    const l = new kt(zs, Hs, e, t);
    l.layers = this.layers, this.add(l);
    const c = new kt(zs, Hs, e, t);
    c.layers = this.layers, this.add(c);
  }
  /**
   * Must be called when the coordinate system of the cube camera is changed.
   */
  updateCoordinateSystem() {
    const e = this.coordinateSystem, t = this.children.concat(), [i, n, s, a, o, l] = t;
    for (const c of t) this.remove(c);
    if (e === wi)
      i.up.set(0, 1, 0), i.lookAt(1, 0, 0), n.up.set(0, 1, 0), n.lookAt(-1, 0, 0), s.up.set(0, 0, -1), s.lookAt(0, 1, 0), a.up.set(0, 0, 1), a.lookAt(0, -1, 0), o.up.set(0, 1, 0), o.lookAt(0, 0, 1), l.up.set(0, 1, 0), l.lookAt(0, 0, -1);
    else if (e === pr)
      i.up.set(0, -1, 0), i.lookAt(-1, 0, 0), n.up.set(0, -1, 0), n.lookAt(1, 0, 0), s.up.set(0, 0, 1), s.lookAt(0, 1, 0), a.up.set(0, 0, -1), a.lookAt(0, -1, 0), o.up.set(0, -1, 0), o.lookAt(0, 0, 1), l.up.set(0, -1, 0), l.lookAt(0, 0, -1);
    else
      throw new Error("THREE.CubeCamera.updateCoordinateSystem(): Invalid coordinate system: " + e);
    for (const c of t)
      this.add(c), c.updateMatrixWorld();
  }
  /**
   * Calling this method will render the given scene with the given renderer
   * into the cube render target of the camera.
   *
   * @param {(Renderer|WebGLRenderer)} renderer - The renderer.
   * @param {Scene} scene - The scene to render.
   */
  update(e, t) {
    this.parent === null && this.updateMatrixWorld();
    const { renderTarget: i, activeMipmapLevel: n } = this;
    this.coordinateSystem !== e.coordinateSystem && (this.coordinateSystem = e.coordinateSystem, this.updateCoordinateSystem());
    const [s, a, o, l, c, h] = this.children, d = e.getRenderTarget(), u = e.getActiveCubeFace(), p = e.getActiveMipmapLevel(), m = e.xr.enabled;
    e.xr.enabled = !1;
    const _ = i.texture.generateMipmaps;
    i.texture.generateMipmaps = !1, e.setRenderTarget(i, 0, n), e.render(t, s), e.setRenderTarget(i, 1, n), e.render(t, a), e.setRenderTarget(i, 2, n), e.render(t, o), e.setRenderTarget(i, 3, n), e.render(t, l), e.setRenderTarget(i, 4, n), e.render(t, c), i.texture.generateMipmaps = _, e.setRenderTarget(i, 5, n), e.render(t, h), e.setRenderTarget(d, u, p), e.xr.enabled = m, i.texture.needsPMREMUpdate = !0;
  }
}
class Sa extends Et {
  /**
   * Constructs a new cube texture.
   *
   * @param {Array<Image>} [images=[]] - An array holding a image for each side of a cube.
   * @param {number} [mapping=CubeReflectionMapping] - The texture mapping.
   * @param {number} [wrapS=ClampToEdgeWrapping] - The wrapS value.
   * @param {number} [wrapT=ClampToEdgeWrapping] - The wrapT value.
   * @param {number} [magFilter=LinearFilter] - The mag filter value.
   * @param {number} [minFilter=LinearMipmapLinearFilter] - The min filter value.
   * @param {number} [format=RGBAFormat] - The texture format.
   * @param {number} [type=UnsignedByteType] - The texture type.
   * @param {number} [anisotropy=Texture.DEFAULT_ANISOTROPY] - The anisotropy value.
   * @param {string} [colorSpace=NoColorSpace] - The color space value.
   */
  constructor(e = [], t = _n, i, n, s, a, o, l, c, h) {
    super(e, t, i, n, s, a, o, l, c, h), this.isCubeTexture = !0, this.flipY = !1;
  }
  /**
   * Alias for {@link CubeTexture#image}.
   *
   * @type {Array<Image>}
   */
  get images() {
    return this.image;
  }
  set images(e) {
    this.image = e;
  }
}
class fm extends nn {
  /**
   * Constructs a new cube render target.
   *
   * @param {number} [size=1] - The size of the render target.
   * @param {RenderTarget~Options} [options] - The configuration object.
   */
  constructor(e = 1, t = {}) {
    super(e, e, t), this.isWebGLCubeRenderTarget = !0;
    const i = { width: e, height: e, depth: 1 }, n = [i, i, i, i, i, i];
    this.texture = new Sa(n), this._setTextureOptions(t), this.texture.isRenderTargetTexture = !0;
  }
  /**
   * Converts the given equirectangular texture to a cube map.
   *
   * @param {WebGLRenderer} renderer - The renderer.
   * @param {Texture} texture - The equirectangular texture.
   * @return {WebGLCubeRenderTarget} A reference to this cube render target.
   */
  fromEquirectangularTexture(e, t) {
    this.texture.type = t.type, this.texture.colorSpace = t.colorSpace, this.texture.generateMipmaps = t.generateMipmaps, this.texture.minFilter = t.minFilter, this.texture.magFilter = t.magFilter;
    const i = {
      uniforms: {
        tEquirect: { value: null }
      },
      vertexShader: (
        /* glsl */
        `

				varying vec3 vWorldDirection;

				vec3 transformDirection( in vec3 dir, in mat4 matrix ) {

					return normalize( ( matrix * vec4( dir, 0.0 ) ).xyz );

				}

				void main() {

					vWorldDirection = transformDirection( position, modelMatrix );

					#include <begin_vertex>
					#include <project_vertex>

				}
			`
      ),
      fragmentShader: (
        /* glsl */
        `

				uniform sampler2D tEquirect;

				varying vec3 vWorldDirection;

				#include <common>

				void main() {

					vec3 direction = normalize( vWorldDirection );

					vec2 sampleUV = equirectUv( direction );

					gl_FragColor = texture2D( tEquirect, sampleUV );

				}
			`
      )
    }, n = new Es(5, 5, 5), s = new Ci({
      name: "CubemapFromEquirect",
      uniforms: mr(i.uniforms),
      vertexShader: i.vertexShader,
      fragmentShader: i.fragmentShader,
      side: zt,
      blending: fn
    });
    s.uniforms.tEquirect.value = t;
    const a = new Je(n, s), o = t.minFilter;
    return t.minFilter === Ji && (t.minFilter = Pt), new pm(1, 10, this).update(e, a), t.minFilter = o, a.geometry.dispose(), a.material.dispose(), this;
  }
  /**
   * Clears this cube render target.
   *
   * @param {WebGLRenderer} renderer - The renderer.
   * @param {boolean} [color=true] - Whether the color buffer should be cleared or not.
   * @param {boolean} [depth=true] - Whether the depth buffer should be cleared or not.
   * @param {boolean} [stencil=true] - Whether the stencil buffer should be cleared or not.
   */
  clear(e, t = !0, i = !0, n = !0) {
    const s = e.getRenderTarget();
    for (let a = 0; a < 6; a++)
      e.setRenderTarget(this, a), e.clear(t, i, n);
    e.setRenderTarget(s);
  }
}
class li extends tt {
  constructor() {
    super(), this.isGroup = !0, this.type = "Group";
  }
}
const oy = { type: "move" };
class Wo {
  /**
   * Constructs a new XR controller.
   */
  constructor() {
    this._targetRay = null, this._grip = null, this._hand = null;
  }
  /**
   * Returns a group representing the hand space of the XR controller.
   *
   * @return {Group} A group representing the hand space of the XR controller.
   */
  getHandSpace() {
    return this._hand === null && (this._hand = new li(), this._hand.matrixAutoUpdate = !1, this._hand.visible = !1, this._hand.joints = {}, this._hand.inputState = { pinching: !1 }), this._hand;
  }
  /**
   * Returns a group representing the target ray space of the XR controller.
   *
   * @return {Group} A group representing the target ray space of the XR controller.
   */
  getTargetRaySpace() {
    return this._targetRay === null && (this._targetRay = new li(), this._targetRay.matrixAutoUpdate = !1, this._targetRay.visible = !1, this._targetRay.hasLinearVelocity = !1, this._targetRay.linearVelocity = new b(), this._targetRay.hasAngularVelocity = !1, this._targetRay.angularVelocity = new b()), this._targetRay;
  }
  /**
   * Returns a group representing the grip space of the XR controller.
   *
   * @return {Group} A group representing the grip space of the XR controller.
   */
  getGripSpace() {
    return this._grip === null && (this._grip = new li(), this._grip.matrixAutoUpdate = !1, this._grip.visible = !1, this._grip.hasLinearVelocity = !1, this._grip.linearVelocity = new b(), this._grip.hasAngularVelocity = !1, this._grip.angularVelocity = new b()), this._grip;
  }
  /**
   * Dispatches the given event to the groups representing
   * the different coordinate spaces of the XR controller.
   *
   * @param {Object} event - The event to dispatch.
   * @return {WebXRController} A reference to this instance.
   */
  dispatchEvent(e) {
    return this._targetRay !== null && this._targetRay.dispatchEvent(e), this._grip !== null && this._grip.dispatchEvent(e), this._hand !== null && this._hand.dispatchEvent(e), this;
  }
  /**
   * Connects the controller with the given XR input source.
   *
   * @param {XRInputSource} inputSource - The input source.
   * @return {WebXRController} A reference to this instance.
   */
  connect(e) {
    if (e && e.hand) {
      const t = this._hand;
      if (t)
        for (const i of e.hand.values())
          this._getHandJoint(t, i);
    }
    return this.dispatchEvent({ type: "connected", data: e }), this;
  }
  /**
   * Disconnects the controller from the given XR input source.
   *
   * @param {XRInputSource} inputSource - The input source.
   * @return {WebXRController} A reference to this instance.
   */
  disconnect(e) {
    return this.dispatchEvent({ type: "disconnected", data: e }), this._targetRay !== null && (this._targetRay.visible = !1), this._grip !== null && (this._grip.visible = !1), this._hand !== null && (this._hand.visible = !1), this;
  }
  /**
   * Updates the controller with the given input source, XR frame and reference space.
   * This updates the transformations of the groups that represent the different
   * coordinate systems of the controller.
   *
   * @param {XRInputSource} inputSource - The input source.
   * @param {XRFrame} frame - The XR frame.
   * @param {XRReferenceSpace} referenceSpace - The reference space.
   * @return {WebXRController} A reference to this instance.
   */
  update(e, t, i) {
    let n = null, s = null, a = null;
    const o = this._targetRay, l = this._grip, c = this._hand;
    if (e && t.session.visibilityState !== "visible-blurred") {
      if (c && e.hand) {
        a = !0;
        for (const _ of e.hand.values()) {
          const g = t.getJointPose(_, i), f = this._getHandJoint(c, _);
          g !== null && (f.matrix.fromArray(g.transform.matrix), f.matrix.decompose(f.position, f.rotation, f.scale), f.matrixWorldNeedsUpdate = !0, f.jointRadius = g.radius), f.visible = g !== null;
        }
        const h = c.joints["index-finger-tip"], d = c.joints["thumb-tip"], u = h.position.distanceTo(d.position), p = 0.02, m = 5e-3;
        c.inputState.pinching && u > p + m ? (c.inputState.pinching = !1, this.dispatchEvent({
          type: "pinchend",
          handedness: e.handedness,
          target: this
        })) : !c.inputState.pinching && u <= p - m && (c.inputState.pinching = !0, this.dispatchEvent({
          type: "pinchstart",
          handedness: e.handedness,
          target: this
        }));
      } else
        l !== null && e.gripSpace && (s = t.getPose(e.gripSpace, i), s !== null && (l.matrix.fromArray(s.transform.matrix), l.matrix.decompose(l.position, l.rotation, l.scale), l.matrixWorldNeedsUpdate = !0, s.linearVelocity ? (l.hasLinearVelocity = !0, l.linearVelocity.copy(s.linearVelocity)) : l.hasLinearVelocity = !1, s.angularVelocity ? (l.hasAngularVelocity = !0, l.angularVelocity.copy(s.angularVelocity)) : l.hasAngularVelocity = !1));
      o !== null && (n = t.getPose(e.targetRaySpace, i), n === null && s !== null && (n = s), n !== null && (o.matrix.fromArray(n.transform.matrix), o.matrix.decompose(o.position, o.rotation, o.scale), o.matrixWorldNeedsUpdate = !0, n.linearVelocity ? (o.hasLinearVelocity = !0, o.linearVelocity.copy(n.linearVelocity)) : o.hasLinearVelocity = !1, n.angularVelocity ? (o.hasAngularVelocity = !0, o.angularVelocity.copy(n.angularVelocity)) : o.hasAngularVelocity = !1, this.dispatchEvent(oy)));
    }
    return o !== null && (o.visible = n !== null), l !== null && (l.visible = s !== null), c !== null && (c.visible = a !== null), this;
  }
  /**
   * Returns a group representing the hand joint for the given input joint.
   *
   * @private
   * @param {Group} hand - The group representing the hand space.
   * @param {XRJointSpace} inputjoint - The hand joint data.
   * @return {Group} A group representing the hand joint for the given input joint.
   */
  _getHandJoint(e, t) {
    if (e.joints[t.jointName] === void 0) {
      const i = new li();
      i.matrixAutoUpdate = !1, i.visible = !1, e.joints[t.jointName] = i, e.add(i);
    }
    return e.joints[t.jointName];
  }
}
class jl {
  /**
   * Constructs a new fog.
   *
   * @param {number|Color} color - The fog's color.
   * @param {number} [density=0.00025] - Defines how fast the fog will grow dense.
   */
  constructor(e, t = 25e-5) {
    this.isFogExp2 = !0, this.name = "", this.color = new oe(e), this.density = t;
  }
  /**
   * Returns a new fog with copied values from this instance.
   *
   * @return {FogExp2} A clone of this instance.
   */
  clone() {
    return new jl(this.color, this.density);
  }
  /**
   * Serializes the fog into JSON.
   *
   * @param {?(Object|string)} meta - An optional value holding meta information about the serialization.
   * @return {Object} A JSON object representing the serialized fog
   */
  toJSON() {
    return {
      type: "FogExp2",
      name: this.name,
      color: this.color.getHex(),
      density: this.density
    };
  }
}
class $l {
  /**
   * Constructs a new fog.
   *
   * @param {number|Color} color - The fog's color.
   * @param {number} [near=1] - The minimum distance to start applying fog.
   * @param {number} [far=1000] - The maximum distance at which fog stops being calculated and applied.
   */
  constructor(e, t = 1, i = 1e3) {
    this.isFog = !0, this.name = "", this.color = new oe(e), this.near = t, this.far = i;
  }
  /**
   * Returns a new fog with copied values from this instance.
   *
   * @return {Fog} A clone of this instance.
   */
  clone() {
    return new $l(this.color, this.near, this.far);
  }
  /**
   * Serializes the fog into JSON.
   *
   * @param {?(Object|string)} meta - An optional value holding meta information about the serialization.
   * @return {Object} A JSON object representing the serialized fog
   */
  toJSON() {
    return {
      type: "Fog",
      name: this.name,
      color: this.color.getHex(),
      near: this.near,
      far: this.far
    };
  }
}
class Ma extends tt {
  /**
   * Constructs a new scene.
   */
  constructor() {
    super(), this.isScene = !0, this.type = "Scene", this.background = null, this.environment = null, this.fog = null, this.backgroundBlurriness = 0, this.backgroundIntensity = 1, this.backgroundRotation = new Ai(), this.environmentIntensity = 1, this.environmentRotation = new Ai(), this.overrideMaterial = null, typeof __THREE_DEVTOOLS__ < "u" && __THREE_DEVTOOLS__.dispatchEvent(new CustomEvent("observe", { detail: this }));
  }
  copy(e, t) {
    return super.copy(e, t), e.background !== null && (this.background = e.background.clone()), e.environment !== null && (this.environment = e.environment.clone()), e.fog !== null && (this.fog = e.fog.clone()), this.backgroundBlurriness = e.backgroundBlurriness, this.backgroundIntensity = e.backgroundIntensity, this.backgroundRotation.copy(e.backgroundRotation), this.environmentIntensity = e.environmentIntensity, this.environmentRotation.copy(e.environmentRotation), e.overrideMaterial !== null && (this.overrideMaterial = e.overrideMaterial.clone()), this.matrixAutoUpdate = e.matrixAutoUpdate, this;
  }
  toJSON(e) {
    const t = super.toJSON(e);
    return this.fog !== null && (t.object.fog = this.fog.toJSON()), this.backgroundBlurriness > 0 && (t.object.backgroundBlurriness = this.backgroundBlurriness), this.backgroundIntensity !== 1 && (t.object.backgroundIntensity = this.backgroundIntensity), t.object.backgroundRotation = this.backgroundRotation.toArray(), this.environmentIntensity !== 1 && (t.object.environmentIntensity = this.environmentIntensity), t.object.environmentRotation = this.environmentRotation.toArray(), t;
  }
}
class Kl {
  /**
   * Constructs a new interleaved buffer.
   *
   * @param {TypedArray} array - A typed array with a shared buffer storing attribute data.
   * @param {number} stride - The number of typed-array elements per vertex.
   */
  constructor(e, t) {
    this.isInterleavedBuffer = !0, this.array = e, this.stride = t, this.count = e !== void 0 ? e.length / t : 0, this.usage = ha, this.updateRanges = [], this.version = 0, this.uuid = Ti();
  }
  /**
   * A callback function that is executed after the renderer has transferred the attribute array
   * data to the GPU.
   */
  onUploadCallback() {
  }
  /**
   * Flag to indicate that this attribute has changed and should be re-sent to
   * the GPU. Set this to `true` when you modify the value of the array.
   *
   * @type {number}
   * @default false
   * @param {boolean} value
   */
  set needsUpdate(e) {
    e === !0 && this.version++;
  }
  /**
   * Sets the usage of this interleaved buffer.
   *
   * @param {(StaticDrawUsage|DynamicDrawUsage|StreamDrawUsage|StaticReadUsage|DynamicReadUsage|StreamReadUsage|StaticCopyUsage|DynamicCopyUsage|StreamCopyUsage)} value - The usage to set.
   * @return {InterleavedBuffer} A reference to this interleaved buffer.
   */
  setUsage(e) {
    return this.usage = e, this;
  }
  /**
   * Adds a range of data in the data array to be updated on the GPU.
   *
   * @param {number} start - Position at which to start update.
   * @param {number} count - The number of components to update.
   */
  addUpdateRange(e, t) {
    this.updateRanges.push({ start: e, count: t });
  }
  /**
   * Clears the update ranges.
   */
  clearUpdateRanges() {
    this.updateRanges.length = 0;
  }
  /**
   * Copies the values of the given interleaved buffer to this instance.
   *
   * @param {InterleavedBuffer} source - The interleaved buffer to copy.
   * @return {InterleavedBuffer} A reference to this instance.
   */
  copy(e) {
    return this.array = new e.array.constructor(e.array), this.count = e.count, this.stride = e.stride, this.usage = e.usage, this;
  }
  /**
   * Copies a vector from the given interleaved buffer to this one. The start
   * and destination position in the attribute buffers are represented by the
   * given indices.
   *
   * @param {number} index1 - The destination index into this interleaved buffer.
   * @param {InterleavedBuffer} interleavedBuffer - The interleaved buffer to copy from.
   * @param {number} index2 - The source index into the given interleaved buffer.
   * @return {InterleavedBuffer} A reference to this instance.
   */
  copyAt(e, t, i) {
    e *= this.stride, i *= t.stride;
    for (let n = 0, s = this.stride; n < s; n++)
      this.array[e + n] = t.array[i + n];
    return this;
  }
  /**
   * Sets the given array data in the interleaved buffer.
   *
   * @param {(TypedArray|Array)} value - The array data to set.
   * @param {number} [offset=0] - The offset in this interleaved buffer's array.
   * @return {InterleavedBuffer} A reference to this instance.
   */
  set(e, t = 0) {
    return this.array.set(e, t), this;
  }
  /**
   * Returns a new interleaved buffer with copied values from this instance.
   *
   * @param {Object} [data] - An object with shared array buffers that allows to retain shared structures.
   * @return {InterleavedBuffer} A clone of this instance.
   */
  clone(e) {
    e.arrayBuffers === void 0 && (e.arrayBuffers = {}), this.array.buffer._uuid === void 0 && (this.array.buffer._uuid = Ti()), e.arrayBuffers[this.array.buffer._uuid] === void 0 && (e.arrayBuffers[this.array.buffer._uuid] = this.array.slice(0).buffer);
    const t = new this.array.constructor(e.arrayBuffers[this.array.buffer._uuid]), i = new this.constructor(t, this.stride);
    return i.setUsage(this.usage), i;
  }
  /**
   * Sets the given callback function that is executed after the Renderer has transferred
   * the array data to the GPU. Can be used to perform clean-up operations after
   * the upload when data are not needed anymore on the CPU side.
   *
   * @param {Function} callback - The `onUpload()` callback.
   * @return {InterleavedBuffer} A reference to this instance.
   */
  onUpload(e) {
    return this.onUploadCallback = e, this;
  }
  /**
   * Serializes the interleaved buffer into JSON.
   *
   * @param {Object} [data] - An optional value holding meta information about the serialization.
   * @return {Object} A JSON object representing the serialized interleaved buffer.
   */
  toJSON(e) {
    return e.arrayBuffers === void 0 && (e.arrayBuffers = {}), this.array.buffer._uuid === void 0 && (this.array.buffer._uuid = Ti()), e.arrayBuffers[this.array.buffer._uuid] === void 0 && (e.arrayBuffers[this.array.buffer._uuid] = Array.from(new Uint32Array(this.array.buffer))), {
      uuid: this.uuid,
      buffer: this.array.buffer._uuid,
      type: this.array.constructor.name,
      stride: this.stride
    };
  }
}
const ii = /* @__PURE__ */ new b();
class Ei {
  /**
   * Constructs a new interleaved buffer attribute.
   *
   * @param {InterleavedBuffer} interleavedBuffer - The buffer holding the interleaved data.
   * @param {number} itemSize - The item size.
   * @param {number} offset - The attribute offset into the buffer.
   * @param {boolean} [normalized=false] - Whether the data are normalized or not.
   */
  constructor(e, t, i, n = !1) {
    this.isInterleavedBufferAttribute = !0, this.name = "", this.data = e, this.itemSize = t, this.offset = i, this.normalized = n;
  }
  /**
   * The item count of this buffer attribute.
   *
   * @type {number}
   * @readonly
   */
  get count() {
    return this.data.count;
  }
  /**
   * The array holding the interleaved buffer attribute data.
   *
   * @type {TypedArray}
   */
  get array() {
    return this.data.array;
  }
  /**
   * Flag to indicate that this attribute has changed and should be re-sent to
   * the GPU. Set this to `true` when you modify the value of the array.
   *
   * @type {number}
   * @default false
   * @param {boolean} value
   */
  set needsUpdate(e) {
    this.data.needsUpdate = e;
  }
  /**
   * Applies the given 4x4 matrix to the given attribute. Only works with
   * item size `3`.
   *
   * @param {Matrix4} m - The matrix to apply.
   * @return {InterleavedBufferAttribute} A reference to this instance.
   */
  applyMatrix4(e) {
    for (let t = 0, i = this.data.count; t < i; t++)
      ii.fromBufferAttribute(this, t), ii.applyMatrix4(e), this.setXYZ(t, ii.x, ii.y, ii.z);
    return this;
  }
  /**
   * Applies the given 3x3 normal matrix to the given attribute. Only works with
   * item size `3`.
   *
   * @param {Matrix3} m - The normal matrix to apply.
   * @return {InterleavedBufferAttribute} A reference to this instance.
   */
  applyNormalMatrix(e) {
    for (let t = 0, i = this.count; t < i; t++)
      ii.fromBufferAttribute(this, t), ii.applyNormalMatrix(e), this.setXYZ(t, ii.x, ii.y, ii.z);
    return this;
  }
  /**
   * Applies the given 4x4 matrix to the given attribute. Only works with
   * item size `3` and with direction vectors.
   *
   * @param {Matrix4} m - The matrix to apply.
   * @return {InterleavedBufferAttribute} A reference to this instance.
   */
  transformDirection(e) {
    for (let t = 0, i = this.count; t < i; t++)
      ii.fromBufferAttribute(this, t), ii.transformDirection(e), this.setXYZ(t, ii.x, ii.y, ii.z);
    return this;
  }
  /**
   * Returns the given component of the vector at the given index.
   *
   * @param {number} index - The index into the buffer attribute.
   * @param {number} component - The component index.
   * @return {number} The returned value.
   */
  getComponent(e, t) {
    let i = this.array[e * this.data.stride + this.offset + t];
    return this.normalized && (i = ai(i, this.array)), i;
  }
  /**
   * Sets the given value to the given component of the vector at the given index.
   *
   * @param {number} index - The index into the buffer attribute.
   * @param {number} component - The component index.
   * @param {number} value - The value to set.
   * @return {InterleavedBufferAttribute} A reference to this instance.
   */
  setComponent(e, t, i) {
    return this.normalized && (i = Xe(i, this.array)), this.data.array[e * this.data.stride + this.offset + t] = i, this;
  }
  /**
   * Sets the x component of the vector at the given index.
   *
   * @param {number} index - The index into the buffer attribute.
   * @param {number} x - The value to set.
   * @return {InterleavedBufferAttribute} A reference to this instance.
   */
  setX(e, t) {
    return this.normalized && (t = Xe(t, this.array)), this.data.array[e * this.data.stride + this.offset] = t, this;
  }
  /**
   * Sets the y component of the vector at the given index.
   *
   * @param {number} index - The index into the buffer attribute.
   * @param {number} y - The value to set.
   * @return {InterleavedBufferAttribute} A reference to this instance.
   */
  setY(e, t) {
    return this.normalized && (t = Xe(t, this.array)), this.data.array[e * this.data.stride + this.offset + 1] = t, this;
  }
  /**
   * Sets the z component of the vector at the given index.
   *
   * @param {number} index - The index into the buffer attribute.
   * @param {number} z - The value to set.
   * @return {InterleavedBufferAttribute} A reference to this instance.
   */
  setZ(e, t) {
    return this.normalized && (t = Xe(t, this.array)), this.data.array[e * this.data.stride + this.offset + 2] = t, this;
  }
  /**
   * Sets the w component of the vector at the given index.
   *
   * @param {number} index - The index into the buffer attribute.
   * @param {number} w - The value to set.
   * @return {InterleavedBufferAttribute} A reference to this instance.
   */
  setW(e, t) {
    return this.normalized && (t = Xe(t, this.array)), this.data.array[e * this.data.stride + this.offset + 3] = t, this;
  }
  /**
   * Returns the x component of the vector at the given index.
   *
   * @param {number} index - The index into the buffer attribute.
   * @return {number} The x component.
   */
  getX(e) {
    let t = this.data.array[e * this.data.stride + this.offset];
    return this.normalized && (t = ai(t, this.array)), t;
  }
  /**
   * Returns the y component of the vector at the given index.
   *
   * @param {number} index - The index into the buffer attribute.
   * @return {number} The y component.
   */
  getY(e) {
    let t = this.data.array[e * this.data.stride + this.offset + 1];
    return this.normalized && (t = ai(t, this.array)), t;
  }
  /**
   * Returns the z component of the vector at the given index.
   *
   * @param {number} index - The index into the buffer attribute.
   * @return {number} The z component.
   */
  getZ(e) {
    let t = this.data.array[e * this.data.stride + this.offset + 2];
    return this.normalized && (t = ai(t, this.array)), t;
  }
  /**
   * Returns the w component of the vector at the given index.
   *
   * @param {number} index - The index into the buffer attribute.
   * @return {number} The w component.
   */
  getW(e) {
    let t = this.data.array[e * this.data.stride + this.offset + 3];
    return this.normalized && (t = ai(t, this.array)), t;
  }
  /**
   * Sets the x and y component of the vector at the given index.
   *
   * @param {number} index - The index into the buffer attribute.
   * @param {number} x - The value for the x component to set.
   * @param {number} y - The value for the y component to set.
   * @return {InterleavedBufferAttribute} A reference to this instance.
   */
  setXY(e, t, i) {
    return e = e * this.data.stride + this.offset, this.normalized && (t = Xe(t, this.array), i = Xe(i, this.array)), this.data.array[e + 0] = t, this.data.array[e + 1] = i, this;
  }
  /**
   * Sets the x, y and z component of the vector at the given index.
   *
   * @param {number} index - The index into the buffer attribute.
   * @param {number} x - The value for the x component to set.
   * @param {number} y - The value for the y component to set.
   * @param {number} z - The value for the z component to set.
   * @return {InterleavedBufferAttribute} A reference to this instance.
   */
  setXYZ(e, t, i, n) {
    return e = e * this.data.stride + this.offset, this.normalized && (t = Xe(t, this.array), i = Xe(i, this.array), n = Xe(n, this.array)), this.data.array[e + 0] = t, this.data.array[e + 1] = i, this.data.array[e + 2] = n, this;
  }
  /**
   * Sets the x, y, z and w component of the vector at the given index.
   *
   * @param {number} index - The index into the buffer attribute.
   * @param {number} x - The value for the x component to set.
   * @param {number} y - The value for the y component to set.
   * @param {number} z - The value for the z component to set.
   * @param {number} w - The value for the w component to set.
   * @return {InterleavedBufferAttribute} A reference to this instance.
   */
  setXYZW(e, t, i, n, s) {
    return e = e * this.data.stride + this.offset, this.normalized && (t = Xe(t, this.array), i = Xe(i, this.array), n = Xe(n, this.array), s = Xe(s, this.array)), this.data.array[e + 0] = t, this.data.array[e + 1] = i, this.data.array[e + 2] = n, this.data.array[e + 3] = s, this;
  }
  /**
   * Returns a new buffer attribute with copied values from this instance.
   *
   * If no parameter is provided, cloning an interleaved buffer attribute will de-interleave buffer data.
   *
   * @param {Object} [data] - An object with interleaved buffers that allows to retain the interleaved property.
   * @return {BufferAttribute|InterleavedBufferAttribute} A clone of this instance.
   */
  clone(e) {
    if (e === void 0) {
      console.log("THREE.InterleavedBufferAttribute.clone(): Cloning an interleaved buffer attribute will de-interleave buffer data.");
      const t = [];
      for (let i = 0; i < this.count; i++) {
        const n = i * this.data.stride + this.offset;
        for (let s = 0; s < this.itemSize; s++)
          t.push(this.data.array[n + s]);
      }
      return new it(new this.array.constructor(t), this.itemSize, this.normalized);
    } else
      return e.interleavedBuffers === void 0 && (e.interleavedBuffers = {}), e.interleavedBuffers[this.data.uuid] === void 0 && (e.interleavedBuffers[this.data.uuid] = this.data.clone(e)), new Ei(e.interleavedBuffers[this.data.uuid], this.itemSize, this.offset, this.normalized);
  }
  /**
   * Serializes the buffer attribute into JSON.
   *
   * If no parameter is provided, cloning an interleaved buffer attribute will de-interleave buffer data.
   *
   * @param {Object} [data] - An optional value holding meta information about the serialization.
   * @return {Object} A JSON object representing the serialized buffer attribute.
   */
  toJSON(e) {
    if (e === void 0) {
      console.log("THREE.InterleavedBufferAttribute.toJSON(): Serializing an interleaved buffer attribute will de-interleave buffer data.");
      const t = [];
      for (let i = 0; i < this.count; i++) {
        const n = i * this.data.stride + this.offset;
        for (let s = 0; s < this.itemSize; s++)
          t.push(this.data.array[n + s]);
      }
      return {
        itemSize: this.itemSize,
        type: this.array.constructor.name,
        array: t,
        normalized: this.normalized
      };
    } else
      return e.interleavedBuffers === void 0 && (e.interleavedBuffers = {}), e.interleavedBuffers[this.data.uuid] === void 0 && (e.interleavedBuffers[this.data.uuid] = this.data.toJSON(e)), {
        isInterleavedBufferAttribute: !0,
        itemSize: this.itemSize,
        data: this.data.uuid,
        offset: this.offset,
        normalized: this.normalized
      };
  }
}
class Jl extends qt {
  /**
   * Constructs a new sprite material.
   *
   * @param {Object} [parameters] - An object with one or more properties
   * defining the material's appearance. Any property of the material
   * (including any property from inherited materials) can be passed
   * in here. Color values can be passed any type of value accepted
   * by {@link Color#set}.
   */
  constructor(e) {
    super(), this.isSpriteMaterial = !0, this.type = "SpriteMaterial", this.color = new oe(16777215), this.map = null, this.alphaMap = null, this.rotation = 0, this.sizeAttenuation = !0, this.transparent = !0, this.fog = !0, this.setValues(e);
  }
  copy(e) {
    return super.copy(e), this.color.copy(e.color), this.map = e.map, this.alphaMap = e.alphaMap, this.rotation = e.rotation, this.sizeAttenuation = e.sizeAttenuation, this.fog = e.fog, this;
  }
}
let Vs;
const Lr = /* @__PURE__ */ new b(), Gs = /* @__PURE__ */ new b(), Ws = /* @__PURE__ */ new b(), Xs = /* @__PURE__ */ new H(), Ir = /* @__PURE__ */ new H(), mm = /* @__PURE__ */ new Ne(), qa = /* @__PURE__ */ new b(), Dr = /* @__PURE__ */ new b(), Za = /* @__PURE__ */ new b(), vu = /* @__PURE__ */ new H(), zc = /* @__PURE__ */ new H(), xu = /* @__PURE__ */ new H();
class Qr extends tt {
  /**
   * Constructs a new sprite.
   *
   * @param {(SpriteMaterial|SpriteNodeMaterial)} [material] - The sprite material.
   */
  constructor(e = new Jl()) {
    if (super(), this.isSprite = !0, this.type = "Sprite", Vs === void 0) {
      Vs = new Ue();
      const t = new Float32Array([
        -0.5,
        -0.5,
        0,
        0,
        0,
        0.5,
        -0.5,
        0,
        1,
        0,
        0.5,
        0.5,
        0,
        1,
        1,
        -0.5,
        0.5,
        0,
        0,
        1
      ]), i = new Kl(t, 5);
      Vs.setIndex([0, 1, 2, 0, 2, 3]), Vs.setAttribute("position", new Ei(i, 3, 0, !1)), Vs.setAttribute("uv", new Ei(i, 2, 3, !1));
    }
    this.geometry = Vs, this.material = e, this.center = new H(0.5, 0.5), this.count = 1;
  }
  /**
   * Computes intersection points between a casted ray and this sprite.
   *
   * @param {Raycaster} raycaster - The raycaster.
   * @param {Array<Object>} intersects - The target array that holds the intersection points.
   */
  raycast(e, t) {
    e.camera === null && console.error('THREE.Sprite: "Raycaster.camera" needs to be set in order to raycast against sprites.'), Gs.setFromMatrixScale(this.matrixWorld), mm.copy(e.camera.matrixWorld), this.modelViewMatrix.multiplyMatrices(e.camera.matrixWorldInverse, this.matrixWorld), Ws.setFromMatrixPosition(this.modelViewMatrix), e.camera.isPerspectiveCamera && this.material.sizeAttenuation === !1 && Gs.multiplyScalar(-Ws.z);
    const i = this.material.rotation;
    let n, s;
    i !== 0 && (s = Math.cos(i), n = Math.sin(i));
    const a = this.center;
    Ya(qa.set(-0.5, -0.5, 0), Ws, a, Gs, n, s), Ya(Dr.set(0.5, -0.5, 0), Ws, a, Gs, n, s), Ya(Za.set(0.5, 0.5, 0), Ws, a, Gs, n, s), vu.set(0, 0), zc.set(1, 0), xu.set(1, 1);
    let o = e.ray.intersectTriangle(qa, Dr, Za, !1, Lr);
    if (o === null && (Ya(Dr.set(-0.5, 0.5, 0), Ws, a, Gs, n, s), zc.set(0, 1), o = e.ray.intersectTriangle(qa, Za, Dr, !1, Lr), o === null))
      return;
    const l = e.ray.origin.distanceTo(Lr);
    l < e.near || l > e.far || t.push({
      distance: l,
      point: Lr.clone(),
      uv: pi.getInterpolation(Lr, qa, Dr, Za, vu, zc, xu, new H()),
      face: null,
      object: this
    });
  }
  copy(e, t) {
    return super.copy(e, t), e.center !== void 0 && this.center.copy(e.center), this.material = e.material, this;
  }
}
function Ya(r, e, t, i, n, s) {
  Xs.subVectors(r, t).addScalar(0.5).multiply(i), n !== void 0 ? (Ir.x = s * Xs.x - n * Xs.y, Ir.y = n * Xs.x + s * Xs.y) : Ir.copy(Xs), r.copy(e), r.x += Ir.x, r.y += Ir.y, r.applyMatrix4(mm);
}
const ja = /* @__PURE__ */ new b(), bu = /* @__PURE__ */ new b();
class gm extends tt {
  /**
   * Constructs a new LOD.
   */
  constructor() {
    super(), this.isLOD = !0, this._currentLevel = 0, this.type = "LOD", Object.defineProperties(this, {
      /**
       * This array holds the LOD levels.
       *
       * @name LOD#levels
       * @type {Array<{object:Object3D,distance:number,hysteresis:number}>}
       */
      levels: {
        enumerable: !0,
        value: []
      }
    }), this.autoUpdate = !0;
  }
  copy(e) {
    super.copy(e, !1);
    const t = e.levels;
    for (let i = 0, n = t.length; i < n; i++) {
      const s = t[i];
      this.addLevel(s.object.clone(), s.distance, s.hysteresis);
    }
    return this.autoUpdate = e.autoUpdate, this;
  }
  /**
   * Adds a mesh that will display at a certain distance and greater. Typically
   * the further away the distance, the lower the detail on the mesh.
   *
   * @param {Object3D} object - The 3D object to display at this level.
   * @param {number} [distance=0] - The distance at which to display this level of detail.
   * @param {number} [hysteresis=0] - Threshold used to avoid flickering at LOD boundaries, as a fraction of distance.
   * @return {LOD} A reference to this instance.
   */
  addLevel(e, t = 0, i = 0) {
    t = Math.abs(t);
    const n = this.levels;
    let s;
    for (s = 0; s < n.length && !(t < n[s].distance); s++)
      ;
    return n.splice(s, 0, { distance: t, hysteresis: i, object: e }), this.add(e), this;
  }
  /**
   * Removes an existing level, based on the distance from the camera.
   * Returns `true` when the level has been removed. Otherwise `false`.
   *
   * @param {number} distance - Distance of the level to remove.
   * @return {boolean} Whether the level has been removed or not.
   */
  removeLevel(e) {
    const t = this.levels;
    for (let i = 0; i < t.length; i++)
      if (t[i].distance === e) {
        const n = t.splice(i, 1);
        return this.remove(n[0].object), !0;
      }
    return !1;
  }
  /**
   * Returns the currently active LOD level index.
   *
   * @return {number} The current active LOD level index.
   */
  getCurrentLevel() {
    return this._currentLevel;
  }
  /**
   * Returns a reference to the first 3D object that is greater than
   * the given distance.
   *
   * @param {number} distance - The LOD distance.
   * @return {?Object3D} The found 3D object. `null` if no 3D object has been found.
   */
  getObjectForDistance(e) {
    const t = this.levels;
    if (t.length > 0) {
      let i, n;
      for (i = 1, n = t.length; i < n; i++) {
        let s = t[i].distance;
        if (t[i].object.visible && (s -= s * t[i].hysteresis), e < s)
          break;
      }
      return t[i - 1].object;
    }
    return null;
  }
  /**
   * Computes intersection points between a casted ray and this LOD.
   *
   * @param {Raycaster} raycaster - The raycaster.
   * @param {Array<Object>} intersects - The target array that holds the intersection points.
   */
  raycast(e, t) {
    if (this.levels.length > 0) {
      ja.setFromMatrixPosition(this.matrixWorld);
      const n = e.ray.origin.distanceTo(ja);
      this.getObjectForDistance(n).raycast(e, t);
    }
  }
  /**
   * Updates the LOD by computing which LOD level should be visible according
   * to the current distance of the given camera.
   *
   * @param {Camera} camera - The camera the scene is rendered with.
   */
  update(e) {
    const t = this.levels;
    if (t.length > 1) {
      ja.setFromMatrixPosition(e.matrixWorld), bu.setFromMatrixPosition(this.matrixWorld);
      const i = ja.distanceTo(bu) / e.zoom;
      t[0].object.visible = !0;
      let n, s;
      for (n = 1, s = t.length; n < s; n++) {
        let a = t[n].distance;
        if (t[n].object.visible && (a -= a * t[n].hysteresis), i >= a)
          t[n - 1].object.visible = !1, t[n].object.visible = !0;
        else
          break;
      }
      for (this._currentLevel = n - 1; n < s; n++)
        t[n].object.visible = !1;
    }
  }
  toJSON(e) {
    const t = super.toJSON(e);
    this.autoUpdate === !1 && (t.object.autoUpdate = !1), t.object.levels = [];
    const i = this.levels;
    for (let n = 0, s = i.length; n < s; n++) {
      const a = i[n];
      t.object.levels.push({
        object: a.object.uuid,
        distance: a.distance,
        hysteresis: a.hysteresis
      });
    }
    return t;
  }
}
const Su = /* @__PURE__ */ new b(), Mu = /* @__PURE__ */ new Ye(), wu = /* @__PURE__ */ new Ye(), ly = /* @__PURE__ */ new b(), Eu = /* @__PURE__ */ new Ne(), $a = /* @__PURE__ */ new b(), Hc = /* @__PURE__ */ new Lt(), Tu = /* @__PURE__ */ new Ne(), Vc = /* @__PURE__ */ new ws();
class _m extends Je {
  /**
   * Constructs a new skinned mesh.
   *
   * @param {BufferGeometry} [geometry] - The mesh geometry.
   * @param {Material|Array<Material>} [material] - The mesh material.
   */
  constructor(e, t) {
    super(e, t), this.isSkinnedMesh = !0, this.type = "SkinnedMesh", this.bindMode = Nh, this.bindMatrix = new Ne(), this.bindMatrixInverse = new Ne(), this.boundingBox = null, this.boundingSphere = null;
  }
  /**
   * Computes the bounding box of the skinned mesh, and updates {@link SkinnedMesh#boundingBox}.
   * The bounding box is not automatically computed by the engine; this method must be called by your app.
   * If the skinned mesh is animated, the bounding box should be recomputed per frame in order to reflect
   * the current animation state.
   */
  computeBoundingBox() {
    const e = this.geometry;
    this.boundingBox === null && (this.boundingBox = new Tt()), this.boundingBox.makeEmpty();
    const t = e.getAttribute("position");
    for (let i = 0; i < t.count; i++)
      this.getVertexPosition(i, $a), this.boundingBox.expandByPoint($a);
  }
  /**
   * Computes the bounding sphere of the skinned mesh, and updates {@link SkinnedMesh#boundingSphere}.
   * The bounding sphere is automatically computed by the engine once when it is needed, e.g., for ray casting
   * and view frustum culling. If the skinned mesh is animated, the bounding sphere should be recomputed
   * per frame in order to reflect the current animation state.
   */
  computeBoundingSphere() {
    const e = this.geometry;
    this.boundingSphere === null && (this.boundingSphere = new Lt()), this.boundingSphere.makeEmpty();
    const t = e.getAttribute("position");
    for (let i = 0; i < t.count; i++)
      this.getVertexPosition(i, $a), this.boundingSphere.expandByPoint($a);
  }
  copy(e, t) {
    return super.copy(e, t), this.bindMode = e.bindMode, this.bindMatrix.copy(e.bindMatrix), this.bindMatrixInverse.copy(e.bindMatrixInverse), this.skeleton = e.skeleton, e.boundingBox !== null && (this.boundingBox = e.boundingBox.clone()), e.boundingSphere !== null && (this.boundingSphere = e.boundingSphere.clone()), this;
  }
  raycast(e, t) {
    const i = this.material, n = this.matrixWorld;
    i !== void 0 && (this.boundingSphere === null && this.computeBoundingSphere(), Hc.copy(this.boundingSphere), Hc.applyMatrix4(n), e.ray.intersectsSphere(Hc) !== !1 && (Tu.copy(n).invert(), Vc.copy(e.ray).applyMatrix4(Tu), !(this.boundingBox !== null && Vc.intersectsBox(this.boundingBox) === !1) && this._computeIntersections(e, t, Vc)));
  }
  getVertexPosition(e, t) {
    return super.getVertexPosition(e, t), this.applyBoneTransform(e, t), t;
  }
  /**
   * Binds the given skeleton to the skinned mesh.
   *
   * @param {Skeleton} skeleton - The skeleton to bind.
   * @param {Matrix4} [bindMatrix] - The bind matrix. If no bind matrix is provided,
   * the skinned mesh's world matrix will be used instead.
   */
  bind(e, t) {
    this.skeleton = e, t === void 0 && (this.updateMatrixWorld(!0), this.skeleton.calculateInverses(), t = this.matrixWorld), this.bindMatrix.copy(t), this.bindMatrixInverse.copy(t).invert();
  }
  /**
   * This method sets the skinned mesh in the rest pose).
   */
  pose() {
    this.skeleton.pose();
  }
  /**
   * Normalizes the skin weights which are defined as a buffer attribute
   * in the skinned mesh's geometry.
   */
  normalizeSkinWeights() {
    const e = new Ye(), t = this.geometry.attributes.skinWeight;
    for (let i = 0, n = t.count; i < n; i++) {
      e.fromBufferAttribute(t, i);
      const s = 1 / e.manhattanLength();
      s !== 1 / 0 ? e.multiplyScalar(s) : e.set(1, 0, 0, 0), t.setXYZW(i, e.x, e.y, e.z, e.w);
    }
  }
  updateMatrixWorld(e) {
    super.updateMatrixWorld(e), this.bindMode === Nh ? this.bindMatrixInverse.copy(this.matrixWorld).invert() : this.bindMode === jf ? this.bindMatrixInverse.copy(this.bindMatrix).invert() : console.warn("THREE.SkinnedMesh: Unrecognized bindMode: " + this.bindMode);
  }
  /**
   * Applies the bone transform associated with the given index to the given
   * vertex position. Returns the updated vector.
   *
   * @param {number} index - The vertex index.
   * @param {Vector3} target - The target object that is used to store the method's result.
   * the skinned mesh's world matrix will be used instead.
   * @return {Vector3} The updated vertex position.
   */
  applyBoneTransform(e, t) {
    const i = this.skeleton, n = this.geometry;
    Mu.fromBufferAttribute(n.attributes.skinIndex, e), wu.fromBufferAttribute(n.attributes.skinWeight, e), Su.copy(t).applyMatrix4(this.bindMatrix), t.set(0, 0, 0);
    for (let s = 0; s < 4; s++) {
      const a = wu.getComponent(s);
      if (a !== 0) {
        const o = Mu.getComponent(s);
        Eu.multiplyMatrices(i.bones[o].matrixWorld, i.boneInverses[o]), t.addScaledVector(ly.copy(Su).applyMatrix4(Eu), a);
      }
    }
    return t.applyMatrix4(this.bindMatrixInverse);
  }
}
class ud extends tt {
  /**
   * Constructs a new bone.
   */
  constructor() {
    super(), this.isBone = !0, this.type = "Bone";
  }
}
class tn extends Et {
  /**
   * Constructs a new data texture.
   *
   * @param {?TypedArray} [data=null] - The buffer data.
   * @param {number} [width=1] - The width of the texture.
   * @param {number} [height=1] - The height of the texture.
   * @param {number} [format=RGBAFormat] - The texture format.
   * @param {number} [type=UnsignedByteType] - The texture type.
   * @param {number} [mapping=Texture.DEFAULT_MAPPING] - The texture mapping.
   * @param {number} [wrapS=ClampToEdgeWrapping] - The wrapS value.
   * @param {number} [wrapT=ClampToEdgeWrapping] - The wrapT value.
   * @param {number} [magFilter=NearestFilter] - The mag filter value.
   * @param {number} [minFilter=NearestFilter] - The min filter value.
   * @param {number} [anisotropy=Texture.DEFAULT_ANISOTROPY] - The anisotropy value.
   * @param {string} [colorSpace=NoColorSpace] - The color space.
   */
  constructor(e = null, t = 1, i = 1, n, s, a, o, l, c = Xt, h = Xt, d, u) {
    super(null, a, o, l, c, h, n, s, d, u), this.isDataTexture = !0, this.image = { data: e, width: t, height: i }, this.generateMipmaps = !1, this.flipY = !1, this.unpackAlignment = 1;
  }
}
const Au = /* @__PURE__ */ new Ne(), cy = /* @__PURE__ */ new Ne();
class Ql {
  /**
   * Constructs a new skeleton.
   *
   * @param {Array<Bone>} [bones] - An array of bones.
   * @param {Array<Matrix4>} [boneInverses] - An array of bone inverse matrices.
   * If not provided, these matrices will be computed automatically via {@link Skeleton#calculateInverses}.
   */
  constructor(e = [], t = []) {
    this.uuid = Ti(), this.bones = e.slice(0), this.boneInverses = t, this.boneMatrices = null, this.boneTexture = null, this.init();
  }
  /**
   * Initializes the skeleton. This method gets automatically called by the constructor
   * but depending on how the skeleton is created it might be necessary to call this method
   * manually.
   */
  init() {
    const e = this.bones, t = this.boneInverses;
    if (this.boneMatrices = new Float32Array(e.length * 16), t.length === 0)
      this.calculateInverses();
    else if (e.length !== t.length) {
      console.warn("THREE.Skeleton: Number of inverse bone matrices does not match amount of bones."), this.boneInverses = [];
      for (let i = 0, n = this.bones.length; i < n; i++)
        this.boneInverses.push(new Ne());
    }
  }
  /**
   * Computes the bone inverse matrices. This method resets {@link Skeleton#boneInverses}
   * and fills it with new matrices.
   */
  calculateInverses() {
    this.boneInverses.length = 0;
    for (let e = 0, t = this.bones.length; e < t; e++) {
      const i = new Ne();
      this.bones[e] && i.copy(this.bones[e].matrixWorld).invert(), this.boneInverses.push(i);
    }
  }
  /**
   * Resets the skeleton to the base pose.
   */
  pose() {
    for (let e = 0, t = this.bones.length; e < t; e++) {
      const i = this.bones[e];
      i && i.matrixWorld.copy(this.boneInverses[e]).invert();
    }
    for (let e = 0, t = this.bones.length; e < t; e++) {
      const i = this.bones[e];
      i && (i.parent && i.parent.isBone ? (i.matrix.copy(i.parent.matrixWorld).invert(), i.matrix.multiply(i.matrixWorld)) : i.matrix.copy(i.matrixWorld), i.matrix.decompose(i.position, i.quaternion, i.scale));
    }
  }
  /**
   * Resets the skeleton to the base pose.
   */
  update() {
    const e = this.bones, t = this.boneInverses, i = this.boneMatrices, n = this.boneTexture;
    for (let s = 0, a = e.length; s < a; s++) {
      const o = e[s] ? e[s].matrixWorld : cy;
      Au.multiplyMatrices(o, t[s]), Au.toArray(i, s * 16);
    }
    n !== null && (n.needsUpdate = !0);
  }
  /**
   * Returns a new skeleton with copied values from this instance.
   *
   * @return {Skeleton} A clone of this instance.
   */
  clone() {
    return new Ql(this.bones, this.boneInverses);
  }
  /**
   * Computes a data texture for passing bone data to the vertex shader.
   *
   * @return {Skeleton} A reference of this instance.
   */
  computeBoneTexture() {
    let e = Math.sqrt(this.bones.length * 4);
    e = Math.ceil(e / 4) * 4, e = Math.max(e, 4);
    const t = new Float32Array(e * e * 4);
    t.set(this.boneMatrices);
    const i = new tn(t, e, e, oi, mi);
    return i.needsUpdate = !0, this.boneMatrices = t, this.boneTexture = i, this;
  }
  /**
   * Searches through the skeleton's bone array and returns the first with a
   * matching name.
   *
   * @param {string} name - The name of the bone.
   * @return {Bone|undefined} The found bone. `undefined` if no bone has been found.
   */
  getBoneByName(e) {
    for (let t = 0, i = this.bones.length; t < i; t++) {
      const n = this.bones[t];
      if (n.name === e)
        return n;
    }
  }
  /**
   * Frees the GPU-related resources allocated by this instance. Call this
   * method whenever this instance is no longer used in your app.
   */
  dispose() {
    this.boneTexture !== null && (this.boneTexture.dispose(), this.boneTexture = null);
  }
  /**
   * Setups the skeleton by the given JSON and bones.
   *
   * @param {Object} json - The skeleton as serialized JSON.
   * @param {Object<string, Bone>} bones - An array of bones.
   * @return {Skeleton} A reference of this instance.
   */
  fromJSON(e, t) {
    this.uuid = e.uuid;
    for (let i = 0, n = e.bones.length; i < n; i++) {
      const s = e.bones[i];
      let a = t[s];
      a === void 0 && (console.warn("THREE.Skeleton: No bone found with UUID:", s), a = new ud()), this.bones.push(a), this.boneInverses.push(new Ne().fromArray(e.boneInverses[i]));
    }
    return this.init(), this;
  }
  /**
   * Serializes the skeleton into JSON.
   *
   * @return {Object} A JSON object representing the serialized skeleton.
   * @see {@link ObjectLoader#parse}
   */
  toJSON() {
    const e = {
      metadata: {
        version: 4.7,
        type: "Skeleton",
        generator: "Skeleton.toJSON"
      },
      bones: [],
      boneInverses: []
    };
    e.uuid = this.uuid;
    const t = this.bones, i = this.boneInverses;
    for (let n = 0, s = t.length; n < s; n++) {
      const a = t[n];
      e.bones.push(a.uuid);
      const o = i[n];
      e.boneInverses.push(o.toArray());
    }
    return e;
  }
}
class gr extends it {
  /**
   * Constructs a new instanced buffer attribute.
   *
   * @param {TypedArray} array - The array holding the attribute data.
   * @param {number} itemSize - The item size.
   * @param {boolean} [normalized=false] - Whether the data are normalized or not.
   * @param {number} [meshPerAttribute=1] - How often a value of this buffer attribute should be repeated.
   */
  constructor(e, t, i, n = 1) {
    super(e, t, i), this.isInstancedBufferAttribute = !0, this.meshPerAttribute = n;
  }
  copy(e) {
    return super.copy(e), this.meshPerAttribute = e.meshPerAttribute, this;
  }
  toJSON() {
    const e = super.toJSON();
    return e.meshPerAttribute = this.meshPerAttribute, e.isInstancedBufferAttribute = !0, e;
  }
}
const qs = /* @__PURE__ */ new Ne(), Cu = /* @__PURE__ */ new Ne(), Ka = [], Ru = /* @__PURE__ */ new Tt(), hy = /* @__PURE__ */ new Ne(), Nr = /* @__PURE__ */ new Je(), Ur = /* @__PURE__ */ new Lt();
class ym extends Je {
  /**
   * Constructs a new instanced mesh.
   *
   * @param {BufferGeometry} [geometry] - The mesh geometry.
   * @param {Material|Array<Material>} [material] - The mesh material.
   * @param {number} count - The number of instances.
   */
  constructor(e, t, i) {
    super(e, t), this.isInstancedMesh = !0, this.instanceMatrix = new gr(new Float32Array(i * 16), 16), this.instanceColor = null, this.morphTexture = null, this.count = i, this.boundingBox = null, this.boundingSphere = null;
    for (let n = 0; n < i; n++)
      this.setMatrixAt(n, hy);
  }
  /**
   * Computes the bounding box of the instanced mesh, and updates {@link InstancedMesh#boundingBox}.
   * The bounding box is not automatically computed by the engine; this method must be called by your app.
   * You may need to recompute the bounding box if an instance is transformed via {@link InstancedMesh#setMatrixAt}.
   */
  computeBoundingBox() {
    const e = this.geometry, t = this.count;
    this.boundingBox === null && (this.boundingBox = new Tt()), e.boundingBox === null && e.computeBoundingBox(), this.boundingBox.makeEmpty();
    for (let i = 0; i < t; i++)
      this.getMatrixAt(i, qs), Ru.copy(e.boundingBox).applyMatrix4(qs), this.boundingBox.union(Ru);
  }
  /**
   * Computes the bounding sphere of the instanced mesh, and updates {@link InstancedMesh#boundingSphere}
   * The engine automatically computes the bounding sphere when it is needed, e.g., for ray casting or view frustum culling.
   * You may need to recompute the bounding sphere if an instance is transformed via {@link InstancedMesh#setMatrixAt}.
   */
  computeBoundingSphere() {
    const e = this.geometry, t = this.count;
    this.boundingSphere === null && (this.boundingSphere = new Lt()), e.boundingSphere === null && e.computeBoundingSphere(), this.boundingSphere.makeEmpty();
    for (let i = 0; i < t; i++)
      this.getMatrixAt(i, qs), Ur.copy(e.boundingSphere).applyMatrix4(qs), this.boundingSphere.union(Ur);
  }
  copy(e, t) {
    return super.copy(e, t), this.instanceMatrix.copy(e.instanceMatrix), e.morphTexture !== null && (this.morphTexture = e.morphTexture.clone()), e.instanceColor !== null && (this.instanceColor = e.instanceColor.clone()), this.count = e.count, e.boundingBox !== null && (this.boundingBox = e.boundingBox.clone()), e.boundingSphere !== null && (this.boundingSphere = e.boundingSphere.clone()), this;
  }
  /**
   * Gets the color of the defined instance.
   *
   * @param {number} index - The instance index.
   * @param {Color} color - The target object that is used to store the method's result.
   */
  getColorAt(e, t) {
    t.fromArray(this.instanceColor.array, e * 3);
  }
  /**
   * Gets the local transformation matrix of the defined instance.
   *
   * @param {number} index - The instance index.
   * @param {Matrix4} matrix - The target object that is used to store the method's result.
   */
  getMatrixAt(e, t) {
    t.fromArray(this.instanceMatrix.array, e * 16);
  }
  /**
   * Gets the morph target weights of the defined instance.
   *
   * @param {number} index - The instance index.
   * @param {Mesh} object - The target object that is used to store the method's result.
   */
  getMorphAt(e, t) {
    const i = t.morphTargetInfluences, n = this.morphTexture.source.data.data, s = i.length + 1, a = e * s + 1;
    for (let o = 0; o < i.length; o++)
      i[o] = n[a + o];
  }
  raycast(e, t) {
    const i = this.matrixWorld, n = this.count;
    if (Nr.geometry = this.geometry, Nr.material = this.material, Nr.material !== void 0 && (this.boundingSphere === null && this.computeBoundingSphere(), Ur.copy(this.boundingSphere), Ur.applyMatrix4(i), e.ray.intersectsSphere(Ur) !== !1))
      for (let s = 0; s < n; s++) {
        this.getMatrixAt(s, qs), Cu.multiplyMatrices(i, qs), Nr.matrixWorld = Cu, Nr.raycast(e, Ka);
        for (let a = 0, o = Ka.length; a < o; a++) {
          const l = Ka[a];
          l.instanceId = s, l.object = this, t.push(l);
        }
        Ka.length = 0;
      }
  }
  /**
   * Sets the given color to the defined instance. Make sure you set the `needsUpdate` flag of
   * {@link InstancedMesh#instanceColor} to `true` after updating all the colors.
   *
   * @param {number} index - The instance index.
   * @param {Color} color - The instance color.
   */
  setColorAt(e, t) {
    this.instanceColor === null && (this.instanceColor = new gr(new Float32Array(this.instanceMatrix.count * 3).fill(1), 3)), t.toArray(this.instanceColor.array, e * 3);
  }
  /**
   * Sets the given local transformation matrix to the defined instance. Make sure you set the `needsUpdate` flag of
   * {@link InstancedMesh#instanceMatrix} to `true` after updating all the colors.
   *
   * @param {number} index - The instance index.
   * @param {Matrix4} matrix - The local transformation.
   */
  setMatrixAt(e, t) {
    t.toArray(this.instanceMatrix.array, e * 16);
  }
  /**
   * Sets the morph target weights to the defined instance. Make sure you set the `needsUpdate` flag of
   * {@link InstancedMesh#morphTexture} to `true` after updating all the influences.
   *
   * @param {number} index - The instance index.
   * @param {Mesh} object -  A mesh which `morphTargetInfluences` property containing the morph target weights
   * of a single instance.
   */
  setMorphAt(e, t) {
    const i = t.morphTargetInfluences, n = i.length + 1;
    this.morphTexture === null && (this.morphTexture = new tn(new Float32Array(n * this.count), n, this.count, zl, mi));
    const s = this.morphTexture.source.data.data;
    let a = 0;
    for (let c = 0; c < i.length; c++)
      a += i[c];
    const o = this.geometry.morphTargetsRelative ? 1 : 1 - a, l = n * e;
    s[l] = o, s.set(i, l + 1);
  }
  updateMorphTargets() {
  }
  /**
   * Frees the GPU-related resources allocated by this instance. Call this
   * method whenever this instance is no longer used in your app.
   */
  dispose() {
    this.dispatchEvent({ type: "dispose" }), this.morphTexture !== null && (this.morphTexture.dispose(), this.morphTexture = null);
  }
}
const Gc = /* @__PURE__ */ new b(), dy = /* @__PURE__ */ new b(), uy = /* @__PURE__ */ new He();
class $i {
  /**
   * Constructs a new plane.
   *
   * @param {Vector3} [normal=(1,0,0)] - A unit length vector defining the normal of the plane.
   * @param {number} [constant=0] - The signed distance from the origin to the plane.
   */
  constructor(e = new b(1, 0, 0), t = 0) {
    this.isPlane = !0, this.normal = e, this.constant = t;
  }
  /**
   * Sets the plane components by copying the given values.
   *
   * @param {Vector3} normal - The normal.
   * @param {number} constant - The constant.
   * @return {Plane} A reference to this plane.
   */
  set(e, t) {
    return this.normal.copy(e), this.constant = t, this;
  }
  /**
   * Sets the plane components by defining `x`, `y`, `z` as the
   * plane normal and `w` as the constant.
   *
   * @param {number} x - The value for the normal's x component.
   * @param {number} y - The value for the normal's y component.
   * @param {number} z - The value for the normal's z component.
   * @param {number} w - The constant value.
   * @return {Plane} A reference to this plane.
   */
  setComponents(e, t, i, n) {
    return this.normal.set(e, t, i), this.constant = n, this;
  }
  /**
   * Sets the plane from the given normal and coplanar point (that is a point
   * that lies onto the plane).
   *
   * @param {Vector3} normal - The normal.
   * @param {Vector3} point - A coplanar point.
   * @return {Plane} A reference to this plane.
   */
  setFromNormalAndCoplanarPoint(e, t) {
    return this.normal.copy(e), this.constant = -t.dot(this.normal), this;
  }
  /**
   * Sets the plane from three coplanar points. The winding order is
   * assumed to be counter-clockwise, and determines the direction of
   * the plane normal.
   *
   * @param {Vector3} a - The first coplanar point.
   * @param {Vector3} b - The second coplanar point.
   * @param {Vector3} c - The third coplanar point.
   * @return {Plane} A reference to this plane.
   */
  setFromCoplanarPoints(e, t, i) {
    const n = Gc.subVectors(i, t).cross(dy.subVectors(e, t)).normalize();
    return this.setFromNormalAndCoplanarPoint(n, e), this;
  }
  /**
   * Copies the values of the given plane to this instance.
   *
   * @param {Plane} plane - The plane to copy.
   * @return {Plane} A reference to this plane.
   */
  copy(e) {
    return this.normal.copy(e.normal), this.constant = e.constant, this;
  }
  /**
   * Normalizes the plane normal and adjusts the constant accordingly.
   *
   * @return {Plane} A reference to this plane.
   */
  normalize() {
    const e = 1 / this.normal.length();
    return this.normal.multiplyScalar(e), this.constant *= e, this;
  }
  /**
   * Negates both the plane normal and the constant.
   *
   * @return {Plane} A reference to this plane.
   */
  negate() {
    return this.constant *= -1, this.normal.negate(), this;
  }
  /**
   * Returns the signed distance from the given point to this plane.
   *
   * @param {Vector3} point - The point to compute the distance for.
   * @return {number} The signed distance.
   */
  distanceToPoint(e) {
    return this.normal.dot(e) + this.constant;
  }
  /**
   * Returns the signed distance from the given sphere to this plane.
   *
   * @param {Sphere} sphere - The sphere to compute the distance for.
   * @return {number} The signed distance.
   */
  distanceToSphere(e) {
    return this.distanceToPoint(e.center) - e.radius;
  }
  /**
   * Projects a the given point onto the plane.
   *
   * @param {Vector3} point - The point to project.
   * @param {Vector3} target - The target vector that is used to store the method's result.
   * @return {Vector3} The projected point on the plane.
   */
  projectPoint(e, t) {
    return t.copy(e).addScaledVector(this.normal, -this.distanceToPoint(e));
  }
  /**
   * Returns the intersection point of the passed line and the plane. Returns
   * `null` if the line does not intersect. Returns the line's starting point if
   * the line is coplanar with the plane.
   *
   * @param {Line3} line - The line to compute the intersection for.
   * @param {Vector3} target - The target vector that is used to store the method's result.
   * @return {?Vector3} The intersection point.
   */
  intersectLine(e, t) {
    const i = e.delta(Gc), n = this.normal.dot(i);
    if (n === 0)
      return this.distanceToPoint(e.start) === 0 ? t.copy(e.start) : null;
    const s = -(e.start.dot(this.normal) + this.constant) / n;
    return s < 0 || s > 1 ? null : t.copy(e.start).addScaledVector(i, s);
  }
  /**
   * Returns `true` if the given line segment intersects with (passes through) the plane.
   *
   * @param {Line3} line - The line to test.
   * @return {boolean} Whether the given line segment intersects with the plane or not.
   */
  intersectsLine(e) {
    const t = this.distanceToPoint(e.start), i = this.distanceToPoint(e.end);
    return t < 0 && i > 0 || i < 0 && t > 0;
  }
  /**
   * Returns `true` if the given bounding box intersects with the plane.
   *
   * @param {Box3} box - The bounding box to test.
   * @return {boolean} Whether the given bounding box intersects with the plane or not.
   */
  intersectsBox(e) {
    return e.intersectsPlane(this);
  }
  /**
   * Returns `true` if the given bounding sphere intersects with the plane.
   *
   * @param {Sphere} sphere - The bounding sphere to test.
   * @return {boolean} Whether the given bounding sphere intersects with the plane or not.
   */
  intersectsSphere(e) {
    return e.intersectsPlane(this);
  }
  /**
   * Returns a coplanar vector to the plane, by calculating the
   * projection of the normal at the origin onto the plane.
   *
   * @param {Vector3} target - The target vector that is used to store the method's result.
   * @return {Vector3} The coplanar point.
   */
  coplanarPoint(e) {
    return e.copy(this.normal).multiplyScalar(-this.constant);
  }
  /**
   * Apply a 4x4 matrix to the plane. The matrix must be an affine, homogeneous transform.
   *
   * The optional normal matrix can be pre-computed like so:
   * ```js
   * const optionalNormalMatrix = new THREE.Matrix3().getNormalMatrix( matrix );
   * ```
   *
   * @param {Matrix4} matrix - The transformation matrix.
   * @param {Matrix4} [optionalNormalMatrix] - A pre-computed normal matrix.
   * @return {Plane} A reference to this plane.
   */
  applyMatrix4(e, t) {
    const i = t || uy.getNormalMatrix(e), n = this.coplanarPoint(Gc).applyMatrix4(e), s = this.normal.applyMatrix3(i).normalize();
    return this.constant = -n.dot(s), this;
  }
  /**
   * Translates the plane by the distance defined by the given offset vector.
   * Note that this only affects the plane constant and will not affect the normal vector.
   *
   * @param {Vector3} offset - The offset vector.
   * @return {Plane} A reference to this plane.
   */
  translate(e) {
    return this.constant -= e.dot(this.normal), this;
  }
  /**
   * Returns `true` if this plane is equal with the given one.
   *
   * @param {Plane} plane - The plane to test for equality.
   * @return {boolean} Whether this plane is equal with the given one.
   */
  equals(e) {
    return e.normal.equals(this.normal) && e.constant === this.constant;
  }
  /**
   * Returns a new plane with copied values from this instance.
   *
   * @return {Plane} A clone of this instance.
   */
  clone() {
    return new this.constructor().copy(this);
  }
}
const jn = /* @__PURE__ */ new Lt(), py = /* @__PURE__ */ new H(0.5, 0.5), Ja = /* @__PURE__ */ new b();
class Sr {
  /**
   * Constructs a new frustum.
   *
   * @param {Plane} [p0] - The first plane that encloses the frustum.
   * @param {Plane} [p1] - The second plane that encloses the frustum.
   * @param {Plane} [p2] - The third plane that encloses the frustum.
   * @param {Plane} [p3] - The fourth plane that encloses the frustum.
   * @param {Plane} [p4] - The fifth plane that encloses the frustum.
   * @param {Plane} [p5] - The sixth plane that encloses the frustum.
   */
  constructor(e = new $i(), t = new $i(), i = new $i(), n = new $i(), s = new $i(), a = new $i()) {
    this.planes = [e, t, i, n, s, a];
  }
  /**
   * Sets the frustum planes by copying the given planes.
   *
   * @param {Plane} [p0] - The first plane that encloses the frustum.
   * @param {Plane} [p1] - The second plane that encloses the frustum.
   * @param {Plane} [p2] - The third plane that encloses the frustum.
   * @param {Plane} [p3] - The fourth plane that encloses the frustum.
   * @param {Plane} [p4] - The fifth plane that encloses the frustum.
   * @param {Plane} [p5] - The sixth plane that encloses the frustum.
   * @return {Frustum} A reference to this frustum.
   */
  set(e, t, i, n, s, a) {
    const o = this.planes;
    return o[0].copy(e), o[1].copy(t), o[2].copy(i), o[3].copy(n), o[4].copy(s), o[5].copy(a), this;
  }
  /**
   * Copies the values of the given frustum to this instance.
   *
   * @param {Frustum} frustum - The frustum to copy.
   * @return {Frustum} A reference to this frustum.
   */
  copy(e) {
    const t = this.planes;
    for (let i = 0; i < 6; i++)
      t[i].copy(e.planes[i]);
    return this;
  }
  /**
   * Sets the frustum planes from the given projection matrix.
   *
   * @param {Matrix4} m - The projection matrix.
   * @param {(WebGLCoordinateSystem|WebGPUCoordinateSystem)} coordinateSystem - The coordinate system.
   * @param {boolean} [reversedDepth=false] - Whether to use a reversed depth.
   * @return {Frustum} A reference to this frustum.
   */
  setFromProjectionMatrix(e, t = wi, i = !1) {
    const n = this.planes, s = e.elements, a = s[0], o = s[1], l = s[2], c = s[3], h = s[4], d = s[5], u = s[6], p = s[7], m = s[8], _ = s[9], g = s[10], f = s[11], v = s[12], x = s[13], y = s[14], A = s[15];
    if (n[0].setComponents(c - a, p - h, f - m, A - v).normalize(), n[1].setComponents(c + a, p + h, f + m, A + v).normalize(), n[2].setComponents(c + o, p + d, f + _, A + x).normalize(), n[3].setComponents(c - o, p - d, f - _, A - x).normalize(), i)
      n[4].setComponents(l, u, g, y).normalize(), n[5].setComponents(c - l, p - u, f - g, A - y).normalize();
    else if (n[4].setComponents(c - l, p - u, f - g, A - y).normalize(), t === wi)
      n[5].setComponents(c + l, p + u, f + g, A + y).normalize();
    else if (t === pr)
      n[5].setComponents(l, u, g, y).normalize();
    else
      throw new Error("THREE.Frustum.setFromProjectionMatrix(): Invalid coordinate system: " + t);
    return this;
  }
  /**
   * Returns `true` if the 3D object's bounding sphere is intersecting this frustum.
   *
   * Note that the 3D object must have a geometry so that the bounding sphere can be calculated.
   *
   * @param {Object3D} object - The 3D object to test.
   * @return {boolean} Whether the 3D object's bounding sphere is intersecting this frustum or not.
   */
  intersectsObject(e) {
    if (e.boundingSphere !== void 0)
      e.boundingSphere === null && e.computeBoundingSphere(), jn.copy(e.boundingSphere).applyMatrix4(e.matrixWorld);
    else {
      const t = e.geometry;
      t.boundingSphere === null && t.computeBoundingSphere(), jn.copy(t.boundingSphere).applyMatrix4(e.matrixWorld);
    }
    return this.intersectsSphere(jn);
  }
  /**
   * Returns `true` if the given sprite is intersecting this frustum.
   *
   * @param {Sprite} sprite - The sprite to test.
   * @return {boolean} Whether the sprite is intersecting this frustum or not.
   */
  intersectsSprite(e) {
    jn.center.set(0, 0, 0);
    const t = py.distanceTo(e.center);
    return jn.radius = 0.7071067811865476 + t, jn.applyMatrix4(e.matrixWorld), this.intersectsSphere(jn);
  }
  /**
   * Returns `true` if the given bounding sphere is intersecting this frustum.
   *
   * @param {Sphere} sphere - The bounding sphere to test.
   * @return {boolean} Whether the bounding sphere is intersecting this frustum or not.
   */
  intersectsSphere(e) {
    const t = this.planes, i = e.center, n = -e.radius;
    for (let s = 0; s < 6; s++)
      if (t[s].distanceToPoint(i) < n)
        return !1;
    return !0;
  }
  /**
   * Returns `true` if the given bounding box is intersecting this frustum.
   *
   * @param {Box3} box - The bounding box to test.
   * @return {boolean} Whether the bounding box is intersecting this frustum or not.
   */
  intersectsBox(e) {
    const t = this.planes;
    for (let i = 0; i < 6; i++) {
      const n = t[i];
      if (Ja.x = n.normal.x > 0 ? e.max.x : e.min.x, Ja.y = n.normal.y > 0 ? e.max.y : e.min.y, Ja.z = n.normal.z > 0 ? e.max.z : e.min.z, n.distanceToPoint(Ja) < 0)
        return !1;
    }
    return !0;
  }
  /**
   * Returns `true` if the given point lies within the frustum.
   *
   * @param {Vector3} point - The point to test.
   * @return {boolean} Whether the point lies within this frustum or not.
   */
  containsPoint(e) {
    const t = this.planes;
    for (let i = 0; i < 6; i++)
      if (t[i].distanceToPoint(e) < 0)
        return !1;
    return !0;
  }
  /**
   * Returns a new frustum with copied values from this instance.
   *
   * @return {Frustum} A clone of this instance.
   */
  clone() {
    return new this.constructor().copy(this);
  }
}
const Wi = /* @__PURE__ */ new Ne(), Xi = /* @__PURE__ */ new Sr();
class ec {
  /**
   * Constructs a new frustum array.
   *
   */
  constructor() {
    this.coordinateSystem = wi;
  }
  /**
   * Returns `true` if the 3D object's bounding sphere is intersecting any frustum
   * from the camera array.
   *
   * @param {Object3D} object - The 3D object to test.
   * @param {Object} cameraArray - An object with a cameras property containing an array of cameras.
   * @return {boolean} Whether the 3D object is visible in any camera.
   */
  intersectsObject(e, t) {
    if (!t.isArrayCamera || t.cameras.length === 0)
      return !1;
    for (let i = 0; i < t.cameras.length; i++) {
      const n = t.cameras[i];
      if (Wi.multiplyMatrices(
        n.projectionMatrix,
        n.matrixWorldInverse
      ), Xi.setFromProjectionMatrix(
        Wi,
        n.coordinateSystem,
        n.reversedDepth
      ), Xi.intersectsObject(e))
        return !0;
    }
    return !1;
  }
  /**
   * Returns `true` if the given sprite is intersecting any frustum
   * from the camera array.
   *
   * @param {Sprite} sprite - The sprite to test.
   * @param {Object} cameraArray - An object with a cameras property containing an array of cameras.
   * @return {boolean} Whether the sprite is visible in any camera.
   */
  intersectsSprite(e, t) {
    if (!t || !t.cameras || t.cameras.length === 0)
      return !1;
    for (let i = 0; i < t.cameras.length; i++) {
      const n = t.cameras[i];
      if (Wi.multiplyMatrices(
        n.projectionMatrix,
        n.matrixWorldInverse
      ), Xi.setFromProjectionMatrix(
        Wi,
        n.coordinateSystem,
        n.reversedDepth
      ), Xi.intersectsSprite(e))
        return !0;
    }
    return !1;
  }
  /**
   * Returns `true` if the given bounding sphere is intersecting any frustum
   * from the camera array.
   *
   * @param {Sphere} sphere - The bounding sphere to test.
   * @param {Object} cameraArray - An object with a cameras property containing an array of cameras.
   * @return {boolean} Whether the sphere is visible in any camera.
   */
  intersectsSphere(e, t) {
    if (!t || !t.cameras || t.cameras.length === 0)
      return !1;
    for (let i = 0; i < t.cameras.length; i++) {
      const n = t.cameras[i];
      if (Wi.multiplyMatrices(
        n.projectionMatrix,
        n.matrixWorldInverse
      ), Xi.setFromProjectionMatrix(
        Wi,
        n.coordinateSystem,
        n.reversedDepth
      ), Xi.intersectsSphere(e))
        return !0;
    }
    return !1;
  }
  /**
   * Returns `true` if the given bounding box is intersecting any frustum
   * from the camera array.
   *
   * @param {Box3} box - The bounding box to test.
   * @param {Object} cameraArray - An object with a cameras property containing an array of cameras.
   * @return {boolean} Whether the box is visible in any camera.
   */
  intersectsBox(e, t) {
    if (!t || !t.cameras || t.cameras.length === 0)
      return !1;
    for (let i = 0; i < t.cameras.length; i++) {
      const n = t.cameras[i];
      if (Wi.multiplyMatrices(
        n.projectionMatrix,
        n.matrixWorldInverse
      ), Xi.setFromProjectionMatrix(
        Wi,
        n.coordinateSystem,
        n.reversedDepth
      ), Xi.intersectsBox(e))
        return !0;
    }
    return !1;
  }
  /**
   * Returns `true` if the given point lies within any frustum
   * from the camera array.
   *
   * @param {Vector3} point - The point to test.
   * @param {Object} cameraArray - An object with a cameras property containing an array of cameras.
   * @return {boolean} Whether the point is visible in any camera.
   */
  containsPoint(e, t) {
    if (!t || !t.cameras || t.cameras.length === 0)
      return !1;
    for (let i = 0; i < t.cameras.length; i++) {
      const n = t.cameras[i];
      if (Wi.multiplyMatrices(
        n.projectionMatrix,
        n.matrixWorldInverse
      ), Xi.setFromProjectionMatrix(
        Wi,
        n.coordinateSystem,
        n.reversedDepth
      ), Xi.containsPoint(e))
        return !0;
    }
    return !1;
  }
  /**
   * Returns a new frustum array with copied values from this instance.
   *
   * @return {FrustumArray} A clone of this instance.
   */
  clone() {
    return new ec();
  }
}
function Wc(r, e) {
  return r - e;
}
function fy(r, e) {
  return r.z - e.z;
}
function my(r, e) {
  return e.z - r.z;
}
class gy {
  constructor() {
    this.index = 0, this.pool = [], this.list = [];
  }
  push(e, t, i, n) {
    const s = this.pool, a = this.list;
    this.index >= s.length && s.push({
      start: -1,
      count: -1,
      z: -1,
      index: -1
    });
    const o = s[this.index];
    a.push(o), this.index++, o.start = e, o.count = t, o.z = i, o.index = n;
  }
  reset() {
    this.list.length = 0, this.index = 0;
  }
}
const hi = /* @__PURE__ */ new Ne(), _y = /* @__PURE__ */ new oe(1, 1, 1), Pu = /* @__PURE__ */ new Sr(), yy = /* @__PURE__ */ new ec(), Qa = /* @__PURE__ */ new Tt(), $n = /* @__PURE__ */ new Lt(), Or = /* @__PURE__ */ new b(), Lu = /* @__PURE__ */ new b(), vy = /* @__PURE__ */ new b(), Xc = /* @__PURE__ */ new gy(), jt = /* @__PURE__ */ new Je(), eo = [];
function xy(r, e, t = 0) {
  const i = e.itemSize;
  if (r.isInterleavedBufferAttribute || r.array.constructor !== e.array.constructor) {
    const n = r.count;
    for (let s = 0; s < n; s++)
      for (let a = 0; a < i; a++)
        e.setComponent(s + t, a, r.getComponent(s, a));
  } else
    e.array.set(r.array, t * i);
  e.needsUpdate = !0;
}
function Kn(r, e) {
  if (r.constructor !== e.constructor) {
    const t = Math.min(r.length, e.length);
    for (let i = 0; i < t; i++)
      e[i] = r[i];
  } else {
    const t = Math.min(r.length, e.length);
    e.set(new r.constructor(r.buffer, 0, t));
  }
}
class vm extends Je {
  /**
   * Constructs a new batched mesh.
   *
   * @param {number} maxInstanceCount - The maximum number of individual instances planned to be added and rendered.
   * @param {number} maxVertexCount - The maximum number of vertices to be used by all unique geometries.
   * @param {number} [maxIndexCount=maxVertexCount*2] - The maximum number of indices to be used by all unique geometries
   * @param {Material|Array<Material>} [material] - The mesh material.
   */
  constructor(e, t, i = t * 2, n) {
    super(new Ue(), n), this.isBatchedMesh = !0, this.perObjectFrustumCulled = !0, this.sortObjects = !0, this.boundingBox = null, this.boundingSphere = null, this.customSort = null, this._instanceInfo = [], this._geometryInfo = [], this._availableInstanceIds = [], this._availableGeometryIds = [], this._nextIndexStart = 0, this._nextVertexStart = 0, this._geometryCount = 0, this._visibilityChanged = !0, this._geometryInitialized = !1, this._maxInstanceCount = e, this._maxVertexCount = t, this._maxIndexCount = i, this._multiDrawCounts = new Int32Array(e), this._multiDrawStarts = new Int32Array(e), this._multiDrawCount = 0, this._multiDrawInstances = null, this._matricesTexture = null, this._indirectTexture = null, this._colorsTexture = null, this._initMatricesTexture(), this._initIndirectTexture();
  }
  /**
   * The maximum number of individual instances that can be stored in the batch.
   *
   * @type {number}
   * @readonly
   */
  get maxInstanceCount() {
    return this._maxInstanceCount;
  }
  /**
   * The instance count.
   *
   * @type {number}
   * @readonly
   */
  get instanceCount() {
    return this._instanceInfo.length - this._availableInstanceIds.length;
  }
  /**
   * The number of unused vertices.
   *
   * @type {number}
   * @readonly
   */
  get unusedVertexCount() {
    return this._maxVertexCount - this._nextVertexStart;
  }
  /**
   * The number of unused indices.
   *
   * @type {number}
   * @readonly
   */
  get unusedIndexCount() {
    return this._maxIndexCount - this._nextIndexStart;
  }
  _initMatricesTexture() {
    let e = Math.sqrt(this._maxInstanceCount * 4);
    e = Math.ceil(e / 4) * 4, e = Math.max(e, 4);
    const t = new Float32Array(e * e * 4), i = new tn(t, e, e, oi, mi);
    this._matricesTexture = i;
  }
  _initIndirectTexture() {
    let e = Math.sqrt(this._maxInstanceCount);
    e = Math.ceil(e);
    const t = new Uint32Array(e * e), i = new tn(t, e, e, ba, yn);
    this._indirectTexture = i;
  }
  _initColorsTexture() {
    let e = Math.sqrt(this._maxInstanceCount);
    e = Math.ceil(e);
    const t = new Float32Array(e * e * 4).fill(1), i = new tn(t, e, e, oi, mi);
    i.colorSpace = et.workingColorSpace, this._colorsTexture = i;
  }
  _initializeGeometry(e) {
    const t = this.geometry, i = this._maxVertexCount, n = this._maxIndexCount;
    if (this._geometryInitialized === !1) {
      for (const s in e.attributes) {
        const a = e.getAttribute(s), { array: o, itemSize: l, normalized: c } = a, h = new o.constructor(i * l), d = new it(h, l, c);
        t.setAttribute(s, d);
      }
      if (e.getIndex() !== null) {
        const s = i > 65535 ? new Uint32Array(n) : new Uint16Array(n);
        t.setIndex(new it(s, 1));
      }
      this._geometryInitialized = !0;
    }
  }
  // Make sure the geometry is compatible with the existing combined geometry attributes
  _validateGeometry(e) {
    const t = this.geometry;
    if (!!e.getIndex() != !!t.getIndex())
      throw new Error('THREE.BatchedMesh: All geometries must consistently have "index".');
    for (const i in t.attributes) {
      if (!e.hasAttribute(i))
        throw new Error(`THREE.BatchedMesh: Added geometry missing "${i}". All geometries must have consistent attributes.`);
      const n = e.getAttribute(i), s = t.getAttribute(i);
      if (n.itemSize !== s.itemSize || n.normalized !== s.normalized)
        throw new Error("THREE.BatchedMesh: All attributes must have a consistent itemSize and normalized value.");
    }
  }
  /**
   * Validates the instance defined by the given ID.
   *
   * @param {number} instanceId - The instance to validate.
   */
  validateInstanceId(e) {
    const t = this._instanceInfo;
    if (e < 0 || e >= t.length || t[e].active === !1)
      throw new Error(`THREE.BatchedMesh: Invalid instanceId ${e}. Instance is either out of range or has been deleted.`);
  }
  /**
   * Validates the geometry defined by the given ID.
   *
   * @param {number} geometryId - The geometry to validate.
   */
  validateGeometryId(e) {
    const t = this._geometryInfo;
    if (e < 0 || e >= t.length || t[e].active === !1)
      throw new Error(`THREE.BatchedMesh: Invalid geometryId ${e}. Geometry is either out of range or has been deleted.`);
  }
  /**
   * Takes a sort a function that is run before render. The function takes a list of instances to
   * sort and a camera. The objects in the list include a "z" field to perform a depth-ordered sort with.
   *
   * @param {Function} func - The custom sort function.
   * @return {BatchedMesh} A reference to this batched mesh.
   */
  setCustomSort(e) {
    return this.customSort = e, this;
  }
  /**
   * Computes the bounding box, updating {@link BatchedMesh#boundingBox}.
   * Bounding boxes aren't computed by default. They need to be explicitly computed,
   * otherwise they are `null`.
   */
  computeBoundingBox() {
    this.boundingBox === null && (this.boundingBox = new Tt());
    const e = this.boundingBox, t = this._instanceInfo;
    e.makeEmpty();
    for (let i = 0, n = t.length; i < n; i++) {
      if (t[i].active === !1) continue;
      const s = t[i].geometryIndex;
      this.getMatrixAt(i, hi), this.getBoundingBoxAt(s, Qa).applyMatrix4(hi), e.union(Qa);
    }
  }
  /**
   * Computes the bounding sphere, updating {@link BatchedMesh#boundingSphere}.
   * Bounding spheres aren't computed by default. They need to be explicitly computed,
   * otherwise they are `null`.
   */
  computeBoundingSphere() {
    this.boundingSphere === null && (this.boundingSphere = new Lt());
    const e = this.boundingSphere, t = this._instanceInfo;
    e.makeEmpty();
    for (let i = 0, n = t.length; i < n; i++) {
      if (t[i].active === !1) continue;
      const s = t[i].geometryIndex;
      this.getMatrixAt(i, hi), this.getBoundingSphereAt(s, $n).applyMatrix4(hi), e.union($n);
    }
  }
  /**
   * Adds a new instance to the batch using the geometry of the given ID and returns
   * a new id referring to the new instance to be used by other functions.
   *
   * @param {number} geometryId - The ID of a previously added geometry via {@link BatchedMesh#addGeometry}.
   * @return {number} The instance ID.
   */
  addInstance(e) {
    if (this._instanceInfo.length >= this.maxInstanceCount && this._availableInstanceIds.length === 0)
      throw new Error("THREE.BatchedMesh: Maximum item count reached.");
    const i = {
      visible: !0,
      active: !0,
      geometryIndex: e
    };
    let n = null;
    this._availableInstanceIds.length > 0 ? (this._availableInstanceIds.sort(Wc), n = this._availableInstanceIds.shift(), this._instanceInfo[n] = i) : (n = this._instanceInfo.length, this._instanceInfo.push(i));
    const s = this._matricesTexture;
    hi.identity().toArray(s.image.data, n * 16), s.needsUpdate = !0;
    const a = this._colorsTexture;
    return a && (_y.toArray(a.image.data, n * 4), a.needsUpdate = !0), this._visibilityChanged = !0, n;
  }
  /**
   * Adds the given geometry to the batch and returns the associated
   * geometry id referring to it to be used in other functions.
   *
   * @param {BufferGeometry} geometry - The geometry to add.
   * @param {number} [reservedVertexCount=-1] - Optional parameter specifying the amount of
   * vertex buffer space to reserve for the added geometry. This is necessary if it is planned
   * to set a new geometry at this index at a later time that is larger than the original geometry.
   * Defaults to the length of the given geometry vertex buffer.
   * @param {number} [reservedIndexCount=-1] - Optional parameter specifying the amount of index
   * buffer space to reserve for the added geometry. This is necessary if it is planned to set a
   * new geometry at this index at a later time that is larger than the original geometry. Defaults to
   * the length of the given geometry index buffer.
   * @return {number} The geometry ID.
   */
  addGeometry(e, t = -1, i = -1) {
    this._initializeGeometry(e), this._validateGeometry(e);
    const n = {
      // geometry information
      vertexStart: -1,
      vertexCount: -1,
      reservedVertexCount: -1,
      indexStart: -1,
      indexCount: -1,
      reservedIndexCount: -1,
      // draw range information
      start: -1,
      count: -1,
      // state
      boundingBox: null,
      boundingSphere: null,
      active: !0
    }, s = this._geometryInfo;
    n.vertexStart = this._nextVertexStart, n.reservedVertexCount = t === -1 ? e.getAttribute("position").count : t;
    const a = e.getIndex();
    if (a !== null && (n.indexStart = this._nextIndexStart, n.reservedIndexCount = i === -1 ? a.count : i), n.indexStart !== -1 && n.indexStart + n.reservedIndexCount > this._maxIndexCount || n.vertexStart + n.reservedVertexCount > this._maxVertexCount)
      throw new Error("THREE.BatchedMesh: Reserved space request exceeds the maximum buffer size.");
    let l;
    return this._availableGeometryIds.length > 0 ? (this._availableGeometryIds.sort(Wc), l = this._availableGeometryIds.shift(), s[l] = n) : (l = this._geometryCount, this._geometryCount++, s.push(n)), this.setGeometryAt(l, e), this._nextIndexStart = n.indexStart + n.reservedIndexCount, this._nextVertexStart = n.vertexStart + n.reservedVertexCount, l;
  }
  /**
   * Replaces the geometry at the given ID with the provided geometry. Throws an error if there
   * is not enough space reserved for geometry. Calling this will change all instances that are
   * rendering that geometry.
   *
   * @param {number} geometryId - The ID of the geometry that should be replaced with the given geometry.
   * @param {BufferGeometry} geometry - The new geometry.
   * @return {number} The geometry ID.
   */
  setGeometryAt(e, t) {
    if (e >= this._geometryCount)
      throw new Error("THREE.BatchedMesh: Maximum geometry count reached.");
    this._validateGeometry(t);
    const i = this.geometry, n = i.getIndex() !== null, s = i.getIndex(), a = t.getIndex(), o = this._geometryInfo[e];
    if (n && a.count > o.reservedIndexCount || t.attributes.position.count > o.reservedVertexCount)
      throw new Error("THREE.BatchedMesh: Reserved space not large enough for provided geometry.");
    const l = o.vertexStart, c = o.reservedVertexCount;
    o.vertexCount = t.getAttribute("position").count;
    for (const h in i.attributes) {
      const d = t.getAttribute(h), u = i.getAttribute(h);
      xy(d, u, l);
      const p = d.itemSize;
      for (let m = d.count, _ = c; m < _; m++) {
        const g = l + m;
        for (let f = 0; f < p; f++)
          u.setComponent(g, f, 0);
      }
      u.needsUpdate = !0, u.addUpdateRange(l * p, c * p);
    }
    if (n) {
      const h = o.indexStart, d = o.reservedIndexCount;
      o.indexCount = t.getIndex().count;
      for (let u = 0; u < a.count; u++)
        s.setX(h + u, l + a.getX(u));
      for (let u = a.count, p = d; u < p; u++)
        s.setX(h + u, l);
      s.needsUpdate = !0, s.addUpdateRange(h, o.reservedIndexCount);
    }
    return o.start = n ? o.indexStart : o.vertexStart, o.count = n ? o.indexCount : o.vertexCount, o.boundingBox = null, t.boundingBox !== null && (o.boundingBox = t.boundingBox.clone()), o.boundingSphere = null, t.boundingSphere !== null && (o.boundingSphere = t.boundingSphere.clone()), this._visibilityChanged = !0, e;
  }
  /**
   * Deletes the geometry defined by the given ID from this batch. Any instances referencing
   * this geometry will also be removed as a side effect.
   *
   * @param {number} geometryId - The ID of the geometry to remove from the batch.
   * @return {BatchedMesh} A reference to this batched mesh.
   */
  deleteGeometry(e) {
    const t = this._geometryInfo;
    if (e >= t.length || t[e].active === !1)
      return this;
    const i = this._instanceInfo;
    for (let n = 0, s = i.length; n < s; n++)
      i[n].active && i[n].geometryIndex === e && this.deleteInstance(n);
    return t[e].active = !1, this._availableGeometryIds.push(e), this._visibilityChanged = !0, this;
  }
  /**
   * Deletes an existing instance from the batch using the given ID.
   *
   * @param {number} instanceId - The ID of the instance to remove from the batch.
   * @return {BatchedMesh} A reference to this batched mesh.
   */
  deleteInstance(e) {
    return this.validateInstanceId(e), this._instanceInfo[e].active = !1, this._availableInstanceIds.push(e), this._visibilityChanged = !0, this;
  }
  /**
   * Repacks the sub geometries in [name] to remove any unused space remaining from
   * previously deleted geometry, freeing up space to add new geometry.
   *
   * @param {number} instanceId - The ID of the instance to remove from the batch.
   * @return {BatchedMesh} A reference to this batched mesh.
   */
  optimize() {
    let e = 0, t = 0;
    const i = this._geometryInfo, n = i.map((a, o) => o).sort((a, o) => i[a].vertexStart - i[o].vertexStart), s = this.geometry;
    for (let a = 0, o = i.length; a < o; a++) {
      const l = n[a], c = i[l];
      if (c.active !== !1) {
        if (s.index !== null) {
          if (c.indexStart !== t) {
            const { indexStart: h, vertexStart: d, reservedIndexCount: u } = c, p = s.index, m = p.array, _ = e - d;
            for (let g = h; g < h + u; g++)
              m[g] = m[g] + _;
            p.array.copyWithin(t, h, h + u), p.addUpdateRange(t, u), c.indexStart = t;
          }
          t += c.reservedIndexCount;
        }
        if (c.vertexStart !== e) {
          const { vertexStart: h, reservedVertexCount: d } = c, u = s.attributes;
          for (const p in u) {
            const m = u[p], { array: _, itemSize: g } = m;
            _.copyWithin(e * g, h * g, (h + d) * g), m.addUpdateRange(e * g, d * g);
          }
          c.vertexStart = e;
        }
        e += c.reservedVertexCount, c.start = s.index ? c.indexStart : c.vertexStart, this._nextIndexStart = s.index ? c.indexStart + c.reservedIndexCount : 0, this._nextVertexStart = c.vertexStart + c.reservedVertexCount;
      }
    }
    return this;
  }
  /**
   * Returns the bounding box for the given geometry.
   *
   * @param {number} geometryId - The ID of the geometry to return the bounding box for.
   * @param {Box3} target - The target object that is used to store the method's result.
   * @return {?Box3} The geometry's bounding box. Returns `null` if no geometry has been found for the given ID.
   */
  getBoundingBoxAt(e, t) {
    if (e >= this._geometryCount)
      return null;
    const i = this.geometry, n = this._geometryInfo[e];
    if (n.boundingBox === null) {
      const s = new Tt(), a = i.index, o = i.attributes.position;
      for (let l = n.start, c = n.start + n.count; l < c; l++) {
        let h = l;
        a && (h = a.getX(h)), s.expandByPoint(Or.fromBufferAttribute(o, h));
      }
      n.boundingBox = s;
    }
    return t.copy(n.boundingBox), t;
  }
  /**
   * Returns the bounding sphere for the given geometry.
   *
   * @param {number} geometryId - The ID of the geometry to return the bounding sphere for.
   * @param {Sphere} target - The target object that is used to store the method's result.
   * @return {?Sphere} The geometry's bounding sphere. Returns `null` if no geometry has been found for the given ID.
   */
  getBoundingSphereAt(e, t) {
    if (e >= this._geometryCount)
      return null;
    const i = this.geometry, n = this._geometryInfo[e];
    if (n.boundingSphere === null) {
      const s = new Lt();
      this.getBoundingBoxAt(e, Qa), Qa.getCenter(s.center);
      const a = i.index, o = i.attributes.position;
      let l = 0;
      for (let c = n.start, h = n.start + n.count; c < h; c++) {
        let d = c;
        a && (d = a.getX(d)), Or.fromBufferAttribute(o, d), l = Math.max(l, s.center.distanceToSquared(Or));
      }
      s.radius = Math.sqrt(l), n.boundingSphere = s;
    }
    return t.copy(n.boundingSphere), t;
  }
  /**
   * Sets the given local transformation matrix to the defined instance.
   * Negatively scaled matrices are not supported.
   *
   * @param {number} instanceId - The ID of an instance to set the matrix of.
   * @param {Matrix4} matrix - A 4x4 matrix representing the local transformation of a single instance.
   * @return {BatchedMesh} A reference to this batched mesh.
   */
  setMatrixAt(e, t) {
    this.validateInstanceId(e);
    const i = this._matricesTexture, n = this._matricesTexture.image.data;
    return t.toArray(n, e * 16), i.needsUpdate = !0, this;
  }
  /**
   * Returns the local transformation matrix of the defined instance.
   *
   * @param {number} instanceId - The ID of an instance to get the matrix of.
   * @param {Matrix4} matrix - The target object that is used to store the method's result.
   * @return {Matrix4} The instance's local transformation matrix.
   */
  getMatrixAt(e, t) {
    return this.validateInstanceId(e), t.fromArray(this._matricesTexture.image.data, e * 16);
  }
  /**
   * Sets the given color to the defined instance.
   *
   * @param {number} instanceId - The ID of an instance to set the color of.
   * @param {Color} color - The color to set the instance to.
   * @return {BatchedMesh} A reference to this batched mesh.
   */
  setColorAt(e, t) {
    return this.validateInstanceId(e), this._colorsTexture === null && this._initColorsTexture(), t.toArray(this._colorsTexture.image.data, e * 4), this._colorsTexture.needsUpdate = !0, this;
  }
  /**
   * Returns the color of the defined instance.
   *
   * @param {number} instanceId - The ID of an instance to get the color of.
   * @param {Color} color - The target object that is used to store the method's result.
   * @return {Color} The instance's color.
   */
  getColorAt(e, t) {
    return this.validateInstanceId(e), t.fromArray(this._colorsTexture.image.data, e * 4);
  }
  /**
   * Sets the visibility of the instance.
   *
   * @param {number} instanceId - The id of the instance to set the visibility of.
   * @param {boolean} visible - Whether the instance is visible or not.
   * @return {BatchedMesh} A reference to this batched mesh.
   */
  setVisibleAt(e, t) {
    return this.validateInstanceId(e), this._instanceInfo[e].visible === t ? this : (this._instanceInfo[e].visible = t, this._visibilityChanged = !0, this);
  }
  /**
   * Returns the visibility state of the defined instance.
   *
   * @param {number} instanceId - The ID of an instance to get the visibility state of.
   * @return {boolean} Whether the instance is visible or not.
   */
  getVisibleAt(e) {
    return this.validateInstanceId(e), this._instanceInfo[e].visible;
  }
  /**
   * Sets the geometry ID of the instance at the given index.
   *
   * @param {number} instanceId - The ID of the instance to set the geometry ID of.
   * @param {number} geometryId - The geometry ID to be use by the instance.
   * @return {BatchedMesh} A reference to this batched mesh.
   */
  setGeometryIdAt(e, t) {
    return this.validateInstanceId(e), this.validateGeometryId(t), this._instanceInfo[e].geometryIndex = t, this;
  }
  /**
   * Returns the geometry ID of the defined instance.
   *
   * @param {number} instanceId - The ID of an instance to get the geometry ID of.
   * @return {number} The instance's geometry ID.
   */
  getGeometryIdAt(e) {
    return this.validateInstanceId(e), this._instanceInfo[e].geometryIndex;
  }
  /**
   * Get the range representing the subset of triangles related to the attached geometry,
   * indicating the starting offset and count, or `null` if invalid.
   *
   * @param {number} geometryId - The id of the geometry to get the range of.
   * @param {Object} [target] - The target object that is used to store the method's result.
   * @return {{
   * 	vertexStart:number,vertexCount:number,reservedVertexCount:number,
   * 	indexStart:number,indexCount:number,reservedIndexCount:number,
   * 	start:number,count:number
   * }} The result object with range data.
   */
  getGeometryRangeAt(e, t = {}) {
    this.validateGeometryId(e);
    const i = this._geometryInfo[e];
    return t.vertexStart = i.vertexStart, t.vertexCount = i.vertexCount, t.reservedVertexCount = i.reservedVertexCount, t.indexStart = i.indexStart, t.indexCount = i.indexCount, t.reservedIndexCount = i.reservedIndexCount, t.start = i.start, t.count = i.count, t;
  }
  /**
   * Resizes the necessary buffers to support the provided number of instances.
   * If the provided arguments shrink the number of instances but there are not enough
   * unused Ids at the end of the list then an error is thrown.
   *
   * @param {number} maxInstanceCount - The max number of individual instances that can be added and rendered by the batch.
  */
  setInstanceCount(e) {
    const t = this._availableInstanceIds, i = this._instanceInfo;
    for (t.sort(Wc); t[t.length - 1] === i.length - 1; )
      i.pop(), t.pop();
    if (e < i.length)
      throw new Error(`BatchedMesh: Instance ids outside the range ${e} are being used. Cannot shrink instance count.`);
    const n = new Int32Array(e), s = new Int32Array(e);
    Kn(this._multiDrawCounts, n), Kn(this._multiDrawStarts, s), this._multiDrawCounts = n, this._multiDrawStarts = s, this._maxInstanceCount = e;
    const a = this._indirectTexture, o = this._matricesTexture, l = this._colorsTexture;
    a.dispose(), this._initIndirectTexture(), Kn(a.image.data, this._indirectTexture.image.data), o.dispose(), this._initMatricesTexture(), Kn(o.image.data, this._matricesTexture.image.data), l && (l.dispose(), this._initColorsTexture(), Kn(l.image.data, this._colorsTexture.image.data));
  }
  /**
   * Resizes the available space in the batch's vertex and index buffer attributes to the provided sizes.
   * If the provided arguments shrink the geometry buffers but there is not enough unused space at the
   * end of the geometry attributes then an error is thrown.
   *
   * @param {number} maxVertexCount - The maximum number of vertices to be used by all unique geometries to resize to.
   * @param {number} maxIndexCount - The maximum number of indices to be used by all unique geometries to resize to.
  */
  setGeometrySize(e, t) {
    const i = [...this._geometryInfo].filter((o) => o.active);
    if (Math.max(...i.map((o) => o.vertexStart + o.reservedVertexCount)) > e)
      throw new Error(`BatchedMesh: Geometry vertex values are being used outside the range ${t}. Cannot shrink further.`);
    if (this.geometry.index && Math.max(...i.map((l) => l.indexStart + l.reservedIndexCount)) > t)
      throw new Error(`BatchedMesh: Geometry index values are being used outside the range ${t}. Cannot shrink further.`);
    const s = this.geometry;
    s.dispose(), this._maxVertexCount = e, this._maxIndexCount = t, this._geometryInitialized && (this._geometryInitialized = !1, this.geometry = new Ue(), this._initializeGeometry(s));
    const a = this.geometry;
    s.index && Kn(s.index.array, a.index.array);
    for (const o in s.attributes)
      Kn(s.attributes[o].array, a.attributes[o].array);
  }
  raycast(e, t) {
    const i = this._instanceInfo, n = this._geometryInfo, s = this.matrixWorld, a = this.geometry;
    jt.material = this.material, jt.geometry.index = a.index, jt.geometry.attributes = a.attributes, jt.geometry.boundingBox === null && (jt.geometry.boundingBox = new Tt()), jt.geometry.boundingSphere === null && (jt.geometry.boundingSphere = new Lt());
    for (let o = 0, l = i.length; o < l; o++) {
      if (!i[o].visible || !i[o].active)
        continue;
      const c = i[o].geometryIndex, h = n[c];
      jt.geometry.setDrawRange(h.start, h.count), this.getMatrixAt(o, jt.matrixWorld).premultiply(s), this.getBoundingBoxAt(c, jt.geometry.boundingBox), this.getBoundingSphereAt(c, jt.geometry.boundingSphere), jt.raycast(e, eo);
      for (let d = 0, u = eo.length; d < u; d++) {
        const p = eo[d];
        p.object = this, p.batchId = o, t.push(p);
      }
      eo.length = 0;
    }
    jt.material = null, jt.geometry.index = null, jt.geometry.attributes = {}, jt.geometry.setDrawRange(0, 1 / 0);
  }
  copy(e) {
    return super.copy(e), this.geometry = e.geometry.clone(), this.perObjectFrustumCulled = e.perObjectFrustumCulled, this.sortObjects = e.sortObjects, this.boundingBox = e.boundingBox !== null ? e.boundingBox.clone() : null, this.boundingSphere = e.boundingSphere !== null ? e.boundingSphere.clone() : null, this._geometryInfo = e._geometryInfo.map((t) => ({
      ...t,
      boundingBox: t.boundingBox !== null ? t.boundingBox.clone() : null,
      boundingSphere: t.boundingSphere !== null ? t.boundingSphere.clone() : null
    })), this._instanceInfo = e._instanceInfo.map((t) => ({ ...t })), this._availableInstanceIds = e._availableInstanceIds.slice(), this._availableGeometryIds = e._availableGeometryIds.slice(), this._nextIndexStart = e._nextIndexStart, this._nextVertexStart = e._nextVertexStart, this._geometryCount = e._geometryCount, this._maxInstanceCount = e._maxInstanceCount, this._maxVertexCount = e._maxVertexCount, this._maxIndexCount = e._maxIndexCount, this._geometryInitialized = e._geometryInitialized, this._multiDrawCounts = e._multiDrawCounts.slice(), this._multiDrawStarts = e._multiDrawStarts.slice(), this._indirectTexture = e._indirectTexture.clone(), this._indirectTexture.image.data = this._indirectTexture.image.data.slice(), this._matricesTexture = e._matricesTexture.clone(), this._matricesTexture.image.data = this._matricesTexture.image.data.slice(), this._colorsTexture !== null && (this._colorsTexture = e._colorsTexture.clone(), this._colorsTexture.image.data = this._colorsTexture.image.data.slice()), this;
  }
  /**
   * Frees the GPU-related resources allocated by this instance. Call this
   * method whenever this instance is no longer used in your app.
   */
  dispose() {
    this.geometry.dispose(), this._matricesTexture.dispose(), this._matricesTexture = null, this._indirectTexture.dispose(), this._indirectTexture = null, this._colorsTexture !== null && (this._colorsTexture.dispose(), this._colorsTexture = null);
  }
  onBeforeRender(e, t, i, n, s) {
    if (!this._visibilityChanged && !this.perObjectFrustumCulled && !this.sortObjects)
      return;
    const a = n.getIndex(), o = a === null ? 1 : a.array.BYTES_PER_ELEMENT, l = this._instanceInfo, c = this._multiDrawStarts, h = this._multiDrawCounts, d = this._geometryInfo, u = this.perObjectFrustumCulled, p = this._indirectTexture, m = p.image.data, _ = i.isArrayCamera ? yy : Pu;
    u && !i.isArrayCamera && (hi.multiplyMatrices(i.projectionMatrix, i.matrixWorldInverse).multiply(this.matrixWorld), Pu.setFromProjectionMatrix(
      hi,
      i.coordinateSystem,
      i.reversedDepth
    ));
    let g = 0;
    if (this.sortObjects) {
      hi.copy(this.matrixWorld).invert(), Or.setFromMatrixPosition(i.matrixWorld).applyMatrix4(hi), Lu.set(0, 0, -1).transformDirection(i.matrixWorld).transformDirection(hi);
      for (let x = 0, y = l.length; x < y; x++)
        if (l[x].visible && l[x].active) {
          const A = l[x].geometryIndex;
          this.getMatrixAt(x, hi), this.getBoundingSphereAt(A, $n).applyMatrix4(hi);
          let S = !1;
          if (u && (S = !_.intersectsSphere($n, i)), !S) {
            const C = d[A], P = vy.subVectors($n.center, Or).dot(Lu);
            Xc.push(C.start, C.count, P, x);
          }
        }
      const f = Xc.list, v = this.customSort;
      v === null ? f.sort(s.transparent ? my : fy) : v.call(this, f, i);
      for (let x = 0, y = f.length; x < y; x++) {
        const A = f[x];
        c[g] = A.start * o, h[g] = A.count, m[g] = A.index, g++;
      }
      Xc.reset();
    } else
      for (let f = 0, v = l.length; f < v; f++)
        if (l[f].visible && l[f].active) {
          const x = l[f].geometryIndex;
          let y = !1;
          if (u && (this.getMatrixAt(f, hi), this.getBoundingSphereAt(x, $n).applyMatrix4(hi), y = !_.intersectsSphere($n, i)), !y) {
            const A = d[x];
            c[g] = A.start * o, h[g] = A.count, m[g] = f, g++;
          }
        }
    p.needsUpdate = !0, this._multiDrawCount = g, this._visibilityChanged = !1;
  }
  onBeforeShadow(e, t, i, n, s, a) {
    this.onBeforeRender(e, null, n, s, a);
  }
}
class It extends qt {
  /**
   * Constructs a new line basic material.
   *
   * @param {Object} [parameters] - An object with one or more properties
   * defining the material's appearance. Any property of the material
   * (including any property from inherited materials) can be passed
   * in here. Color values can be passed any type of value accepted
   * by {@link Color#set}.
   */
  constructor(e) {
    super(), this.isLineBasicMaterial = !0, this.type = "LineBasicMaterial", this.color = new oe(16777215), this.map = null, this.linewidth = 1, this.linecap = "round", this.linejoin = "round", this.fog = !0, this.setValues(e);
  }
  copy(e) {
    return super.copy(e), this.color.copy(e.color), this.map = e.map, this.linewidth = e.linewidth, this.linecap = e.linecap, this.linejoin = e.linejoin, this.fog = e.fog, this;
  }
}
const Pl = /* @__PURE__ */ new b(), Ll = /* @__PURE__ */ new b(), Iu = /* @__PURE__ */ new Ne(), Fr = /* @__PURE__ */ new ws(), to = /* @__PURE__ */ new Lt(), qc = /* @__PURE__ */ new b(), Du = /* @__PURE__ */ new b();
class Fn extends tt {
  /**
   * Constructs a new line.
   *
   * @param {BufferGeometry} [geometry] - The line geometry.
   * @param {Material|Array<Material>} [material] - The line material.
   */
  constructor(e = new Ue(), t = new It()) {
    super(), this.isLine = !0, this.type = "Line", this.geometry = e, this.material = t, this.morphTargetDictionary = void 0, this.morphTargetInfluences = void 0, this.updateMorphTargets();
  }
  copy(e, t) {
    return super.copy(e, t), this.material = Array.isArray(e.material) ? e.material.slice() : e.material, this.geometry = e.geometry, this;
  }
  /**
   * Computes an array of distance values which are necessary for rendering dashed lines.
   * For each vertex in the geometry, the method calculates the cumulative length from the
   * current point to the very beginning of the line.
   *
   * @return {Line} A reference to this line.
   */
  computeLineDistances() {
    const e = this.geometry;
    if (e.index === null) {
      const t = e.attributes.position, i = [0];
      for (let n = 1, s = t.count; n < s; n++)
        Pl.fromBufferAttribute(t, n - 1), Ll.fromBufferAttribute(t, n), i[n] = i[n - 1], i[n] += Pl.distanceTo(Ll);
      e.setAttribute("lineDistance", new ve(i, 1));
    } else
      console.warn("THREE.Line.computeLineDistances(): Computation only possible with non-indexed BufferGeometry.");
    return this;
  }
  /**
   * Computes intersection points between a casted ray and this line.
   *
   * @param {Raycaster} raycaster - The raycaster.
   * @param {Array<Object>} intersects - The target array that holds the intersection points.
   */
  raycast(e, t) {
    const i = this.geometry, n = this.matrixWorld, s = e.params.Line.threshold, a = i.drawRange;
    if (i.boundingSphere === null && i.computeBoundingSphere(), to.copy(i.boundingSphere), to.applyMatrix4(n), to.radius += s, e.ray.intersectsSphere(to) === !1) return;
    Iu.copy(n).invert(), Fr.copy(e.ray).applyMatrix4(Iu);
    const o = s / ((this.scale.x + this.scale.y + this.scale.z) / 3), l = o * o, c = this.isLineSegments ? 2 : 1, h = i.index, u = i.attributes.position;
    if (h !== null) {
      const p = Math.max(0, a.start), m = Math.min(h.count, a.start + a.count);
      for (let _ = p, g = m - 1; _ < g; _ += c) {
        const f = h.getX(_), v = h.getX(_ + 1), x = io(this, e, Fr, l, f, v, _);
        x && t.push(x);
      }
      if (this.isLineLoop) {
        const _ = h.getX(m - 1), g = h.getX(p), f = io(this, e, Fr, l, _, g, m - 1);
        f && t.push(f);
      }
    } else {
      const p = Math.max(0, a.start), m = Math.min(u.count, a.start + a.count);
      for (let _ = p, g = m - 1; _ < g; _ += c) {
        const f = io(this, e, Fr, l, _, _ + 1, _);
        f && t.push(f);
      }
      if (this.isLineLoop) {
        const _ = io(this, e, Fr, l, m - 1, p, m - 1);
        _ && t.push(_);
      }
    }
  }
  /**
   * Sets the values of {@link Line#morphTargetDictionary} and {@link Line#morphTargetInfluences}
   * to make sure existing morph targets can influence this 3D object.
   */
  updateMorphTargets() {
    const t = this.geometry.morphAttributes, i = Object.keys(t);
    if (i.length > 0) {
      const n = t[i[0]];
      if (n !== void 0) {
        this.morphTargetInfluences = [], this.morphTargetDictionary = {};
        for (let s = 0, a = n.length; s < a; s++) {
          const o = n[s].name || String(s);
          this.morphTargetInfluences.push(0), this.morphTargetDictionary[o] = s;
        }
      }
    }
  }
}
function io(r, e, t, i, n, s, a) {
  const o = r.geometry.attributes.position;
  if (Pl.fromBufferAttribute(o, n), Ll.fromBufferAttribute(o, s), t.distanceSqToSegment(Pl, Ll, qc, Du) > i) return;
  qc.applyMatrix4(r.matrixWorld);
  const c = e.ray.origin.distanceTo(qc);
  if (!(c < e.near || c > e.far))
    return {
      distance: c,
      // What do we want? intersection point on the ray or on the segment??
      // point: raycaster.ray.at( distance ),
      point: Du.clone().applyMatrix4(r.matrixWorld),
      index: a,
      face: null,
      faceIndex: null,
      barycoord: null,
      object: r
    };
}
const Nu = /* @__PURE__ */ new b(), Uu = /* @__PURE__ */ new b();
class ei extends Fn {
  /**
   * Constructs a new line segments.
   *
   * @param {BufferGeometry} [geometry] - The line geometry.
   * @param {Material|Array<Material>} [material] - The line material.
   */
  constructor(e, t) {
    super(e, t), this.isLineSegments = !0, this.type = "LineSegments";
  }
  computeLineDistances() {
    const e = this.geometry;
    if (e.index === null) {
      const t = e.attributes.position, i = [];
      for (let n = 0, s = t.count; n < s; n += 2)
        Nu.fromBufferAttribute(t, n), Uu.fromBufferAttribute(t, n + 1), i[n] = n === 0 ? 0 : i[n - 1], i[n + 1] = i[n] + Nu.distanceTo(Uu);
      e.setAttribute("lineDistance", new ve(i, 1));
    } else
      console.warn("THREE.LineSegments.computeLineDistances(): Computation only possible with non-indexed BufferGeometry.");
    return this;
  }
}
class xm extends Fn {
  /**
   * Constructs a new line loop.
   *
   * @param {BufferGeometry} [geometry] - The line geometry.
   * @param {Material|Array<Material>} [material] - The line material.
   */
  constructor(e, t) {
    super(e, t), this.isLineLoop = !0, this.type = "LineLoop";
  }
}
class tc extends qt {
  /**
   * Constructs a new points material.
   *
   * @param {Object} [parameters] - An object with one or more properties
   * defining the material's appearance. Any property of the material
   * (including any property from inherited materials) can be passed
   * in here. Color values can be passed any type of value accepted
   * by {@link Color#set}.
   */
  constructor(e) {
    super(), this.isPointsMaterial = !0, this.type = "PointsMaterial", this.color = new oe(16777215), this.map = null, this.alphaMap = null, this.size = 1, this.sizeAttenuation = !0, this.fog = !0, this.setValues(e);
  }
  copy(e) {
    return super.copy(e), this.color.copy(e.color), this.map = e.map, this.alphaMap = e.alphaMap, this.size = e.size, this.sizeAttenuation = e.sizeAttenuation, this.fog = e.fog, this;
  }
}
const Ou = /* @__PURE__ */ new Ne(), Oh = /* @__PURE__ */ new ws(), no = /* @__PURE__ */ new Lt(), so = /* @__PURE__ */ new b();
class pd extends tt {
  /**
   * Constructs a new point cloud.
   *
   * @param {BufferGeometry} [geometry] - The points geometry.
   * @param {Material|Array<Material>} [material] - The points material.
   */
  constructor(e = new Ue(), t = new tc()) {
    super(), this.isPoints = !0, this.type = "Points", this.geometry = e, this.material = t, this.morphTargetDictionary = void 0, this.morphTargetInfluences = void 0, this.updateMorphTargets();
  }
  copy(e, t) {
    return super.copy(e, t), this.material = Array.isArray(e.material) ? e.material.slice() : e.material, this.geometry = e.geometry, this;
  }
  /**
   * Computes intersection points between a casted ray and this point cloud.
   *
   * @param {Raycaster} raycaster - The raycaster.
   * @param {Array<Object>} intersects - The target array that holds the intersection points.
   */
  raycast(e, t) {
    const i = this.geometry, n = this.matrixWorld, s = e.params.Points.threshold, a = i.drawRange;
    if (i.boundingSphere === null && i.computeBoundingSphere(), no.copy(i.boundingSphere), no.applyMatrix4(n), no.radius += s, e.ray.intersectsSphere(no) === !1) return;
    Ou.copy(n).invert(), Oh.copy(e.ray).applyMatrix4(Ou);
    const o = s / ((this.scale.x + this.scale.y + this.scale.z) / 3), l = o * o, c = i.index, d = i.attributes.position;
    if (c !== null) {
      const u = Math.max(0, a.start), p = Math.min(c.count, a.start + a.count);
      for (let m = u, _ = p; m < _; m++) {
        const g = c.getX(m);
        so.fromBufferAttribute(d, g), Fu(so, g, l, n, e, t, this);
      }
    } else {
      const u = Math.max(0, a.start), p = Math.min(d.count, a.start + a.count);
      for (let m = u, _ = p; m < _; m++)
        so.fromBufferAttribute(d, m), Fu(so, m, l, n, e, t, this);
    }
  }
  /**
   * Sets the values of {@link Points#morphTargetDictionary} and {@link Points#morphTargetInfluences}
   * to make sure existing morph targets can influence this 3D object.
   */
  updateMorphTargets() {
    const t = this.geometry.morphAttributes, i = Object.keys(t);
    if (i.length > 0) {
      const n = t[i[0]];
      if (n !== void 0) {
        this.morphTargetInfluences = [], this.morphTargetDictionary = {};
        for (let s = 0, a = n.length; s < a; s++) {
          const o = n[s].name || String(s);
          this.morphTargetInfluences.push(0), this.morphTargetDictionary[o] = s;
        }
      }
    }
  }
}
function Fu(r, e, t, i, n, s, a) {
  const o = Oh.distanceSqToPoint(r);
  if (o < t) {
    const l = new b();
    Oh.closestPointToPoint(r, l), l.applyMatrix4(i);
    const c = n.ray.origin.distanceTo(l);
    if (c < n.near || c > n.far) return;
    s.push({
      distance: c,
      distanceToRay: Math.sqrt(o),
      point: l,
      index: e,
      face: null,
      faceIndex: null,
      barycoord: null,
      object: a
    });
  }
}
class bm extends Et {
  /**
   * Constructs a new video texture.
   *
   * @param {HTMLVideoElement} video - The video element to use as a data source for the texture.
   * @param {number} [mapping=Texture.DEFAULT_MAPPING] - The texture mapping.
   * @param {number} [wrapS=ClampToEdgeWrapping] - The wrapS value.
   * @param {number} [wrapT=ClampToEdgeWrapping] - The wrapT value.
   * @param {number} [magFilter=LinearFilter] - The mag filter value.
   * @param {number} [minFilter=LinearFilter] - The min filter value.
   * @param {number} [format=RGBAFormat] - The texture format.
   * @param {number} [type=UnsignedByteType] - The texture type.
   * @param {number} [anisotropy=Texture.DEFAULT_ANISOTROPY] - The anisotropy value.
   */
  constructor(e, t, i, n, s = Pt, a = Pt, o, l, c) {
    super(e, t, i, n, s, a, o, l, c), this.isVideoTexture = !0, this.generateMipmaps = !1, this._requestVideoFrameCallbackId = 0;
    const h = this;
    function d() {
      h.needsUpdate = !0, h._requestVideoFrameCallbackId = e.requestVideoFrameCallback(d);
    }
    "requestVideoFrameCallback" in e && (this._requestVideoFrameCallbackId = e.requestVideoFrameCallback(d));
  }
  clone() {
    return new this.constructor(this.image).copy(this);
  }
  /**
   * This method is called automatically by the renderer and sets {@link Texture#needsUpdate}
   * to `true` every time a new frame is available.
   *
   * Only relevant if `requestVideoFrameCallback` is not supported in the browser.
   */
  update() {
    const e = this.image;
    "requestVideoFrameCallback" in e === !1 && e.readyState >= e.HAVE_CURRENT_DATA && (this.needsUpdate = !0);
  }
  dispose() {
    this._requestVideoFrameCallbackId !== 0 && this.source.data.cancelVideoFrameCallback(this._requestVideoFrameCallbackId), super.dispose();
  }
}
class by extends bm {
  /**
   * Constructs a new video frame texture.
   *
   * @param {number} [mapping=Texture.DEFAULT_MAPPING] - The texture mapping.
   * @param {number} [wrapS=ClampToEdgeWrapping] - The wrapS value.
   * @param {number} [wrapT=ClampToEdgeWrapping] - The wrapT value.
   * @param {number} [magFilter=LinearFilter] - The mag filter value.
   * @param {number} [minFilter=LinearFilter] - The min filter value.
   * @param {number} [format=RGBAFormat] - The texture format.
   * @param {number} [type=UnsignedByteType] - The texture type.
   * @param {number} [anisotropy=Texture.DEFAULT_ANISOTROPY] - The anisotropy value.
   */
  constructor(e, t, i, n, s, a, o, l) {
    super({}, e, t, i, n, s, a, o, l), this.isVideoFrameTexture = !0;
  }
  /**
   * This method overwritten with an empty implementation since
   * this type of texture is updated via `setFrame()`.
   */
  update() {
  }
  clone() {
    return new this.constructor().copy(this);
  }
  /**
   * Sets the current frame of the video. This will automatically update the texture
   * so the data can be used for rendering.
   *
   * @param {VideoFrame} frame - The video frame.
   */
  setFrame(e) {
    this.image = e, this.needsUpdate = !0;
  }
}
class Sy extends Et {
  /**
   * Constructs a new framebuffer texture.
   *
   * @param {number} [width] - The width of the texture.
   * @param {number} [height] - The height of the texture.
   */
  constructor(e, t) {
    super({ width: e, height: t }), this.isFramebufferTexture = !0, this.magFilter = Xt, this.minFilter = Xt, this.generateMipmaps = !1, this.needsUpdate = !0;
  }
}
class ic extends Et {
  /**
   * Constructs a new compressed texture.
   *
   * @param {Array<Object>} mipmaps - This array holds for all mipmaps (including the bases mip)
   * the data and dimensions.
   * @param {number} width - The width of the texture.
   * @param {number} height - The height of the texture.
   * @param {number} [format=RGBAFormat] - The texture format.
   * @param {number} [type=UnsignedByteType] - The texture type.
   * @param {number} [mapping=Texture.DEFAULT_MAPPING] - The texture mapping.
   * @param {number} [wrapS=ClampToEdgeWrapping] - The wrapS value.
   * @param {number} [wrapT=ClampToEdgeWrapping] - The wrapT value.
   * @param {number} [magFilter=LinearFilter] - The mag filter value.
   * @param {number} [minFilter=LinearMipmapLinearFilter] - The min filter value.
   * @param {number} [anisotropy=Texture.DEFAULT_ANISOTROPY] - The anisotropy value.
   * @param {string} [colorSpace=NoColorSpace] - The color space.
   */
  constructor(e, t, i, n, s, a, o, l, c, h, d, u) {
    super(null, a, o, l, c, h, n, s, d, u), this.isCompressedTexture = !0, this.image = { width: t, height: i }, this.mipmaps = e, this.flipY = !1, this.generateMipmaps = !1;
  }
}
class My extends ic {
  /**
   * Constructs a new compressed array texture.
   *
   * @param {Array<Object>} mipmaps - This array holds for all mipmaps (including the bases mip)
   * the data and dimensions.
   * @param {number} width - The width of the texture.
   * @param {number} height - The height of the texture.
   * @param {number} depth - The depth of the texture.
   * @param {number} [format=RGBAFormat] - The min filter value.
   * @param {number} [type=UnsignedByteType] - The min filter value.
   */
  constructor(e, t, i, n, s, a) {
    super(e, t, i, s, a), this.isCompressedArrayTexture = !0, this.image.depth = n, this.wrapR = fi, this.layerUpdates = /* @__PURE__ */ new Set();
  }
  /**
   * Describes that a specific layer of the texture needs to be updated.
   * Normally when {@link Texture#needsUpdate} is set to `true`, the
   * entire compressed texture array is sent to the GPU. Marking specific
   * layers will only transmit subsets of all mipmaps associated with a
   * specific depth in the array which is often much more performant.
   *
   * @param {number} layerIndex - The layer index that should be updated.
   */
  addLayerUpdate(e) {
    this.layerUpdates.add(e);
  }
  /**
   * Resets the layer updates registry.
   */
  clearLayerUpdates() {
    this.layerUpdates.clear();
  }
}
class wy extends ic {
  /**
   * Constructs a new compressed texture.
   *
   * @param {Array<CompressedTexture>} images - An array of compressed textures.
   * @param {number} [format=RGBAFormat] - The texture format.
   * @param {number} [type=UnsignedByteType] - The texture type.
   */
  constructor(e, t, i) {
    super(void 0, e[0].width, e[0].height, t, i, _n), this.isCompressedCubeTexture = !0, this.isCubeTexture = !0, this.image = e;
  }
}
class fd extends Et {
  /**
   * Constructs a new texture.
   *
   * @param {HTMLCanvasElement} [canvas] - The HTML canvas element.
   * @param {number} [mapping=Texture.DEFAULT_MAPPING] - The texture mapping.
   * @param {number} [wrapS=ClampToEdgeWrapping] - The wrapS value.
   * @param {number} [wrapT=ClampToEdgeWrapping] - The wrapT value.
   * @param {number} [magFilter=LinearFilter] - The mag filter value.
   * @param {number} [minFilter=LinearMipmapLinearFilter] - The min filter value.
   * @param {number} [format=RGBAFormat] - The texture format.
   * @param {number} [type=UnsignedByteType] - The texture type.
   * @param {number} [anisotropy=Texture.DEFAULT_ANISOTROPY] - The anisotropy value.
   */
  constructor(e, t, i, n, s, a, o, l, c) {
    super(e, t, i, n, s, a, o, l, c), this.isCanvasTexture = !0, this.needsUpdate = !0;
  }
}
class md extends Et {
  /**
   * Constructs a new depth texture.
   *
   * @param {number} width - The width of the texture.
   * @param {number} height - The height of the texture.
   * @param {number} [type=UnsignedIntType] - The texture type.
   * @param {number} [mapping=Texture.DEFAULT_MAPPING] - The texture mapping.
   * @param {number} [wrapS=ClampToEdgeWrapping] - The wrapS value.
   * @param {number} [wrapT=ClampToEdgeWrapping] - The wrapT value.
   * @param {number} [magFilter=LinearFilter] - The mag filter value.
   * @param {number} [minFilter=LinearFilter] - The min filter value.
   * @param {number} [anisotropy=Texture.DEFAULT_ANISOTROPY] - The anisotropy value.
   * @param {number} [format=DepthFormat] - The texture format.
   * @param {number} [depth=1] - The depth of the texture.
   */
  constructor(e, t, i = yn, n, s, a, o = Xt, l = Xt, c, h = dr, d = 1) {
    if (h !== dr && h !== ur)
      throw new Error("DepthTexture format must be either THREE.DepthFormat or THREE.DepthStencilFormat");
    const u = { width: e, height: t, depth: d };
    super(u, n, s, a, o, l, h, i, c), this.isDepthTexture = !0, this.flipY = !1, this.generateMipmaps = !1, this.compareFunction = null;
  }
  copy(e) {
    return super.copy(e), this.source = new In(Object.assign({}, e.image)), this.compareFunction = e.compareFunction, this;
  }
  toJSON(e) {
    const t = super.toJSON(e);
    return this.compareFunction !== null && (t.compareFunction = this.compareFunction), t;
  }
}
class gd extends Et {
  /**
   * Creates a new raw texture.
   *
   * @param {?(WebGLTexture|GPUTexture)} [sourceTexture=null] - The external texture.
   */
  constructor(e = null) {
    super(), this.sourceTexture = e, this.isExternalTexture = !0;
  }
  copy(e) {
    return super.copy(e), this.sourceTexture = e.sourceTexture, this;
  }
}
class nc extends Ue {
  /**
   * Constructs a new capsule geometry.
   *
   * @param {number} [radius=1] - Radius of the capsule.
   * @param {number} [height=1] - Height of the middle section.
   * @param {number} [capSegments=4] - Number of curve segments used to build each cap.
   * @param {number} [radialSegments=8] - Number of segmented faces around the circumference of the capsule. Must be an integer >= 3.
   * @param {number} [heightSegments=1] - Number of rows of faces along the height of the middle section. Must be an integer >= 1.
   */
  constructor(e = 1, t = 1, i = 4, n = 8, s = 1) {
    super(), this.type = "CapsuleGeometry", this.parameters = {
      radius: e,
      height: t,
      capSegments: i,
      radialSegments: n,
      heightSegments: s
    }, t = Math.max(0, t), i = Math.max(1, Math.floor(i)), n = Math.max(3, Math.floor(n)), s = Math.max(1, Math.floor(s));
    const a = [], o = [], l = [], c = [], h = t / 2, d = Math.PI / 2 * e, u = t, p = 2 * d + u, m = i * 2 + s, _ = n + 1, g = new b(), f = new b();
    for (let v = 0; v <= m; v++) {
      let x = 0, y = 0, A = 0, S = 0;
      if (v <= i) {
        const E = v / i, w = E * Math.PI / 2;
        y = -h - e * Math.cos(w), A = e * Math.sin(w), S = -e * Math.cos(w), x = E * d;
      } else if (v <= i + s) {
        const E = (v - i) / s;
        y = -h + E * t, A = e, S = 0, x = d + E * u;
      } else {
        const E = (v - i - s) / i, w = E * Math.PI / 2;
        y = h + e * Math.sin(w), A = e * Math.cos(w), S = e * Math.sin(w), x = d + u + E * d;
      }
      const C = Math.max(0, Math.min(1, x / p));
      let P = 0;
      v === 0 ? P = 0.5 / n : v === m && (P = -0.5 / n);
      for (let E = 0; E <= n; E++) {
        const w = E / n, L = w * Math.PI * 2, N = Math.sin(L), B = Math.cos(L);
        f.x = -A * B, f.y = y, f.z = A * N, o.push(f.x, f.y, f.z), g.set(
          -A * B,
          S,
          A * N
        ), g.normalize(), l.push(g.x, g.y, g.z), c.push(w + P, C);
      }
      if (v > 0) {
        const E = (v - 1) * _;
        for (let w = 0; w < n; w++) {
          const L = E + w, N = E + w + 1, B = v * _ + w, W = v * _ + w + 1;
          a.push(L, N, B), a.push(N, W, B);
        }
      }
    }
    this.setIndex(a), this.setAttribute("position", new ve(o, 3)), this.setAttribute("normal", new ve(l, 3)), this.setAttribute("uv", new ve(c, 2));
  }
  copy(e) {
    return super.copy(e), this.parameters = Object.assign({}, e.parameters), this;
  }
  /**
   * Factory method for creating an instance of this class from the given
   * JSON object.
   *
   * @param {Object} data - A JSON object representing the serialized geometry.
   * @return {CapsuleGeometry} A new instance.
   */
  static fromJSON(e) {
    return new nc(e.radius, e.height, e.capSegments, e.radialSegments, e.heightSegments);
  }
}
class sc extends Ue {
  /**
   * Constructs a new circle geometry.
   *
   * @param {number} [radius=1] - Radius of the circle.
   * @param {number} [segments=32] - Number of segments (triangles), minimum = `3`.
   * @param {number} [thetaStart=0] - Start angle for first segment in radians.
   * @param {number} [thetaLength=Math.PI*2] - The central angle, often called theta,
   * of the circular sector in radians. The default value results in a complete circle.
   */
  constructor(e = 1, t = 32, i = 0, n = Math.PI * 2) {
    super(), this.type = "CircleGeometry", this.parameters = {
      radius: e,
      segments: t,
      thetaStart: i,
      thetaLength: n
    }, t = Math.max(3, t);
    const s = [], a = [], o = [], l = [], c = new b(), h = new H();
    a.push(0, 0, 0), o.push(0, 0, 1), l.push(0.5, 0.5);
    for (let d = 0, u = 3; d <= t; d++, u += 3) {
      const p = i + d / t * n;
      c.x = e * Math.cos(p), c.y = e * Math.sin(p), a.push(c.x, c.y, c.z), o.push(0, 0, 1), h.x = (a[u] / e + 1) / 2, h.y = (a[u + 1] / e + 1) / 2, l.push(h.x, h.y);
    }
    for (let d = 1; d <= t; d++)
      s.push(d, d + 1, 0);
    this.setIndex(s), this.setAttribute("position", new ve(a, 3)), this.setAttribute("normal", new ve(o, 3)), this.setAttribute("uv", new ve(l, 2));
  }
  copy(e) {
    return super.copy(e), this.parameters = Object.assign({}, e.parameters), this;
  }
  /**
   * Factory method for creating an instance of this class from the given
   * JSON object.
   *
   * @param {Object} data - A JSON object representing the serialized geometry.
   * @return {CircleGeometry} A new instance.
   */
  static fromJSON(e) {
    return new sc(e.radius, e.segments, e.thetaStart, e.thetaLength);
  }
}
class Mr extends Ue {
  /**
   * Constructs a new cylinder geometry.
   *
   * @param {number} [radiusTop=1] - Radius of the cylinder at the top.
   * @param {number} [radiusBottom=1] - Radius of the cylinder at the bottom.
   * @param {number} [height=1] - Height of the cylinder.
   * @param {number} [radialSegments=32] - Number of segmented faces around the circumference of the cylinder.
   * @param {number} [heightSegments=1] - Number of rows of faces along the height of the cylinder.
   * @param {boolean} [openEnded=false] - Whether the base of the cylinder is open or capped.
   * @param {number} [thetaStart=0] - Start angle for first segment, in radians.
   * @param {number} [thetaLength=Math.PI*2] - The central angle, often called theta, of the circular sector, in radians.
   * The default value results in a complete cylinder.
   */
  constructor(e = 1, t = 1, i = 1, n = 32, s = 1, a = !1, o = 0, l = Math.PI * 2) {
    super(), this.type = "CylinderGeometry", this.parameters = {
      radiusTop: e,
      radiusBottom: t,
      height: i,
      radialSegments: n,
      heightSegments: s,
      openEnded: a,
      thetaStart: o,
      thetaLength: l
    };
    const c = this;
    n = Math.floor(n), s = Math.floor(s);
    const h = [], d = [], u = [], p = [];
    let m = 0;
    const _ = [], g = i / 2;
    let f = 0;
    v(), a === !1 && (e > 0 && x(!0), t > 0 && x(!1)), this.setIndex(h), this.setAttribute("position", new ve(d, 3)), this.setAttribute("normal", new ve(u, 3)), this.setAttribute("uv", new ve(p, 2));
    function v() {
      const y = new b(), A = new b();
      let S = 0;
      const C = (t - e) / i;
      for (let P = 0; P <= s; P++) {
        const E = [], w = P / s, L = w * (t - e) + e;
        for (let N = 0; N <= n; N++) {
          const B = N / n, W = B * l + o, Z = Math.sin(W), X = Math.cos(W);
          A.x = L * Z, A.y = -w * i + g, A.z = L * X, d.push(A.x, A.y, A.z), y.set(Z, C, X).normalize(), u.push(y.x, y.y, y.z), p.push(B, 1 - w), E.push(m++);
        }
        _.push(E);
      }
      for (let P = 0; P < n; P++)
        for (let E = 0; E < s; E++) {
          const w = _[E][P], L = _[E + 1][P], N = _[E + 1][P + 1], B = _[E][P + 1];
          (e > 0 || E !== 0) && (h.push(w, L, B), S += 3), (t > 0 || E !== s - 1) && (h.push(L, N, B), S += 3);
        }
      c.addGroup(f, S, 0), f += S;
    }
    function x(y) {
      const A = m, S = new H(), C = new b();
      let P = 0;
      const E = y === !0 ? e : t, w = y === !0 ? 1 : -1;
      for (let N = 1; N <= n; N++)
        d.push(0, g * w, 0), u.push(0, w, 0), p.push(0.5, 0.5), m++;
      const L = m;
      for (let N = 0; N <= n; N++) {
        const W = N / n * l + o, Z = Math.cos(W), X = Math.sin(W);
        C.x = E * X, C.y = g * w, C.z = E * Z, d.push(C.x, C.y, C.z), u.push(0, w, 0), S.x = Z * 0.5 + 0.5, S.y = X * 0.5 * w + 0.5, p.push(S.x, S.y), m++;
      }
      for (let N = 0; N < n; N++) {
        const B = A + N, W = L + N;
        y === !0 ? h.push(W, W + 1, B) : h.push(W + 1, W, B), P += 3;
      }
      c.addGroup(f, P, y === !0 ? 1 : 2), f += P;
    }
  }
  copy(e) {
    return super.copy(e), this.parameters = Object.assign({}, e.parameters), this;
  }
  /**
   * Factory method for creating an instance of this class from the given
   * JSON object.
   *
   * @param {Object} data - A JSON object representing the serialized geometry.
   * @return {CylinderGeometry} A new instance.
   */
  static fromJSON(e) {
    return new Mr(e.radiusTop, e.radiusBottom, e.height, e.radialSegments, e.heightSegments, e.openEnded, e.thetaStart, e.thetaLength);
  }
}
class wr extends Mr {
  /**
   * Constructs a new cone geometry.
   *
   * @param {number} [radius=1] - Radius of the cone base.
   * @param {number} [height=1] - Height of the cone.
   * @param {number} [radialSegments=32] - Number of segmented faces around the circumference of the cone.
   * @param {number} [heightSegments=1] - Number of rows of faces along the height of the cone.
   * @param {boolean} [openEnded=false] - Whether the base of the cone is open or capped.
   * @param {number} [thetaStart=0] - Start angle for first segment, in radians.
   * @param {number} [thetaLength=Math.PI*2] - The central angle, often called theta, of the circular sector, in radians.
   * The default value results in a complete cone.
   */
  constructor(e = 1, t = 1, i = 32, n = 1, s = !1, a = 0, o = Math.PI * 2) {
    super(0, e, t, i, n, s, a, o), this.type = "ConeGeometry", this.parameters = {
      radius: e,
      height: t,
      radialSegments: i,
      heightSegments: n,
      openEnded: s,
      thetaStart: a,
      thetaLength: o
    };
  }
  /**
   * Factory method for creating an instance of this class from the given
   * JSON object.
   *
   * @param {Object} data - A JSON object representing the serialized geometry.
   * @return {ConeGeometry} A new instance.
   */
  static fromJSON(e) {
    return new wr(e.radius, e.height, e.radialSegments, e.heightSegments, e.openEnded, e.thetaStart, e.thetaLength);
  }
}
class Hn extends Ue {
  /**
   * Constructs a new polyhedron geometry.
   *
   * @param {Array<number>} [vertices] - A flat array of vertices describing the base shape.
   * @param {Array<number>} [indices] - A flat array of indices describing the base shape.
   * @param {number} [radius=1] - The radius of the shape.
   * @param {number} [detail=0] - How many levels to subdivide the geometry. The more detail, the smoother the shape.
   */
  constructor(e = [], t = [], i = 1, n = 0) {
    super(), this.type = "PolyhedronGeometry", this.parameters = {
      vertices: e,
      indices: t,
      radius: i,
      detail: n
    };
    const s = [], a = [];
    o(n), c(i), h(), this.setAttribute("position", new ve(s, 3)), this.setAttribute("normal", new ve(s.slice(), 3)), this.setAttribute("uv", new ve(a, 2)), n === 0 ? this.computeVertexNormals() : this.normalizeNormals();
    function o(v) {
      const x = new b(), y = new b(), A = new b();
      for (let S = 0; S < t.length; S += 3)
        p(t[S + 0], x), p(t[S + 1], y), p(t[S + 2], A), l(x, y, A, v);
    }
    function l(v, x, y, A) {
      const S = A + 1, C = [];
      for (let P = 0; P <= S; P++) {
        C[P] = [];
        const E = v.clone().lerp(y, P / S), w = x.clone().lerp(y, P / S), L = S - P;
        for (let N = 0; N <= L; N++)
          N === 0 && P === S ? C[P][N] = E : C[P][N] = E.clone().lerp(w, N / L);
      }
      for (let P = 0; P < S; P++)
        for (let E = 0; E < 2 * (S - P) - 1; E++) {
          const w = Math.floor(E / 2);
          E % 2 === 0 ? (u(C[P][w + 1]), u(C[P + 1][w]), u(C[P][w])) : (u(C[P][w + 1]), u(C[P + 1][w + 1]), u(C[P + 1][w]));
        }
    }
    function c(v) {
      const x = new b();
      for (let y = 0; y < s.length; y += 3)
        x.x = s[y + 0], x.y = s[y + 1], x.z = s[y + 2], x.normalize().multiplyScalar(v), s[y + 0] = x.x, s[y + 1] = x.y, s[y + 2] = x.z;
    }
    function h() {
      const v = new b();
      for (let x = 0; x < s.length; x += 3) {
        v.x = s[x + 0], v.y = s[x + 1], v.z = s[x + 2];
        const y = g(v) / 2 / Math.PI + 0.5, A = f(v) / Math.PI + 0.5;
        a.push(y, 1 - A);
      }
      m(), d();
    }
    function d() {
      for (let v = 0; v < a.length; v += 6) {
        const x = a[v + 0], y = a[v + 2], A = a[v + 4], S = Math.max(x, y, A), C = Math.min(x, y, A);
        S > 0.9 && C < 0.1 && (x < 0.2 && (a[v + 0] += 1), y < 0.2 && (a[v + 2] += 1), A < 0.2 && (a[v + 4] += 1));
      }
    }
    function u(v) {
      s.push(v.x, v.y, v.z);
    }
    function p(v, x) {
      const y = v * 3;
      x.x = e[y + 0], x.y = e[y + 1], x.z = e[y + 2];
    }
    function m() {
      const v = new b(), x = new b(), y = new b(), A = new b(), S = new H(), C = new H(), P = new H();
      for (let E = 0, w = 0; E < s.length; E += 9, w += 6) {
        v.set(s[E + 0], s[E + 1], s[E + 2]), x.set(s[E + 3], s[E + 4], s[E + 5]), y.set(s[E + 6], s[E + 7], s[E + 8]), S.set(a[w + 0], a[w + 1]), C.set(a[w + 2], a[w + 3]), P.set(a[w + 4], a[w + 5]), A.copy(v).add(x).add(y).divideScalar(3);
        const L = g(A);
        _(S, w + 0, v, L), _(C, w + 2, x, L), _(P, w + 4, y, L);
      }
    }
    function _(v, x, y, A) {
      A < 0 && v.x === 1 && (a[x] = v.x - 1), y.x === 0 && y.z === 0 && (a[x] = A / 2 / Math.PI + 0.5);
    }
    function g(v) {
      return Math.atan2(v.z, -v.x);
    }
    function f(v) {
      return Math.atan2(-v.y, Math.sqrt(v.x * v.x + v.z * v.z));
    }
  }
  copy(e) {
    return super.copy(e), this.parameters = Object.assign({}, e.parameters), this;
  }
  /**
   * Factory method for creating an instance of this class from the given
   * JSON object.
   *
   * @param {Object} data - A JSON object representing the serialized geometry.
   * @return {PolyhedronGeometry} A new instance.
   */
  static fromJSON(e) {
    return new Hn(e.vertices, e.indices, e.radius, e.details);
  }
}
class rc extends Hn {
  /**
   * Constructs a new dodecahedron geometry.
   *
   * @param {number} [radius=1] - Radius of the dodecahedron.
   * @param {number} [detail=0] - Setting this to a value greater than `0` adds vertices making it no longer a dodecahedron.
   */
  constructor(e = 1, t = 0) {
    const i = (1 + Math.sqrt(5)) / 2, n = 1 / i, s = [
      // (±1, ±1, ±1)
      -1,
      -1,
      -1,
      -1,
      -1,
      1,
      -1,
      1,
      -1,
      -1,
      1,
      1,
      1,
      -1,
      -1,
      1,
      -1,
      1,
      1,
      1,
      -1,
      1,
      1,
      1,
      // (0, ±1/φ, ±φ)
      0,
      -n,
      -i,
      0,
      -n,
      i,
      0,
      n,
      -i,
      0,
      n,
      i,
      // (±1/φ, ±φ, 0)
      -n,
      -i,
      0,
      -n,
      i,
      0,
      n,
      -i,
      0,
      n,
      i,
      0,
      // (±φ, 0, ±1/φ)
      -i,
      0,
      -n,
      i,
      0,
      -n,
      -i,
      0,
      n,
      i,
      0,
      n
    ], a = [
      3,
      11,
      7,
      3,
      7,
      15,
      3,
      15,
      13,
      7,
      19,
      17,
      7,
      17,
      6,
      7,
      6,
      15,
      17,
      4,
      8,
      17,
      8,
      10,
      17,
      10,
      6,
      8,
      0,
      16,
      8,
      16,
      2,
      8,
      2,
      10,
      0,
      12,
      1,
      0,
      1,
      18,
      0,
      18,
      16,
      6,
      10,
      2,
      6,
      2,
      13,
      6,
      13,
      15,
      2,
      16,
      18,
      2,
      18,
      3,
      2,
      3,
      13,
      18,
      1,
      9,
      18,
      9,
      11,
      18,
      11,
      3,
      4,
      14,
      12,
      4,
      12,
      0,
      4,
      0,
      8,
      11,
      9,
      5,
      11,
      5,
      19,
      11,
      19,
      7,
      19,
      5,
      14,
      19,
      14,
      4,
      19,
      4,
      17,
      1,
      12,
      14,
      1,
      14,
      5,
      1,
      5,
      9
    ];
    super(s, a, e, t), this.type = "DodecahedronGeometry", this.parameters = {
      radius: e,
      detail: t
    };
  }
  /**
   * Factory method for creating an instance of this class from the given
   * JSON object.
   *
   * @param {Object} data - A JSON object representing the serialized geometry.
   * @return {DodecahedronGeometry} A new instance.
   */
  static fromJSON(e) {
    return new rc(e.radius, e.detail);
  }
}
const ro = /* @__PURE__ */ new b(), ao = /* @__PURE__ */ new b(), Zc = /* @__PURE__ */ new b(), oo = /* @__PURE__ */ new pi();
class Sm extends Ue {
  /**
   * Constructs a new edges geometry.
   *
   * @param {?BufferGeometry} [geometry=null] - The geometry.
   * @param {number} [thresholdAngle=1] - An edge is only rendered if the angle (in degrees)
   * between the face normals of the adjoining faces exceeds this value.
   */
  constructor(e = null, t = 1) {
    if (super(), this.type = "EdgesGeometry", this.parameters = {
      geometry: e,
      thresholdAngle: t
    }, e !== null) {
      const n = Math.pow(10, 4), s = Math.cos(ms * t), a = e.getIndex(), o = e.getAttribute("position"), l = a ? a.count : o.count, c = [0, 0, 0], h = ["a", "b", "c"], d = new Array(3), u = {}, p = [];
      for (let m = 0; m < l; m += 3) {
        a ? (c[0] = a.getX(m), c[1] = a.getX(m + 1), c[2] = a.getX(m + 2)) : (c[0] = m, c[1] = m + 1, c[2] = m + 2);
        const { a: _, b: g, c: f } = oo;
        if (_.fromBufferAttribute(o, c[0]), g.fromBufferAttribute(o, c[1]), f.fromBufferAttribute(o, c[2]), oo.getNormal(Zc), d[0] = `${Math.round(_.x * n)},${Math.round(_.y * n)},${Math.round(_.z * n)}`, d[1] = `${Math.round(g.x * n)},${Math.round(g.y * n)},${Math.round(g.z * n)}`, d[2] = `${Math.round(f.x * n)},${Math.round(f.y * n)},${Math.round(f.z * n)}`, !(d[0] === d[1] || d[1] === d[2] || d[2] === d[0]))
          for (let v = 0; v < 3; v++) {
            const x = (v + 1) % 3, y = d[v], A = d[x], S = oo[h[v]], C = oo[h[x]], P = `${y}_${A}`, E = `${A}_${y}`;
            E in u && u[E] ? (Zc.dot(u[E].normal) <= s && (p.push(S.x, S.y, S.z), p.push(C.x, C.y, C.z)), u[E] = null) : P in u || (u[P] = {
              index0: c[v],
              index1: c[x],
              normal: Zc.clone()
            });
          }
      }
      for (const m in u)
        if (u[m]) {
          const { index0: _, index1: g } = u[m];
          ro.fromBufferAttribute(o, _), ao.fromBufferAttribute(o, g), p.push(ro.x, ro.y, ro.z), p.push(ao.x, ao.y, ao.z);
        }
      this.setAttribute("position", new ve(p, 3));
    }
  }
  copy(e) {
    return super.copy(e), this.parameters = Object.assign({}, e.parameters), this;
  }
}
class Vi {
  /**
   * Constructs a new curve.
   */
  constructor() {
    this.type = "Curve", this.arcLengthDivisions = 200, this.needsUpdate = !1, this.cacheArcLengths = null;
  }
  /**
   * This method returns a vector in 2D or 3D space (depending on the curve definition)
   * for the given interpolation factor.
   *
   * @abstract
   * @param {number} t - A interpolation factor representing a position on the curve. Must be in the range `[0,1]`.
   * @param {(Vector2|Vector3)} [optionalTarget] - The optional target vector the result is written to.
   * @return {(Vector2|Vector3)} The position on the curve. It can be a 2D or 3D vector depending on the curve definition.
   */
  getPoint() {
    console.warn("THREE.Curve: .getPoint() not implemented.");
  }
  /**
   * This method returns a vector in 2D or 3D space (depending on the curve definition)
   * for the given interpolation factor. Unlike {@link Curve#getPoint}, this method honors the length
   * of the curve which equidistant samples.
   *
   * @param {number} u - A interpolation factor representing a position on the curve. Must be in the range `[0,1]`.
   * @param {(Vector2|Vector3)} [optionalTarget] - The optional target vector the result is written to.
   * @return {(Vector2|Vector3)} The position on the curve. It can be a 2D or 3D vector depending on the curve definition.
   */
  getPointAt(e, t) {
    const i = this.getUtoTmapping(e);
    return this.getPoint(i, t);
  }
  /**
   * This method samples the curve via {@link Curve#getPoint} and returns an array of points representing
   * the curve shape.
   *
   * @param {number} [divisions=5] - The number of divisions.
   * @return {Array<(Vector2|Vector3)>} An array holding the sampled curve values. The number of points is `divisions + 1`.
   */
  getPoints(e = 5) {
    const t = [];
    for (let i = 0; i <= e; i++)
      t.push(this.getPoint(i / e));
    return t;
  }
  // Get sequence of points using getPointAt( u )
  /**
   * This method samples the curve via {@link Curve#getPointAt} and returns an array of points representing
   * the curve shape. Unlike {@link Curve#getPoints}, this method returns equi-spaced points across the entire
   * curve.
   *
   * @param {number} [divisions=5] - The number of divisions.
   * @return {Array<(Vector2|Vector3)>} An array holding the sampled curve values. The number of points is `divisions + 1`.
   */
  getSpacedPoints(e = 5) {
    const t = [];
    for (let i = 0; i <= e; i++)
      t.push(this.getPointAt(i / e));
    return t;
  }
  /**
   * Returns the total arc length of the curve.
   *
   * @return {number} The length of the curve.
   */
  getLength() {
    const e = this.getLengths();
    return e[e.length - 1];
  }
  /**
   * Returns an array of cumulative segment lengths of the curve.
   *
   * @param {number} [divisions=this.arcLengthDivisions] - The number of divisions.
   * @return {Array<number>} An array holding the cumulative segment lengths.
   */
  getLengths(e = this.arcLengthDivisions) {
    if (this.cacheArcLengths && this.cacheArcLengths.length === e + 1 && !this.needsUpdate)
      return this.cacheArcLengths;
    this.needsUpdate = !1;
    const t = [];
    let i, n = this.getPoint(0), s = 0;
    t.push(0);
    for (let a = 1; a <= e; a++)
      i = this.getPoint(a / e), s += i.distanceTo(n), t.push(s), n = i;
    return this.cacheArcLengths = t, t;
  }
  /**
   * Update the cumulative segment distance cache. The method must be called
   * every time curve parameters are changed. If an updated curve is part of a
   * composed curve like {@link CurvePath}, this method must be called on the
   * composed curve, too.
   */
  updateArcLengths() {
    this.needsUpdate = !0, this.getLengths();
  }
  /**
   * Given an interpolation factor in the range `[0,1]`, this method returns an updated
   * interpolation factor in the same range that can be ued to sample equidistant points
   * from a curve.
   *
   * @param {number} u - The interpolation factor.
   * @param {?number} distance - An optional distance on the curve.
   * @return {number} The updated interpolation factor.
   */
  getUtoTmapping(e, t = null) {
    const i = this.getLengths();
    let n = 0;
    const s = i.length;
    let a;
    t ? a = t : a = e * i[s - 1];
    let o = 0, l = s - 1, c;
    for (; o <= l; )
      if (n = Math.floor(o + (l - o) / 2), c = i[n] - a, c < 0)
        o = n + 1;
      else if (c > 0)
        l = n - 1;
      else {
        l = n;
        break;
      }
    if (n = l, i[n] === a)
      return n / (s - 1);
    const h = i[n], u = i[n + 1] - h, p = (a - h) / u;
    return (n + p) / (s - 1);
  }
  /**
   * Returns a unit vector tangent for the given interpolation factor.
   * If the derived curve does not implement its tangent derivation,
   * two points a small delta apart will be used to find its gradient
   * which seems to give a reasonable approximation.
   *
   * @param {number} t - The interpolation factor.
   * @param {(Vector2|Vector3)} [optionalTarget] - The optional target vector the result is written to.
   * @return {(Vector2|Vector3)} The tangent vector.
   */
  getTangent(e, t) {
    let n = e - 1e-4, s = e + 1e-4;
    n < 0 && (n = 0), s > 1 && (s = 1);
    const a = this.getPoint(n), o = this.getPoint(s), l = t || (a.isVector2 ? new H() : new b());
    return l.copy(o).sub(a).normalize(), l;
  }
  /**
   * Same as {@link Curve#getTangent} but with equidistant samples.
   *
   * @param {number} u - The interpolation factor.
   * @param {(Vector2|Vector3)} [optionalTarget] - The optional target vector the result is written to.
   * @return {(Vector2|Vector3)} The tangent vector.
   * @see {@link Curve#getPointAt}
   */
  getTangentAt(e, t) {
    const i = this.getUtoTmapping(e);
    return this.getTangent(i, t);
  }
  /**
   * Generates the Frenet Frames. Requires a curve definition in 3D space. Used
   * in geometries like {@link TubeGeometry} or {@link ExtrudeGeometry}.
   *
   * @param {number} segments - The number of segments.
   * @param {boolean} [closed=false] - Whether the curve is closed or not.
   * @return {{tangents: Array<Vector3>, normals: Array<Vector3>, binormals: Array<Vector3>}} The Frenet Frames.
   */
  computeFrenetFrames(e, t = !1) {
    const i = new b(), n = [], s = [], a = [], o = new b(), l = new Ne();
    for (let p = 0; p <= e; p++) {
      const m = p / e;
      n[p] = this.getTangentAt(m, new b());
    }
    s[0] = new b(), a[0] = new b();
    let c = Number.MAX_VALUE;
    const h = Math.abs(n[0].x), d = Math.abs(n[0].y), u = Math.abs(n[0].z);
    h <= c && (c = h, i.set(1, 0, 0)), d <= c && (c = d, i.set(0, 1, 0)), u <= c && i.set(0, 0, 1), o.crossVectors(n[0], i).normalize(), s[0].crossVectors(n[0], o), a[0].crossVectors(n[0], s[0]);
    for (let p = 1; p <= e; p++) {
      if (s[p] = s[p - 1].clone(), a[p] = a[p - 1].clone(), o.crossVectors(n[p - 1], n[p]), o.length() > Number.EPSILON) {
        o.normalize();
        const m = Math.acos(Fe(n[p - 1].dot(n[p]), -1, 1));
        s[p].applyMatrix4(l.makeRotationAxis(o, m));
      }
      a[p].crossVectors(n[p], s[p]);
    }
    if (t === !0) {
      let p = Math.acos(Fe(s[0].dot(s[e]), -1, 1));
      p /= e, n[0].dot(o.crossVectors(s[0], s[e])) > 0 && (p = -p);
      for (let m = 1; m <= e; m++)
        s[m].applyMatrix4(l.makeRotationAxis(n[m], p * m)), a[m].crossVectors(n[m], s[m]);
    }
    return {
      tangents: n,
      normals: s,
      binormals: a
    };
  }
  /**
   * Returns a new curve with copied values from this instance.
   *
   * @return {Curve} A clone of this instance.
   */
  clone() {
    return new this.constructor().copy(this);
  }
  /**
   * Copies the values of the given curve to this instance.
   *
   * @param {Curve} source - The curve to copy.
   * @return {Curve} A reference to this curve.
   */
  copy(e) {
    return this.arcLengthDivisions = e.arcLengthDivisions, this;
  }
  /**
   * Serializes the curve into JSON.
   *
   * @return {Object} A JSON object representing the serialized curve.
   * @see {@link ObjectLoader#parse}
   */
  toJSON() {
    const e = {
      metadata: {
        version: 4.7,
        type: "Curve",
        generator: "Curve.toJSON"
      }
    };
    return e.arcLengthDivisions = this.arcLengthDivisions, e.type = this.type, e;
  }
  /**
   * Deserializes the curve from the given JSON.
   *
   * @param {Object} json - The JSON holding the serialized curve.
   * @return {Curve} A reference to this curve.
   */
  fromJSON(e) {
    return this.arcLengthDivisions = e.arcLengthDivisions, this;
  }
}
class ac extends Vi {
  /**
   * Constructs a new ellipse curve.
   *
   * @param {number} [aX=0] - The X center of the ellipse.
   * @param {number} [aY=0] - The Y center of the ellipse.
   * @param {number} [xRadius=1] - The radius of the ellipse in the x direction.
   * @param {number} [yRadius=1] - The radius of the ellipse in the y direction.
   * @param {number} [aStartAngle=0] - The start angle of the curve in radians starting from the positive X axis.
   * @param {number} [aEndAngle=Math.PI*2] - The end angle of the curve in radians starting from the positive X axis.
   * @param {boolean} [aClockwise=false] - Whether the ellipse is drawn clockwise or not.
   * @param {number} [aRotation=0] - The rotation angle of the ellipse in radians, counterclockwise from the positive X axis.
   */
  constructor(e = 0, t = 0, i = 1, n = 1, s = 0, a = Math.PI * 2, o = !1, l = 0) {
    super(), this.isEllipseCurve = !0, this.type = "EllipseCurve", this.aX = e, this.aY = t, this.xRadius = i, this.yRadius = n, this.aStartAngle = s, this.aEndAngle = a, this.aClockwise = o, this.aRotation = l;
  }
  /**
   * Returns a point on the curve.
   *
   * @param {number} t - A interpolation factor representing a position on the curve. Must be in the range `[0,1]`.
   * @param {Vector2} [optionalTarget] - The optional target vector the result is written to.
   * @return {Vector2} The position on the curve.
   */
  getPoint(e, t = new H()) {
    const i = t, n = Math.PI * 2;
    let s = this.aEndAngle - this.aStartAngle;
    const a = Math.abs(s) < Number.EPSILON;
    for (; s < 0; ) s += n;
    for (; s > n; ) s -= n;
    s < Number.EPSILON && (a ? s = 0 : s = n), this.aClockwise === !0 && !a && (s === n ? s = -n : s = s - n);
    const o = this.aStartAngle + e * s;
    let l = this.aX + this.xRadius * Math.cos(o), c = this.aY + this.yRadius * Math.sin(o);
    if (this.aRotation !== 0) {
      const h = Math.cos(this.aRotation), d = Math.sin(this.aRotation), u = l - this.aX, p = c - this.aY;
      l = u * h - p * d + this.aX, c = u * d + p * h + this.aY;
    }
    return i.set(l, c);
  }
  copy(e) {
    return super.copy(e), this.aX = e.aX, this.aY = e.aY, this.xRadius = e.xRadius, this.yRadius = e.yRadius, this.aStartAngle = e.aStartAngle, this.aEndAngle = e.aEndAngle, this.aClockwise = e.aClockwise, this.aRotation = e.aRotation, this;
  }
  toJSON() {
    const e = super.toJSON();
    return e.aX = this.aX, e.aY = this.aY, e.xRadius = this.xRadius, e.yRadius = this.yRadius, e.aStartAngle = this.aStartAngle, e.aEndAngle = this.aEndAngle, e.aClockwise = this.aClockwise, e.aRotation = this.aRotation, e;
  }
  fromJSON(e) {
    return super.fromJSON(e), this.aX = e.aX, this.aY = e.aY, this.xRadius = e.xRadius, this.yRadius = e.yRadius, this.aStartAngle = e.aStartAngle, this.aEndAngle = e.aEndAngle, this.aClockwise = e.aClockwise, this.aRotation = e.aRotation, this;
  }
}
class Mm extends ac {
  /**
   * Constructs a new arc curve.
   *
   * @param {number} [aX=0] - The X center of the ellipse.
   * @param {number} [aY=0] - The Y center of the ellipse.
   * @param {number} [aRadius=1] - The radius of the ellipse in the x direction.
   * @param {number} [aStartAngle=0] - The start angle of the curve in radians starting from the positive X axis.
   * @param {number} [aEndAngle=Math.PI*2] - The end angle of the curve in radians starting from the positive X axis.
   * @param {boolean} [aClockwise=false] - Whether the ellipse is drawn clockwise or not.
   */
  constructor(e, t, i, n, s, a) {
    super(e, t, i, i, n, s, a), this.isArcCurve = !0, this.type = "ArcCurve";
  }
}
function _d() {
  let r = 0, e = 0, t = 0, i = 0;
  function n(s, a, o, l) {
    r = s, e = o, t = -3 * s + 3 * a - 2 * o - l, i = 2 * s - 2 * a + o + l;
  }
  return {
    initCatmullRom: function(s, a, o, l, c) {
      n(a, o, c * (o - s), c * (l - a));
    },
    initNonuniformCatmullRom: function(s, a, o, l, c, h, d) {
      let u = (a - s) / c - (o - s) / (c + h) + (o - a) / h, p = (o - a) / h - (l - a) / (h + d) + (l - o) / d;
      u *= h, p *= h, n(a, o, u, p);
    },
    calc: function(s) {
      const a = s * s, o = a * s;
      return r + e * s + t * a + i * o;
    }
  };
}
const lo = /* @__PURE__ */ new b(), Yc = /* @__PURE__ */ new _d(), jc = /* @__PURE__ */ new _d(), $c = /* @__PURE__ */ new _d();
class wm extends Vi {
  /**
   * Constructs a new Catmull-Rom curve.
   *
   * @param {Array<Vector3>} [points] - An array of 3D points defining the curve.
   * @param {boolean} [closed=false] - Whether the curve is closed or not.
   * @param {('centripetal'|'chordal'|'catmullrom')} [curveType='centripetal'] - The curve type.
   * @param {number} [tension=0.5] - Tension of the curve.
   */
  constructor(e = [], t = !1, i = "centripetal", n = 0.5) {
    super(), this.isCatmullRomCurve3 = !0, this.type = "CatmullRomCurve3", this.points = e, this.closed = t, this.curveType = i, this.tension = n;
  }
  /**
   * Returns a point on the curve.
   *
   * @param {number} t - A interpolation factor representing a position on the curve. Must be in the range `[0,1]`.
   * @param {Vector3} [optionalTarget] - The optional target vector the result is written to.
   * @return {Vector3} The position on the curve.
   */
  getPoint(e, t = new b()) {
    const i = t, n = this.points, s = n.length, a = (s - (this.closed ? 0 : 1)) * e;
    let o = Math.floor(a), l = a - o;
    this.closed ? o += o > 0 ? 0 : (Math.floor(Math.abs(o) / s) + 1) * s : l === 0 && o === s - 1 && (o = s - 2, l = 1);
    let c, h;
    this.closed || o > 0 ? c = n[(o - 1) % s] : (lo.subVectors(n[0], n[1]).add(n[0]), c = lo);
    const d = n[o % s], u = n[(o + 1) % s];
    if (this.closed || o + 2 < s ? h = n[(o + 2) % s] : (lo.subVectors(n[s - 1], n[s - 2]).add(n[s - 1]), h = lo), this.curveType === "centripetal" || this.curveType === "chordal") {
      const p = this.curveType === "chordal" ? 0.5 : 0.25;
      let m = Math.pow(c.distanceToSquared(d), p), _ = Math.pow(d.distanceToSquared(u), p), g = Math.pow(u.distanceToSquared(h), p);
      _ < 1e-4 && (_ = 1), m < 1e-4 && (m = _), g < 1e-4 && (g = _), Yc.initNonuniformCatmullRom(c.x, d.x, u.x, h.x, m, _, g), jc.initNonuniformCatmullRom(c.y, d.y, u.y, h.y, m, _, g), $c.initNonuniformCatmullRom(c.z, d.z, u.z, h.z, m, _, g);
    } else this.curveType === "catmullrom" && (Yc.initCatmullRom(c.x, d.x, u.x, h.x, this.tension), jc.initCatmullRom(c.y, d.y, u.y, h.y, this.tension), $c.initCatmullRom(c.z, d.z, u.z, h.z, this.tension));
    return i.set(
      Yc.calc(l),
      jc.calc(l),
      $c.calc(l)
    ), i;
  }
  copy(e) {
    super.copy(e), this.points = [];
    for (let t = 0, i = e.points.length; t < i; t++) {
      const n = e.points[t];
      this.points.push(n.clone());
    }
    return this.closed = e.closed, this.curveType = e.curveType, this.tension = e.tension, this;
  }
  toJSON() {
    const e = super.toJSON();
    e.points = [];
    for (let t = 0, i = this.points.length; t < i; t++) {
      const n = this.points[t];
      e.points.push(n.toArray());
    }
    return e.closed = this.closed, e.curveType = this.curveType, e.tension = this.tension, e;
  }
  fromJSON(e) {
    super.fromJSON(e), this.points = [];
    for (let t = 0, i = e.points.length; t < i; t++) {
      const n = e.points[t];
      this.points.push(new b().fromArray(n));
    }
    return this.closed = e.closed, this.curveType = e.curveType, this.tension = e.tension, this;
  }
}
function Bu(r, e, t, i, n) {
  const s = (i - e) * 0.5, a = (n - t) * 0.5, o = r * r, l = r * o;
  return (2 * t - 2 * i + s + a) * l + (-3 * t + 3 * i - 2 * s - a) * o + s * r + t;
}
function Ey(r, e) {
  const t = 1 - r;
  return t * t * e;
}
function Ty(r, e) {
  return 2 * (1 - r) * r * e;
}
function Ay(r, e) {
  return r * r * e;
}
function ea(r, e, t, i) {
  return Ey(r, e) + Ty(r, t) + Ay(r, i);
}
function Cy(r, e) {
  const t = 1 - r;
  return t * t * t * e;
}
function Ry(r, e) {
  const t = 1 - r;
  return 3 * t * t * r * e;
}
function Py(r, e) {
  return 3 * (1 - r) * r * r * e;
}
function Ly(r, e) {
  return r * r * r * e;
}
function ta(r, e, t, i, n) {
  return Cy(r, e) + Ry(r, t) + Py(r, i) + Ly(r, n);
}
class yd extends Vi {
  /**
   * Constructs a new Cubic Bezier curve.
   *
   * @param {Vector2} [v0] - The start point.
   * @param {Vector2} [v1] - The first control point.
   * @param {Vector2} [v2] - The second control point.
   * @param {Vector2} [v3] - The end point.
   */
  constructor(e = new H(), t = new H(), i = new H(), n = new H()) {
    super(), this.isCubicBezierCurve = !0, this.type = "CubicBezierCurve", this.v0 = e, this.v1 = t, this.v2 = i, this.v3 = n;
  }
  /**
   * Returns a point on the curve.
   *
   * @param {number} t - A interpolation factor representing a position on the curve. Must be in the range `[0,1]`.
   * @param {Vector2} [optionalTarget] - The optional target vector the result is written to.
   * @return {Vector2} The position on the curve.
   */
  getPoint(e, t = new H()) {
    const i = t, n = this.v0, s = this.v1, a = this.v2, o = this.v3;
    return i.set(
      ta(e, n.x, s.x, a.x, o.x),
      ta(e, n.y, s.y, a.y, o.y)
    ), i;
  }
  copy(e) {
    return super.copy(e), this.v0.copy(e.v0), this.v1.copy(e.v1), this.v2.copy(e.v2), this.v3.copy(e.v3), this;
  }
  toJSON() {
    const e = super.toJSON();
    return e.v0 = this.v0.toArray(), e.v1 = this.v1.toArray(), e.v2 = this.v2.toArray(), e.v3 = this.v3.toArray(), e;
  }
  fromJSON(e) {
    return super.fromJSON(e), this.v0.fromArray(e.v0), this.v1.fromArray(e.v1), this.v2.fromArray(e.v2), this.v3.fromArray(e.v3), this;
  }
}
class Em extends Vi {
  /**
   * Constructs a new Cubic Bezier curve.
   *
   * @param {Vector3} [v0] - The start point.
   * @param {Vector3} [v1] - The first control point.
   * @param {Vector3} [v2] - The second control point.
   * @param {Vector3} [v3] - The end point.
   */
  constructor(e = new b(), t = new b(), i = new b(), n = new b()) {
    super(), this.isCubicBezierCurve3 = !0, this.type = "CubicBezierCurve3", this.v0 = e, this.v1 = t, this.v2 = i, this.v3 = n;
  }
  /**
   * Returns a point on the curve.
   *
   * @param {number} t - A interpolation factor representing a position on the curve. Must be in the range `[0,1]`.
   * @param {Vector3} [optionalTarget] - The optional target vector the result is written to.
   * @return {Vector3} The position on the curve.
   */
  getPoint(e, t = new b()) {
    const i = t, n = this.v0, s = this.v1, a = this.v2, o = this.v3;
    return i.set(
      ta(e, n.x, s.x, a.x, o.x),
      ta(e, n.y, s.y, a.y, o.y),
      ta(e, n.z, s.z, a.z, o.z)
    ), i;
  }
  copy(e) {
    return super.copy(e), this.v0.copy(e.v0), this.v1.copy(e.v1), this.v2.copy(e.v2), this.v3.copy(e.v3), this;
  }
  toJSON() {
    const e = super.toJSON();
    return e.v0 = this.v0.toArray(), e.v1 = this.v1.toArray(), e.v2 = this.v2.toArray(), e.v3 = this.v3.toArray(), e;
  }
  fromJSON(e) {
    return super.fromJSON(e), this.v0.fromArray(e.v0), this.v1.fromArray(e.v1), this.v2.fromArray(e.v2), this.v3.fromArray(e.v3), this;
  }
}
class vd extends Vi {
  /**
   * Constructs a new line curve.
   *
   * @param {Vector2} [v1] - The start point.
   * @param {Vector2} [v2] - The end point.
   */
  constructor(e = new H(), t = new H()) {
    super(), this.isLineCurve = !0, this.type = "LineCurve", this.v1 = e, this.v2 = t;
  }
  /**
   * Returns a point on the line.
   *
   * @param {number} t - A interpolation factor representing a position on the line. Must be in the range `[0,1]`.
   * @param {Vector2} [optionalTarget] - The optional target vector the result is written to.
   * @return {Vector2} The position on the line.
   */
  getPoint(e, t = new H()) {
    const i = t;
    return e === 1 ? i.copy(this.v2) : (i.copy(this.v2).sub(this.v1), i.multiplyScalar(e).add(this.v1)), i;
  }
  // Line curve is linear, so we can overwrite default getPointAt
  getPointAt(e, t) {
    return this.getPoint(e, t);
  }
  getTangent(e, t = new H()) {
    return t.subVectors(this.v2, this.v1).normalize();
  }
  getTangentAt(e, t) {
    return this.getTangent(e, t);
  }
  copy(e) {
    return super.copy(e), this.v1.copy(e.v1), this.v2.copy(e.v2), this;
  }
  toJSON() {
    const e = super.toJSON();
    return e.v1 = this.v1.toArray(), e.v2 = this.v2.toArray(), e;
  }
  fromJSON(e) {
    return super.fromJSON(e), this.v1.fromArray(e.v1), this.v2.fromArray(e.v2), this;
  }
}
class Tm extends Vi {
  /**
   * Constructs a new line curve.
   *
   * @param {Vector3} [v1] - The start point.
   * @param {Vector3} [v2] - The end point.
   */
  constructor(e = new b(), t = new b()) {
    super(), this.isLineCurve3 = !0, this.type = "LineCurve3", this.v1 = e, this.v2 = t;
  }
  /**
   * Returns a point on the line.
   *
   * @param {number} t - A interpolation factor representing a position on the line. Must be in the range `[0,1]`.
   * @param {Vector3} [optionalTarget] - The optional target vector the result is written to.
   * @return {Vector3} The position on the line.
   */
  getPoint(e, t = new b()) {
    const i = t;
    return e === 1 ? i.copy(this.v2) : (i.copy(this.v2).sub(this.v1), i.multiplyScalar(e).add(this.v1)), i;
  }
  // Line curve is linear, so we can overwrite default getPointAt
  getPointAt(e, t) {
    return this.getPoint(e, t);
  }
  getTangent(e, t = new b()) {
    return t.subVectors(this.v2, this.v1).normalize();
  }
  getTangentAt(e, t) {
    return this.getTangent(e, t);
  }
  copy(e) {
    return super.copy(e), this.v1.copy(e.v1), this.v2.copy(e.v2), this;
  }
  toJSON() {
    const e = super.toJSON();
    return e.v1 = this.v1.toArray(), e.v2 = this.v2.toArray(), e;
  }
  fromJSON(e) {
    return super.fromJSON(e), this.v1.fromArray(e.v1), this.v2.fromArray(e.v2), this;
  }
}
class xd extends Vi {
  /**
   * Constructs a new Quadratic Bezier curve.
   *
   * @param {Vector2} [v0] - The start point.
   * @param {Vector2} [v1] - The control point.
   * @param {Vector2} [v2] - The end point.
   */
  constructor(e = new H(), t = new H(), i = new H()) {
    super(), this.isQuadraticBezierCurve = !0, this.type = "QuadraticBezierCurve", this.v0 = e, this.v1 = t, this.v2 = i;
  }
  /**
   * Returns a point on the curve.
   *
   * @param {number} t - A interpolation factor representing a position on the curve. Must be in the range `[0,1]`.
   * @param {Vector2} [optionalTarget] - The optional target vector the result is written to.
   * @return {Vector2} The position on the curve.
   */
  getPoint(e, t = new H()) {
    const i = t, n = this.v0, s = this.v1, a = this.v2;
    return i.set(
      ea(e, n.x, s.x, a.x),
      ea(e, n.y, s.y, a.y)
    ), i;
  }
  copy(e) {
    return super.copy(e), this.v0.copy(e.v0), this.v1.copy(e.v1), this.v2.copy(e.v2), this;
  }
  toJSON() {
    const e = super.toJSON();
    return e.v0 = this.v0.toArray(), e.v1 = this.v1.toArray(), e.v2 = this.v2.toArray(), e;
  }
  fromJSON(e) {
    return super.fromJSON(e), this.v0.fromArray(e.v0), this.v1.fromArray(e.v1), this.v2.fromArray(e.v2), this;
  }
}
class bd extends Vi {
  /**
   * Constructs a new Quadratic Bezier curve.
   *
   * @param {Vector3} [v0] - The start point.
   * @param {Vector3} [v1] - The control point.
   * @param {Vector3} [v2] - The end point.
   */
  constructor(e = new b(), t = new b(), i = new b()) {
    super(), this.isQuadraticBezierCurve3 = !0, this.type = "QuadraticBezierCurve3", this.v0 = e, this.v1 = t, this.v2 = i;
  }
  /**
   * Returns a point on the curve.
   *
   * @param {number} t - A interpolation factor representing a position on the curve. Must be in the range `[0,1]`.
   * @param {Vector3} [optionalTarget] - The optional target vector the result is written to.
   * @return {Vector3} The position on the curve.
   */
  getPoint(e, t = new b()) {
    const i = t, n = this.v0, s = this.v1, a = this.v2;
    return i.set(
      ea(e, n.x, s.x, a.x),
      ea(e, n.y, s.y, a.y),
      ea(e, n.z, s.z, a.z)
    ), i;
  }
  copy(e) {
    return super.copy(e), this.v0.copy(e.v0), this.v1.copy(e.v1), this.v2.copy(e.v2), this;
  }
  toJSON() {
    const e = super.toJSON();
    return e.v0 = this.v0.toArray(), e.v1 = this.v1.toArray(), e.v2 = this.v2.toArray(), e;
  }
  fromJSON(e) {
    return super.fromJSON(e), this.v0.fromArray(e.v0), this.v1.fromArray(e.v1), this.v2.fromArray(e.v2), this;
  }
}
class Sd extends Vi {
  /**
   * Constructs a new 2D spline curve.
   *
   * @param {Array<Vector2>} [points] -  An array of 2D points defining the curve.
   */
  constructor(e = []) {
    super(), this.isSplineCurve = !0, this.type = "SplineCurve", this.points = e;
  }
  /**
   * Returns a point on the curve.
   *
   * @param {number} t - A interpolation factor representing a position on the curve. Must be in the range `[0,1]`.
   * @param {Vector2} [optionalTarget] - The optional target vector the result is written to.
   * @return {Vector2} The position on the curve.
   */
  getPoint(e, t = new H()) {
    const i = t, n = this.points, s = (n.length - 1) * e, a = Math.floor(s), o = s - a, l = n[a === 0 ? a : a - 1], c = n[a], h = n[a > n.length - 2 ? n.length - 1 : a + 1], d = n[a > n.length - 3 ? n.length - 1 : a + 2];
    return i.set(
      Bu(o, l.x, c.x, h.x, d.x),
      Bu(o, l.y, c.y, h.y, d.y)
    ), i;
  }
  copy(e) {
    super.copy(e), this.points = [];
    for (let t = 0, i = e.points.length; t < i; t++) {
      const n = e.points[t];
      this.points.push(n.clone());
    }
    return this;
  }
  toJSON() {
    const e = super.toJSON();
    e.points = [];
    for (let t = 0, i = this.points.length; t < i; t++) {
      const n = this.points[t];
      e.points.push(n.toArray());
    }
    return e;
  }
  fromJSON(e) {
    super.fromJSON(e), this.points = [];
    for (let t = 0, i = e.points.length; t < i; t++) {
      const n = e.points[t];
      this.points.push(new H().fromArray(n));
    }
    return this;
  }
}
var Il = /* @__PURE__ */ Object.freeze({
  __proto__: null,
  ArcCurve: Mm,
  CatmullRomCurve3: wm,
  CubicBezierCurve: yd,
  CubicBezierCurve3: Em,
  EllipseCurve: ac,
  LineCurve: vd,
  LineCurve3: Tm,
  QuadraticBezierCurve: xd,
  QuadraticBezierCurve3: bd,
  SplineCurve: Sd
});
class Am extends Vi {
  /**
   * Constructs a new curve path.
   */
  constructor() {
    super(), this.type = "CurvePath", this.curves = [], this.autoClose = !1;
  }
  /**
   * Adds a curve to this curve path.
   *
   * @param {Curve} curve - The curve to add.
   */
  add(e) {
    this.curves.push(e);
  }
  /**
   * Adds a line curve to close the path.
   *
   * @return {CurvePath} A reference to this curve path.
   */
  closePath() {
    const e = this.curves[0].getPoint(0), t = this.curves[this.curves.length - 1].getPoint(1);
    if (!e.equals(t)) {
      const i = e.isVector2 === !0 ? "LineCurve" : "LineCurve3";
      this.curves.push(new Il[i](t, e));
    }
    return this;
  }
  /**
   * This method returns a vector in 2D or 3D space (depending on the curve definitions)
   * for the given interpolation factor.
   *
   * @param {number} t - A interpolation factor representing a position on the curve. Must be in the range `[0,1]`.
   * @param {(Vector2|Vector3)} [optionalTarget] - The optional target vector the result is written to.
   * @return {?(Vector2|Vector3)} The position on the curve. It can be a 2D or 3D vector depending on the curve definition.
   */
  getPoint(e, t) {
    const i = e * this.getLength(), n = this.getCurveLengths();
    let s = 0;
    for (; s < n.length; ) {
      if (n[s] >= i) {
        const a = n[s] - i, o = this.curves[s], l = o.getLength(), c = l === 0 ? 0 : 1 - a / l;
        return o.getPointAt(c, t);
      }
      s++;
    }
    return null;
  }
  getLength() {
    const e = this.getCurveLengths();
    return e[e.length - 1];
  }
  updateArcLengths() {
    this.needsUpdate = !0, this.cacheLengths = null, this.getCurveLengths();
  }
  /**
   * Returns list of cumulative curve lengths of the defined curves.
   *
   * @return {Array<number>} The curve lengths.
   */
  getCurveLengths() {
    if (this.cacheLengths && this.cacheLengths.length === this.curves.length)
      return this.cacheLengths;
    const e = [];
    let t = 0;
    for (let i = 0, n = this.curves.length; i < n; i++)
      t += this.curves[i].getLength(), e.push(t);
    return this.cacheLengths = e, e;
  }
  getSpacedPoints(e = 40) {
    const t = [];
    for (let i = 0; i <= e; i++)
      t.push(this.getPoint(i / e));
    return this.autoClose && t.push(t[0]), t;
  }
  getPoints(e = 12) {
    const t = [];
    let i;
    for (let n = 0, s = this.curves; n < s.length; n++) {
      const a = s[n], o = a.isEllipseCurve ? e * 2 : a.isLineCurve || a.isLineCurve3 ? 1 : a.isSplineCurve ? e * a.points.length : e, l = a.getPoints(o);
      for (let c = 0; c < l.length; c++) {
        const h = l[c];
        i && i.equals(h) || (t.push(h), i = h);
      }
    }
    return this.autoClose && t.length > 1 && !t[t.length - 1].equals(t[0]) && t.push(t[0]), t;
  }
  copy(e) {
    super.copy(e), this.curves = [];
    for (let t = 0, i = e.curves.length; t < i; t++) {
      const n = e.curves[t];
      this.curves.push(n.clone());
    }
    return this.autoClose = e.autoClose, this;
  }
  toJSON() {
    const e = super.toJSON();
    e.autoClose = this.autoClose, e.curves = [];
    for (let t = 0, i = this.curves.length; t < i; t++) {
      const n = this.curves[t];
      e.curves.push(n.toJSON());
    }
    return e;
  }
  fromJSON(e) {
    super.fromJSON(e), this.autoClose = e.autoClose, this.curves = [];
    for (let t = 0, i = e.curves.length; t < i; t++) {
      const n = e.curves[t];
      this.curves.push(new Il[n.type]().fromJSON(n));
    }
    return this;
  }
}
class Dl extends Am {
  /**
   * Constructs a new path.
   *
   * @param {Array<Vector2>} [points] - An array of 2D points defining the path.
   */
  constructor(e) {
    super(), this.type = "Path", this.currentPoint = new H(), e && this.setFromPoints(e);
  }
  /**
   * Creates a path from the given list of points. The points are added
   * to the path as instances of {@link LineCurve}.
   *
   * @param {Array<Vector2>} points - An array of 2D points.
   * @return {Path} A reference to this path.
   */
  setFromPoints(e) {
    this.moveTo(e[0].x, e[0].y);
    for (let t = 1, i = e.length; t < i; t++)
      this.lineTo(e[t].x, e[t].y);
    return this;
  }
  /**
   * Moves {@link Path#currentPoint} to the given point.
   *
   * @param {number} x - The x coordinate.
   * @param {number} y - The y coordinate.
   * @return {Path} A reference to this path.
   */
  moveTo(e, t) {
    return this.currentPoint.set(e, t), this;
  }
  /**
   * Adds an instance of {@link LineCurve} to the path by connecting
   * the current point with the given one.
   *
   * @param {number} x - The x coordinate of the end point.
   * @param {number} y - The y coordinate of the end point.
   * @return {Path} A reference to this path.
   */
  lineTo(e, t) {
    const i = new vd(this.currentPoint.clone(), new H(e, t));
    return this.curves.push(i), this.currentPoint.set(e, t), this;
  }
  /**
   * Adds an instance of {@link QuadraticBezierCurve} to the path by connecting
   * the current point with the given one.
   *
   * @param {number} aCPx - The x coordinate of the control point.
   * @param {number} aCPy - The y coordinate of the control point.
   * @param {number} aX - The x coordinate of the end point.
   * @param {number} aY - The y coordinate of the end point.
   * @return {Path} A reference to this path.
   */
  quadraticCurveTo(e, t, i, n) {
    const s = new xd(
      this.currentPoint.clone(),
      new H(e, t),
      new H(i, n)
    );
    return this.curves.push(s), this.currentPoint.set(i, n), this;
  }
  /**
   * Adds an instance of {@link CubicBezierCurve} to the path by connecting
   * the current point with the given one.
   *
   * @param {number} aCP1x - The x coordinate of the first control point.
   * @param {number} aCP1y - The y coordinate of the first control point.
   * @param {number} aCP2x - The x coordinate of the second control point.
   * @param {number} aCP2y - The y coordinate of the second control point.
   * @param {number} aX - The x coordinate of the end point.
   * @param {number} aY - The y coordinate of the end point.
   * @return {Path} A reference to this path.
   */
  bezierCurveTo(e, t, i, n, s, a) {
    const o = new yd(
      this.currentPoint.clone(),
      new H(e, t),
      new H(i, n),
      new H(s, a)
    );
    return this.curves.push(o), this.currentPoint.set(s, a), this;
  }
  /**
   * Adds an instance of {@link SplineCurve} to the path by connecting
   * the current point with the given list of points.
   *
   * @param {Array<Vector2>} pts - An array of points in 2D space.
   * @return {Path} A reference to this path.
   */
  splineThru(e) {
    const t = [this.currentPoint.clone()].concat(e), i = new Sd(t);
    return this.curves.push(i), this.currentPoint.copy(e[e.length - 1]), this;
  }
  /**
   * Adds an arc as an instance of {@link EllipseCurve} to the path, positioned relative
   * to the current point.
   *
   * @param {number} [aX=0] - The x coordinate of the center of the arc offsetted from the previous curve.
   * @param {number} [aY=0] - The y coordinate of the center of the arc offsetted from the previous curve.
   * @param {number} [aRadius=1] - The radius of the arc.
   * @param {number} [aStartAngle=0] - The start angle in radians.
   * @param {number} [aEndAngle=Math.PI*2] - The end angle in radians.
   * @param {boolean} [aClockwise=false] - Whether to sweep the arc clockwise or not.
   * @return {Path} A reference to this path.
   */
  arc(e, t, i, n, s, a) {
    const o = this.currentPoint.x, l = this.currentPoint.y;
    return this.absarc(
      e + o,
      t + l,
      i,
      n,
      s,
      a
    ), this;
  }
  /**
   * Adds an absolutely positioned arc as an instance of {@link EllipseCurve} to the path.
   *
   * @param {number} [aX=0] - The x coordinate of the center of the arc.
   * @param {number} [aY=0] - The y coordinate of the center of the arc.
   * @param {number} [aRadius=1] - The radius of the arc.
   * @param {number} [aStartAngle=0] - The start angle in radians.
   * @param {number} [aEndAngle=Math.PI*2] - The end angle in radians.
   * @param {boolean} [aClockwise=false] - Whether to sweep the arc clockwise or not.
   * @return {Path} A reference to this path.
   */
  absarc(e, t, i, n, s, a) {
    return this.absellipse(e, t, i, i, n, s, a), this;
  }
  /**
   * Adds an ellipse as an instance of {@link EllipseCurve} to the path, positioned relative
   * to the current point
   *
   * @param {number} [aX=0] - The x coordinate of the center of the ellipse offsetted from the previous curve.
   * @param {number} [aY=0] - The y coordinate of the center of the ellipse offsetted from the previous curve.
   * @param {number} [xRadius=1] - The radius of the ellipse in the x axis.
   * @param {number} [yRadius=1] - The radius of the ellipse in the y axis.
   * @param {number} [aStartAngle=0] - The start angle in radians.
   * @param {number} [aEndAngle=Math.PI*2] - The end angle in radians.
   * @param {boolean} [aClockwise=false] - Whether to sweep the ellipse clockwise or not.
   * @param {number} [aRotation=0] - The rotation angle of the ellipse in radians, counterclockwise from the positive X axis.
   * @return {Path} A reference to this path.
   */
  ellipse(e, t, i, n, s, a, o, l) {
    const c = this.currentPoint.x, h = this.currentPoint.y;
    return this.absellipse(e + c, t + h, i, n, s, a, o, l), this;
  }
  /**
   * Adds an absolutely positioned ellipse as an instance of {@link EllipseCurve} to the path.
   *
   * @param {number} [aX=0] - The x coordinate of the absolute center of the ellipse.
   * @param {number} [aY=0] - The y coordinate of the absolute center of the ellipse.
   * @param {number} [xRadius=1] - The radius of the ellipse in the x axis.
   * @param {number} [yRadius=1] - The radius of the ellipse in the y axis.
   * @param {number} [aStartAngle=0] - The start angle in radians.
   * @param {number} [aEndAngle=Math.PI*2] - The end angle in radians.
   * @param {boolean} [aClockwise=false] - Whether to sweep the ellipse clockwise or not.
   * @param {number} [aRotation=0] - The rotation angle of the ellipse in radians, counterclockwise from the positive X axis.
   * @return {Path} A reference to this path.
   */
  absellipse(e, t, i, n, s, a, o, l) {
    const c = new ac(e, t, i, n, s, a, o, l);
    if (this.curves.length > 0) {
      const d = c.getPoint(0);
      d.equals(this.currentPoint) || this.lineTo(d.x, d.y);
    }
    this.curves.push(c);
    const h = c.getPoint(1);
    return this.currentPoint.copy(h), this;
  }
  copy(e) {
    return super.copy(e), this.currentPoint.copy(e.currentPoint), this;
  }
  toJSON() {
    const e = super.toJSON();
    return e.currentPoint = this.currentPoint.toArray(), e;
  }
  fromJSON(e) {
    return super.fromJSON(e), this.currentPoint.fromArray(e.currentPoint), this;
  }
}
class Nn extends Dl {
  /**
   * Constructs a new shape.
   *
   * @param {Array<Vector2>} [points] - An array of 2D points defining the shape.
   */
  constructor(e) {
    super(e), this.uuid = Ti(), this.type = "Shape", this.holes = [];
  }
  /**
   * Returns an array representing each contour of the holes
   * as a list of 2D points.
   *
   * @param {number} divisions - The fineness of the result.
   * @return {Array<Array<Vector2>>} The holes as a series of 2D points.
   */
  getPointsHoles(e) {
    const t = [];
    for (let i = 0, n = this.holes.length; i < n; i++)
      t[i] = this.holes[i].getPoints(e);
    return t;
  }
  // get points of shape and holes (keypoints based on segments parameter)
  /**
   * Returns an object that holds contour data for the shape and its holes as
   * arrays of 2D points.
   *
   * @param {number} divisions - The fineness of the result.
   * @return {{shape:Array<Vector2>,holes:Array<Array<Vector2>>}} An object with contour data.
   */
  extractPoints(e) {
    return {
      shape: this.getPoints(e),
      holes: this.getPointsHoles(e)
    };
  }
  copy(e) {
    super.copy(e), this.holes = [];
    for (let t = 0, i = e.holes.length; t < i; t++) {
      const n = e.holes[t];
      this.holes.push(n.clone());
    }
    return this;
  }
  toJSON() {
    const e = super.toJSON();
    e.uuid = this.uuid, e.holes = [];
    for (let t = 0, i = this.holes.length; t < i; t++) {
      const n = this.holes[t];
      e.holes.push(n.toJSON());
    }
    return e;
  }
  fromJSON(e) {
    super.fromJSON(e), this.uuid = e.uuid, this.holes = [];
    for (let t = 0, i = e.holes.length; t < i; t++) {
      const n = e.holes[t];
      this.holes.push(new Dl().fromJSON(n));
    }
    return this;
  }
}
function Iy(r, e, t = 2) {
  const i = e && e.length, n = i ? e[0] * t : r.length;
  let s = Cm(r, 0, n, t, !0);
  const a = [];
  if (!s || s.next === s.prev) return a;
  let o, l, c;
  if (i && (s = Fy(r, e, s, t)), r.length > 80 * t) {
    o = 1 / 0, l = 1 / 0;
    let h = -1 / 0, d = -1 / 0;
    for (let u = t; u < n; u += t) {
      const p = r[u], m = r[u + 1];
      p < o && (o = p), m < l && (l = m), p > h && (h = p), m > d && (d = m);
    }
    c = Math.max(h - o, d - l), c = c !== 0 ? 32767 / c : 0;
  }
  return fa(s, a, t, o, l, c, 0), a;
}
function Cm(r, e, t, i, n) {
  let s;
  if (n === Yy(r, e, t, i) > 0)
    for (let a = e; a < t; a += i) s = ku(a / i | 0, r[a], r[a + 1], s);
  else
    for (let a = t - i; a >= e; a -= i) s = ku(a / i | 0, r[a], r[a + 1], s);
  return s && _r(s, s.next) && (ga(s), s = s.next), s;
}
function bs(r, e) {
  if (!r) return r;
  e || (e = r);
  let t = r, i;
  do
    if (i = !1, !t.steiner && (_r(t, t.next) || wt(t.prev, t, t.next) === 0)) {
      if (ga(t), t = e = t.prev, t === t.next) break;
      i = !0;
    } else
      t = t.next;
  while (i || t !== e);
  return e;
}
function fa(r, e, t, i, n, s, a) {
  if (!r) return;
  !a && s && Vy(r, i, n, s);
  let o = r;
  for (; r.prev !== r.next; ) {
    const l = r.prev, c = r.next;
    if (s ? Ny(r, i, n, s) : Dy(r)) {
      e.push(l.i, r.i, c.i), ga(r), r = c.next, o = c.next;
      continue;
    }
    if (r = c, r === o) {
      a ? a === 1 ? (r = Uy(bs(r), e), fa(r, e, t, i, n, s, 2)) : a === 2 && Oy(r, e, t, i, n, s) : fa(bs(r), e, t, i, n, s, 1);
      break;
    }
  }
}
function Dy(r) {
  const e = r.prev, t = r, i = r.next;
  if (wt(e, t, i) >= 0) return !1;
  const n = e.x, s = t.x, a = i.x, o = e.y, l = t.y, c = i.y, h = Math.min(n, s, a), d = Math.min(o, l, c), u = Math.max(n, s, a), p = Math.max(o, l, c);
  let m = i.next;
  for (; m !== e; ) {
    if (m.x >= h && m.x <= u && m.y >= d && m.y <= p && Wr(n, o, s, l, a, c, m.x, m.y) && wt(m.prev, m, m.next) >= 0) return !1;
    m = m.next;
  }
  return !0;
}
function Ny(r, e, t, i) {
  const n = r.prev, s = r, a = r.next;
  if (wt(n, s, a) >= 0) return !1;
  const o = n.x, l = s.x, c = a.x, h = n.y, d = s.y, u = a.y, p = Math.min(o, l, c), m = Math.min(h, d, u), _ = Math.max(o, l, c), g = Math.max(h, d, u), f = Fh(p, m, e, t, i), v = Fh(_, g, e, t, i);
  let x = r.prevZ, y = r.nextZ;
  for (; x && x.z >= f && y && y.z <= v; ) {
    if (x.x >= p && x.x <= _ && x.y >= m && x.y <= g && x !== n && x !== a && Wr(o, h, l, d, c, u, x.x, x.y) && wt(x.prev, x, x.next) >= 0 || (x = x.prevZ, y.x >= p && y.x <= _ && y.y >= m && y.y <= g && y !== n && y !== a && Wr(o, h, l, d, c, u, y.x, y.y) && wt(y.prev, y, y.next) >= 0)) return !1;
    y = y.nextZ;
  }
  for (; x && x.z >= f; ) {
    if (x.x >= p && x.x <= _ && x.y >= m && x.y <= g && x !== n && x !== a && Wr(o, h, l, d, c, u, x.x, x.y) && wt(x.prev, x, x.next) >= 0) return !1;
    x = x.prevZ;
  }
  for (; y && y.z <= v; ) {
    if (y.x >= p && y.x <= _ && y.y >= m && y.y <= g && y !== n && y !== a && Wr(o, h, l, d, c, u, y.x, y.y) && wt(y.prev, y, y.next) >= 0) return !1;
    y = y.nextZ;
  }
  return !0;
}
function Uy(r, e) {
  let t = r;
  do {
    const i = t.prev, n = t.next.next;
    !_r(i, n) && Pm(i, t, t.next, n) && ma(i, n) && ma(n, i) && (e.push(i.i, t.i, n.i), ga(t), ga(t.next), t = r = n), t = t.next;
  } while (t !== r);
  return bs(t);
}
function Oy(r, e, t, i, n, s) {
  let a = r;
  do {
    let o = a.next.next;
    for (; o !== a.prev; ) {
      if (a.i !== o.i && Xy(a, o)) {
        let l = Lm(a, o);
        a = bs(a, a.next), l = bs(l, l.next), fa(a, e, t, i, n, s, 0), fa(l, e, t, i, n, s, 0);
        return;
      }
      o = o.next;
    }
    a = a.next;
  } while (a !== r);
}
function Fy(r, e, t, i) {
  const n = [];
  for (let s = 0, a = e.length; s < a; s++) {
    const o = e[s] * i, l = s < a - 1 ? e[s + 1] * i : r.length, c = Cm(r, o, l, i, !1);
    c === c.next && (c.steiner = !0), n.push(Wy(c));
  }
  n.sort(By);
  for (let s = 0; s < n.length; s++)
    t = ky(n[s], t);
  return t;
}
function By(r, e) {
  let t = r.x - e.x;
  if (t === 0 && (t = r.y - e.y, t === 0)) {
    const i = (r.next.y - r.y) / (r.next.x - r.x), n = (e.next.y - e.y) / (e.next.x - e.x);
    t = i - n;
  }
  return t;
}
function ky(r, e) {
  const t = zy(r, e);
  if (!t)
    return e;
  const i = Lm(t, r);
  return bs(i, i.next), bs(t, t.next);
}
function zy(r, e) {
  let t = e;
  const i = r.x, n = r.y;
  let s = -1 / 0, a;
  if (_r(r, t)) return t;
  do {
    if (_r(r, t.next)) return t.next;
    if (n <= t.y && n >= t.next.y && t.next.y !== t.y) {
      const d = t.x + (n - t.y) * (t.next.x - t.x) / (t.next.y - t.y);
      if (d <= i && d > s && (s = d, a = t.x < t.next.x ? t : t.next, d === i))
        return a;
    }
    t = t.next;
  } while (t !== e);
  if (!a) return null;
  const o = a, l = a.x, c = a.y;
  let h = 1 / 0;
  t = a;
  do {
    if (i >= t.x && t.x >= l && i !== t.x && Rm(n < c ? i : s, n, l, c, n < c ? s : i, n, t.x, t.y)) {
      const d = Math.abs(n - t.y) / (i - t.x);
      ma(t, r) && (d < h || d === h && (t.x > a.x || t.x === a.x && Hy(a, t))) && (a = t, h = d);
    }
    t = t.next;
  } while (t !== o);
  return a;
}
function Hy(r, e) {
  return wt(r.prev, r, e.prev) < 0 && wt(e.next, r, r.next) < 0;
}
function Vy(r, e, t, i) {
  let n = r;
  do
    n.z === 0 && (n.z = Fh(n.x, n.y, e, t, i)), n.prevZ = n.prev, n.nextZ = n.next, n = n.next;
  while (n !== r);
  n.prevZ.nextZ = null, n.prevZ = null, Gy(n);
}
function Gy(r) {
  let e, t = 1;
  do {
    let i = r, n;
    r = null;
    let s = null;
    for (e = 0; i; ) {
      e++;
      let a = i, o = 0;
      for (let c = 0; c < t && (o++, a = a.nextZ, !!a); c++)
        ;
      let l = t;
      for (; o > 0 || l > 0 && a; )
        o !== 0 && (l === 0 || !a || i.z <= a.z) ? (n = i, i = i.nextZ, o--) : (n = a, a = a.nextZ, l--), s ? s.nextZ = n : r = n, n.prevZ = s, s = n;
      i = a;
    }
    s.nextZ = null, t *= 2;
  } while (e > 1);
  return r;
}
function Fh(r, e, t, i, n) {
  return r = (r - t) * n | 0, e = (e - i) * n | 0, r = (r | r << 8) & 16711935, r = (r | r << 4) & 252645135, r = (r | r << 2) & 858993459, r = (r | r << 1) & 1431655765, e = (e | e << 8) & 16711935, e = (e | e << 4) & 252645135, e = (e | e << 2) & 858993459, e = (e | e << 1) & 1431655765, r | e << 1;
}
function Wy(r) {
  let e = r, t = r;
  do
    (e.x < t.x || e.x === t.x && e.y < t.y) && (t = e), e = e.next;
  while (e !== r);
  return t;
}
function Rm(r, e, t, i, n, s, a, o) {
  return (n - a) * (e - o) >= (r - a) * (s - o) && (r - a) * (i - o) >= (t - a) * (e - o) && (t - a) * (s - o) >= (n - a) * (i - o);
}
function Wr(r, e, t, i, n, s, a, o) {
  return !(r === a && e === o) && Rm(r, e, t, i, n, s, a, o);
}
function Xy(r, e) {
  return r.next.i !== e.i && r.prev.i !== e.i && !qy(r, e) && // doesn't intersect other edges
  (ma(r, e) && ma(e, r) && Zy(r, e) && // locally visible
  (wt(r.prev, r, e.prev) || wt(r, e.prev, e)) || // does not create opposite-facing sectors
  _r(r, e) && wt(r.prev, r, r.next) > 0 && wt(e.prev, e, e.next) > 0);
}
function wt(r, e, t) {
  return (e.y - r.y) * (t.x - e.x) - (e.x - r.x) * (t.y - e.y);
}
function _r(r, e) {
  return r.x === e.x && r.y === e.y;
}
function Pm(r, e, t, i) {
  const n = ho(wt(r, e, t)), s = ho(wt(r, e, i)), a = ho(wt(t, i, r)), o = ho(wt(t, i, e));
  return !!(n !== s && a !== o || n === 0 && co(r, t, e) || s === 0 && co(r, i, e) || a === 0 && co(t, r, i) || o === 0 && co(t, e, i));
}
function co(r, e, t) {
  return e.x <= Math.max(r.x, t.x) && e.x >= Math.min(r.x, t.x) && e.y <= Math.max(r.y, t.y) && e.y >= Math.min(r.y, t.y);
}
function ho(r) {
  return r > 0 ? 1 : r < 0 ? -1 : 0;
}
function qy(r, e) {
  let t = r;
  do {
    if (t.i !== r.i && t.next.i !== r.i && t.i !== e.i && t.next.i !== e.i && Pm(t, t.next, r, e)) return !0;
    t = t.next;
  } while (t !== r);
  return !1;
}
function ma(r, e) {
  return wt(r.prev, r, r.next) < 0 ? wt(r, e, r.next) >= 0 && wt(r, r.prev, e) >= 0 : wt(r, e, r.prev) < 0 || wt(r, r.next, e) < 0;
}
function Zy(r, e) {
  let t = r, i = !1;
  const n = (r.x + e.x) / 2, s = (r.y + e.y) / 2;
  do
    t.y > s != t.next.y > s && t.next.y !== t.y && n < (t.next.x - t.x) * (s - t.y) / (t.next.y - t.y) + t.x && (i = !i), t = t.next;
  while (t !== r);
  return i;
}
function Lm(r, e) {
  const t = Bh(r.i, r.x, r.y), i = Bh(e.i, e.x, e.y), n = r.next, s = e.prev;
  return r.next = e, e.prev = r, t.next = n, n.prev = t, i.next = t, t.prev = i, s.next = i, i.prev = s, i;
}
function ku(r, e, t, i) {
  const n = Bh(r, e, t);
  return i ? (n.next = i.next, n.prev = i, i.next.prev = n, i.next = n) : (n.prev = n, n.next = n), n;
}
function ga(r) {
  r.next.prev = r.prev, r.prev.next = r.next, r.prevZ && (r.prevZ.nextZ = r.nextZ), r.nextZ && (r.nextZ.prevZ = r.prevZ);
}
function Bh(r, e, t) {
  return {
    i: r,
    // vertex index in coordinates array
    x: e,
    y: t,
    // vertex coordinates
    prev: null,
    // previous and next vertex nodes in a polygon ring
    next: null,
    z: 0,
    // z-order curve value
    prevZ: null,
    // previous and next nodes in z-order
    nextZ: null,
    steiner: !1
    // indicates whether this is a steiner point
  };
}
function Yy(r, e, t, i) {
  let n = 0;
  for (let s = e, a = t - i; s < t; s += i)
    n += (r[a] - r[s]) * (r[s + 1] + r[a + 1]), a = s;
  return n;
}
class jy {
  /**
   * Triangulates the given shape definition by returning an array of triangles.
   *
   * @param {Array<number>} data - An array with 2D points.
   * @param {Array<number>} holeIndices - An array with indices defining holes.
   * @param {number} [dim=2] - The number of coordinates per vertex in the input array.
   * @return {Array<number>} An array representing the triangulated faces. Each face is defined by three consecutive numbers
   * representing vertex indices.
   */
  static triangulate(e, t, i = 2) {
    return Iy(e, t, i);
  }
}
class zi {
  /**
   * Calculate area of a ( 2D ) contour polygon.
   *
   * @param {Array<Vector2>} contour - An array of 2D points.
   * @return {number} The area.
   */
  static area(e) {
    const t = e.length;
    let i = 0;
    for (let n = t - 1, s = 0; s < t; n = s++)
      i += e[n].x * e[s].y - e[s].x * e[n].y;
    return i * 0.5;
  }
  /**
   * Returns `true` if the given contour uses a clockwise winding order.
   *
   * @param {Array<Vector2>} pts - An array of 2D points defining a polygon.
   * @return {boolean} Whether the given contour uses a clockwise winding order or not.
   */
  static isClockWise(e) {
    return zi.area(e) < 0;
  }
  /**
   * Triangulates the given shape definition.
   *
   * @param {Array<Vector2>} contour - An array of 2D points defining the contour.
   * @param {Array<Array<Vector2>>} holes - An array that holds arrays of 2D points defining the holes.
   * @return {Array<Array<number>>} An array that holds for each face definition an array with three indices.
   */
  static triangulateShape(e, t) {
    const i = [], n = [], s = [];
    zu(e), Hu(i, e);
    let a = e.length;
    t.forEach(zu);
    for (let l = 0; l < t.length; l++)
      n.push(a), a += t[l].length, Hu(i, t[l]);
    const o = jy.triangulate(i, n);
    for (let l = 0; l < o.length; l += 3)
      s.push(o.slice(l, l + 3));
    return s;
  }
}
function zu(r) {
  const e = r.length;
  e > 2 && r[e - 1].equals(r[0]) && r.pop();
}
function Hu(r, e) {
  for (let t = 0; t < e.length; t++)
    r.push(e[t].x), r.push(e[t].y);
}
class wa extends Ue {
  /**
   * Constructs a new extrude geometry.
   *
   * @param {Shape|Array<Shape>} [shapes] - A shape or an array of shapes.
   * @param {ExtrudeGeometry~Options} [options] - The extrude settings.
   */
  constructor(e = new Nn([new H(0.5, 0.5), new H(-0.5, 0.5), new H(-0.5, -0.5), new H(0.5, -0.5)]), t = {}) {
    super(), this.type = "ExtrudeGeometry", this.parameters = {
      shapes: e,
      options: t
    }, e = Array.isArray(e) ? e : [e];
    const i = this, n = [], s = [];
    for (let o = 0, l = e.length; o < l; o++) {
      const c = e[o];
      a(c);
    }
    this.setAttribute("position", new ve(n, 3)), this.setAttribute("uv", new ve(s, 2)), this.computeVertexNormals();
    function a(o) {
      const l = [], c = t.curveSegments !== void 0 ? t.curveSegments : 12, h = t.steps !== void 0 ? t.steps : 1, d = t.depth !== void 0 ? t.depth : 1;
      let u = t.bevelEnabled !== void 0 ? t.bevelEnabled : !0, p = t.bevelThickness !== void 0 ? t.bevelThickness : 0.2, m = t.bevelSize !== void 0 ? t.bevelSize : p - 0.1, _ = t.bevelOffset !== void 0 ? t.bevelOffset : 0, g = t.bevelSegments !== void 0 ? t.bevelSegments : 3;
      const f = t.extrudePath, v = t.UVGenerator !== void 0 ? t.UVGenerator : $y;
      let x, y = !1, A, S, C, P;
      f && (x = f.getSpacedPoints(h), y = !0, u = !1, A = f.computeFrenetFrames(h, !1), S = new b(), C = new b(), P = new b()), u || (g = 0, p = 0, m = 0, _ = 0);
      const E = o.extractPoints(c);
      let w = E.shape;
      const L = E.holes;
      if (!zi.isClockWise(w)) {
        w = w.reverse();
        for (let ee = 0, K = L.length; ee < K; ee++) {
          const $ = L[ee];
          zi.isClockWise($) && (L[ee] = $.reverse());
        }
      }
      function B(ee) {
        const $ = 10000000000000001e-36;
        let j = ee[0];
        for (let de = 1; de <= ee.length; de++) {
          const ne = de % ee.length, ue = ee[ne], Ve = ue.x - j.x, ze = ue.y - j.y, R = Ve * Ve + ze * ze, M = Math.max(
            Math.abs(ue.x),
            Math.abs(ue.y),
            Math.abs(j.x),
            Math.abs(j.y)
          ), F = $ * M * M;
          if (R <= F) {
            ee.splice(ne, 1), de--;
            continue;
          }
          j = ue;
        }
      }
      B(w), L.forEach(B);
      const W = L.length, Z = w;
      for (let ee = 0; ee < W; ee++) {
        const K = L[ee];
        w = w.concat(K);
      }
      function X(ee, K, $) {
        return K || console.error("THREE.ExtrudeGeometry: vec does not exist"), ee.clone().addScaledVector(K, $);
      }
      const ie = w.length;
      function G(ee, K, $) {
        let j, de, ne;
        const ue = ee.x - K.x, Ve = ee.y - K.y, ze = $.x - ee.x, R = $.y - ee.y, M = ue * ue + Ve * Ve, F = ue * R - Ve * ze;
        if (Math.abs(F) > Number.EPSILON) {
          const V = Math.sqrt(M), Q = Math.sqrt(ze * ze + R * R), q = K.x - Ve / V, Re = K.y + ue / V, ce = $.x - R / Q, Te = $.y + ze / Q, Ae = ((ce - q) * R - (Te - Re) * ze) / (ue * R - Ve * ze);
          j = q + ue * Ae - ee.x, de = Re + Ve * Ae - ee.y;
          const se = j * j + de * de;
          if (se <= 2)
            return new H(j, de);
          ne = Math.sqrt(se / 2);
        } else {
          let V = !1;
          ue > Number.EPSILON ? ze > Number.EPSILON && (V = !0) : ue < -Number.EPSILON ? ze < -Number.EPSILON && (V = !0) : Math.sign(Ve) === Math.sign(R) && (V = !0), V ? (j = -Ve, de = ue, ne = Math.sqrt(M)) : (j = ue, de = Ve, ne = Math.sqrt(M / 2));
        }
        return new H(j / ne, de / ne);
      }
      const he = [];
      for (let ee = 0, K = Z.length, $ = K - 1, j = ee + 1; ee < K; ee++, $++, j++)
        $ === K && ($ = 0), j === K && (j = 0), he[ee] = G(Z[ee], Z[$], Z[j]);
      const me = [];
      let Se, We = he.concat();
      for (let ee = 0, K = W; ee < K; ee++) {
        const $ = L[ee];
        Se = [];
        for (let j = 0, de = $.length, ne = de - 1, ue = j + 1; j < de; j++, ne++, ue++)
          ne === de && (ne = 0), ue === de && (ue = 0), Se[j] = G($[j], $[ne], $[ue]);
        me.push(Se), We = We.concat(Se);
      }
      let Qe;
      if (g === 0)
        Qe = zi.triangulateShape(Z, L);
      else {
        const ee = [], K = [];
        for (let $ = 0; $ < g; $++) {
          const j = $ / g, de = p * Math.cos(j * Math.PI / 2), ne = m * Math.sin(j * Math.PI / 2) + _;
          for (let ue = 0, Ve = Z.length; ue < Ve; ue++) {
            const ze = X(Z[ue], he[ue], ne);
            Le(ze.x, ze.y, -de), j === 0 && ee.push(ze);
          }
          for (let ue = 0, Ve = W; ue < Ve; ue++) {
            const ze = L[ue];
            Se = me[ue];
            const R = [];
            for (let M = 0, F = ze.length; M < F; M++) {
              const V = X(ze[M], Se[M], ne);
              Le(V.x, V.y, -de), j === 0 && R.push(V);
            }
            j === 0 && K.push(R);
          }
        }
        Qe = zi.triangulateShape(ee, K);
      }
      const ht = Qe.length, nt = m + _;
      for (let ee = 0; ee < ie; ee++) {
        const K = u ? X(w[ee], We[ee], nt) : w[ee];
        y ? (C.copy(A.normals[0]).multiplyScalar(K.x), S.copy(A.binormals[0]).multiplyScalar(K.y), P.copy(x[0]).add(C).add(S), Le(P.x, P.y, P.z)) : Le(K.x, K.y, 0);
      }
      for (let ee = 1; ee <= h; ee++)
        for (let K = 0; K < ie; K++) {
          const $ = u ? X(w[K], We[K], nt) : w[K];
          y ? (C.copy(A.normals[ee]).multiplyScalar($.x), S.copy(A.binormals[ee]).multiplyScalar($.y), P.copy(x[ee]).add(C).add(S), Le(P.x, P.y, P.z)) : Le($.x, $.y, d / h * ee);
        }
      for (let ee = g - 1; ee >= 0; ee--) {
        const K = ee / g, $ = p * Math.cos(K * Math.PI / 2), j = m * Math.sin(K * Math.PI / 2) + _;
        for (let de = 0, ne = Z.length; de < ne; de++) {
          const ue = X(Z[de], he[de], j);
          Le(ue.x, ue.y, d + $);
        }
        for (let de = 0, ne = L.length; de < ne; de++) {
          const ue = L[de];
          Se = me[de];
          for (let Ve = 0, ze = ue.length; Ve < ze; Ve++) {
            const R = X(ue[Ve], Se[Ve], j);
            y ? Le(R.x, R.y + x[h - 1].y, x[h - 1].x + $) : Le(R.x, R.y, d + $);
          }
        }
      }
      Y(), te();
      function Y() {
        const ee = n.length / 3;
        if (u) {
          let K = 0, $ = ie * K;
          for (let j = 0; j < ht; j++) {
            const de = Qe[j];
            Ee(de[2] + $, de[1] + $, de[0] + $);
          }
          K = h + g * 2, $ = ie * K;
          for (let j = 0; j < ht; j++) {
            const de = Qe[j];
            Ee(de[0] + $, de[1] + $, de[2] + $);
          }
        } else {
          for (let K = 0; K < ht; K++) {
            const $ = Qe[K];
            Ee($[2], $[1], $[0]);
          }
          for (let K = 0; K < ht; K++) {
            const $ = Qe[K];
            Ee($[0] + ie * h, $[1] + ie * h, $[2] + ie * h);
          }
        }
        i.addGroup(ee, n.length / 3 - ee, 0);
      }
      function te() {
        const ee = n.length / 3;
        let K = 0;
        be(Z, K), K += Z.length;
        for (let $ = 0, j = L.length; $ < j; $++) {
          const de = L[$];
          be(de, K), K += de.length;
        }
        i.addGroup(ee, n.length / 3 - ee, 1);
      }
      function be(ee, K) {
        let $ = ee.length;
        for (; --$ >= 0; ) {
          const j = $;
          let de = $ - 1;
          de < 0 && (de = ee.length - 1);
          for (let ne = 0, ue = h + g * 2; ne < ue; ne++) {
            const Ve = ie * ne, ze = ie * (ne + 1), R = K + j + Ve, M = K + de + Ve, F = K + de + ze, V = K + j + ze;
            $e(R, M, F, V);
          }
        }
      }
      function Le(ee, K, $) {
        l.push(ee), l.push(K), l.push($);
      }
      function Ee(ee, K, $) {
        yt(ee), yt(K), yt($);
        const j = n.length / 3, de = v.generateTopUV(i, n, j - 3, j - 2, j - 1);
        I(de[0]), I(de[1]), I(de[2]);
      }
      function $e(ee, K, $, j) {
        yt(ee), yt(K), yt(j), yt(K), yt($), yt(j);
        const de = n.length / 3, ne = v.generateSideWallUV(i, n, de - 6, de - 3, de - 2, de - 1);
        I(ne[0]), I(ne[1]), I(ne[3]), I(ne[1]), I(ne[2]), I(ne[3]);
      }
      function yt(ee) {
        n.push(l[ee * 3 + 0]), n.push(l[ee * 3 + 1]), n.push(l[ee * 3 + 2]);
      }
      function I(ee) {
        s.push(ee.x), s.push(ee.y);
      }
    }
  }
  copy(e) {
    return super.copy(e), this.parameters = Object.assign({}, e.parameters), this;
  }
  toJSON() {
    const e = super.toJSON(), t = this.parameters.shapes, i = this.parameters.options;
    return Ky(t, i, e);
  }
  /**
   * Factory method for creating an instance of this class from the given
   * JSON object.
   *
   * @param {Object} data - A JSON object representing the serialized geometry.
   * @param {Array<Shape>} shapes - An array of shapes.
   * @return {ExtrudeGeometry} A new instance.
   */
  static fromJSON(e, t) {
    const i = [];
    for (let s = 0, a = e.shapes.length; s < a; s++) {
      const o = t[e.shapes[s]];
      i.push(o);
    }
    const n = e.options.extrudePath;
    return n !== void 0 && (e.options.extrudePath = new Il[n.type]().fromJSON(n)), new wa(i, e.options);
  }
}
const $y = {
  generateTopUV: function(r, e, t, i, n) {
    const s = e[t * 3], a = e[t * 3 + 1], o = e[i * 3], l = e[i * 3 + 1], c = e[n * 3], h = e[n * 3 + 1];
    return [
      new H(s, a),
      new H(o, l),
      new H(c, h)
    ];
  },
  generateSideWallUV: function(r, e, t, i, n, s) {
    const a = e[t * 3], o = e[t * 3 + 1], l = e[t * 3 + 2], c = e[i * 3], h = e[i * 3 + 1], d = e[i * 3 + 2], u = e[n * 3], p = e[n * 3 + 1], m = e[n * 3 + 2], _ = e[s * 3], g = e[s * 3 + 1], f = e[s * 3 + 2];
    return Math.abs(o - h) < Math.abs(a - c) ? [
      new H(a, 1 - l),
      new H(c, 1 - d),
      new H(u, 1 - m),
      new H(_, 1 - f)
    ] : [
      new H(o, 1 - l),
      new H(h, 1 - d),
      new H(p, 1 - m),
      new H(g, 1 - f)
    ];
  }
};
function Ky(r, e, t) {
  if (t.shapes = [], Array.isArray(r))
    for (let i = 0, n = r.length; i < n; i++) {
      const s = r[i];
      t.shapes.push(s.uuid);
    }
  else
    t.shapes.push(r.uuid);
  return t.options = Object.assign({}, e), e.extrudePath !== void 0 && (t.options.extrudePath = e.extrudePath.toJSON()), t;
}
class oc extends Hn {
  /**
   * Constructs a new icosahedron geometry.
   *
   * @param {number} [radius=1] - Radius of the icosahedron.
   * @param {number} [detail=0] - Setting this to a value greater than `0` adds vertices making it no longer a icosahedron.
   */
  constructor(e = 1, t = 0) {
    const i = (1 + Math.sqrt(5)) / 2, n = [
      -1,
      i,
      0,
      1,
      i,
      0,
      -1,
      -i,
      0,
      1,
      -i,
      0,
      0,
      -1,
      i,
      0,
      1,
      i,
      0,
      -1,
      -i,
      0,
      1,
      -i,
      i,
      0,
      -1,
      i,
      0,
      1,
      -i,
      0,
      -1,
      -i,
      0,
      1
    ], s = [
      0,
      11,
      5,
      0,
      5,
      1,
      0,
      1,
      7,
      0,
      7,
      10,
      0,
      10,
      11,
      1,
      5,
      9,
      5,
      11,
      4,
      11,
      10,
      2,
      10,
      7,
      6,
      7,
      1,
      8,
      3,
      9,
      4,
      3,
      4,
      2,
      3,
      2,
      6,
      3,
      6,
      8,
      3,
      8,
      9,
      4,
      9,
      5,
      2,
      4,
      11,
      6,
      2,
      10,
      8,
      6,
      7,
      9,
      8,
      1
    ];
    super(n, s, e, t), this.type = "IcosahedronGeometry", this.parameters = {
      radius: e,
      detail: t
    };
  }
  /**
   * Factory method for creating an instance of this class from the given
   * JSON object.
   *
   * @param {Object} data - A JSON object representing the serialized geometry.
   * @return {IcosahedronGeometry} A new instance.
   */
  static fromJSON(e) {
    return new oc(e.radius, e.detail);
  }
}
class lc extends Ue {
  /**
   * Constructs a new lathe geometry.
   *
   * @param {Array<Vector2|Vector3>} [points] - An array of points in 2D space. The x-coordinate of each point
   * must be greater than zero.
   * @param {number} [segments=12] - The number of circumference segments to generate.
   * @param {number} [phiStart=0] - The starting angle in radians.
   * @param {number} [phiLength=Math.PI*2] - The radian (0 to 2PI) range of the lathed section 2PI is a
   * closed lathe, less than 2PI is a portion.
   */
  constructor(e = [new H(0, -0.5), new H(0.5, 0), new H(0, 0.5)], t = 12, i = 0, n = Math.PI * 2) {
    super(), this.type = "LatheGeometry", this.parameters = {
      points: e,
      segments: t,
      phiStart: i,
      phiLength: n
    }, t = Math.floor(t), n = Fe(n, 0, Math.PI * 2);
    const s = [], a = [], o = [], l = [], c = [], h = 1 / t, d = new b(), u = new H(), p = new b(), m = new b(), _ = new b();
    let g = 0, f = 0;
    for (let v = 0; v <= e.length - 1; v++)
      switch (v) {
        case 0:
          g = e[v + 1].x - e[v].x, f = e[v + 1].y - e[v].y, p.x = f * 1, p.y = -g, p.z = f * 0, _.copy(p), p.normalize(), l.push(p.x, p.y, p.z);
          break;
        case e.length - 1:
          l.push(_.x, _.y, _.z);
          break;
        default:
          g = e[v + 1].x - e[v].x, f = e[v + 1].y - e[v].y, p.x = f * 1, p.y = -g, p.z = f * 0, m.copy(p), p.x += _.x, p.y += _.y, p.z += _.z, p.normalize(), l.push(p.x, p.y, p.z), _.copy(m);
      }
    for (let v = 0; v <= t; v++) {
      const x = i + v * h * n, y = Math.sin(x), A = Math.cos(x);
      for (let S = 0; S <= e.length - 1; S++) {
        d.x = e[S].x * y, d.y = e[S].y, d.z = e[S].x * A, a.push(d.x, d.y, d.z), u.x = v / t, u.y = S / (e.length - 1), o.push(u.x, u.y);
        const C = l[3 * S + 0] * y, P = l[3 * S + 1], E = l[3 * S + 0] * A;
        c.push(C, P, E);
      }
    }
    for (let v = 0; v < t; v++)
      for (let x = 0; x < e.length - 1; x++) {
        const y = x + v * e.length, A = y, S = y + e.length, C = y + e.length + 1, P = y + 1;
        s.push(A, S, P), s.push(C, P, S);
      }
    this.setIndex(s), this.setAttribute("position", new ve(a, 3)), this.setAttribute("uv", new ve(o, 2)), this.setAttribute("normal", new ve(c, 3));
  }
  copy(e) {
    return super.copy(e), this.parameters = Object.assign({}, e.parameters), this;
  }
  /**
   * Factory method for creating an instance of this class from the given
   * JSON object.
   *
   * @param {Object} data - A JSON object representing the serialized geometry.
   * @return {LatheGeometry} A new instance.
   */
  static fromJSON(e) {
    return new lc(e.points, e.segments, e.phiStart, e.phiLength);
  }
}
class Ea extends Hn {
  /**
   * Constructs a new octahedron geometry.
   *
   * @param {number} [radius=1] - Radius of the octahedron.
   * @param {number} [detail=0] - Setting this to a value greater than `0` adds vertices making it no longer a octahedron.
   */
  constructor(e = 1, t = 0) {
    const i = [
      1,
      0,
      0,
      -1,
      0,
      0,
      0,
      1,
      0,
      0,
      -1,
      0,
      0,
      0,
      1,
      0,
      0,
      -1
    ], n = [
      0,
      2,
      4,
      0,
      4,
      3,
      0,
      3,
      5,
      0,
      5,
      2,
      1,
      2,
      5,
      1,
      5,
      3,
      1,
      3,
      4,
      1,
      4,
      2
    ];
    super(i, n, e, t), this.type = "OctahedronGeometry", this.parameters = {
      radius: e,
      detail: t
    };
  }
  /**
   * Factory method for creating an instance of this class from the given
   * JSON object.
   *
   * @param {Object} data - A JSON object representing the serialized geometry.
   * @return {OctahedronGeometry} A new instance.
   */
  static fromJSON(e) {
    return new Ea(e.radius, e.detail);
  }
}
class Vn extends Ue {
  /**
   * Constructs a new plane geometry.
   *
   * @param {number} [width=1] - The width along the X axis.
   * @param {number} [height=1] - The height along the Y axis
   * @param {number} [widthSegments=1] - The number of segments along the X axis.
   * @param {number} [heightSegments=1] - The number of segments along the Y axis.
   */
  constructor(e = 1, t = 1, i = 1, n = 1) {
    super(), this.type = "PlaneGeometry", this.parameters = {
      width: e,
      height: t,
      widthSegments: i,
      heightSegments: n
    };
    const s = e / 2, a = t / 2, o = Math.floor(i), l = Math.floor(n), c = o + 1, h = l + 1, d = e / o, u = t / l, p = [], m = [], _ = [], g = [];
    for (let f = 0; f < h; f++) {
      const v = f * u - a;
      for (let x = 0; x < c; x++) {
        const y = x * d - s;
        m.push(y, -v, 0), _.push(0, 0, 1), g.push(x / o), g.push(1 - f / l);
      }
    }
    for (let f = 0; f < l; f++)
      for (let v = 0; v < o; v++) {
        const x = v + c * f, y = v + c * (f + 1), A = v + 1 + c * (f + 1), S = v + 1 + c * f;
        p.push(x, y, S), p.push(y, A, S);
      }
    this.setIndex(p), this.setAttribute("position", new ve(m, 3)), this.setAttribute("normal", new ve(_, 3)), this.setAttribute("uv", new ve(g, 2));
  }
  copy(e) {
    return super.copy(e), this.parameters = Object.assign({}, e.parameters), this;
  }
  /**
   * Factory method for creating an instance of this class from the given
   * JSON object.
   *
   * @param {Object} data - A JSON object representing the serialized geometry.
   * @return {PlaneGeometry} A new instance.
   */
  static fromJSON(e) {
    return new Vn(e.width, e.height, e.widthSegments, e.heightSegments);
  }
}
class cc extends Ue {
  /**
   * Constructs a new ring geometry.
   *
   * @param {number} [innerRadius=0.5] - The inner radius of the ring.
   * @param {number} [outerRadius=1] - The outer radius of the ring.
   * @param {number} [thetaSegments=32] - Number of segments. A higher number means the ring will be more round. Minimum is `3`.
   * @param {number} [phiSegments=1] - Number of segments per ring segment. Minimum is `1`.
   * @param {number} [thetaStart=0] - Starting angle in radians.
   * @param {number} [thetaLength=Math.PI*2] - Central angle in radians.
   */
  constructor(e = 0.5, t = 1, i = 32, n = 1, s = 0, a = Math.PI * 2) {
    super(), this.type = "RingGeometry", this.parameters = {
      innerRadius: e,
      outerRadius: t,
      thetaSegments: i,
      phiSegments: n,
      thetaStart: s,
      thetaLength: a
    }, i = Math.max(3, i), n = Math.max(1, n);
    const o = [], l = [], c = [], h = [];
    let d = e;
    const u = (t - e) / n, p = new b(), m = new H();
    for (let _ = 0; _ <= n; _++) {
      for (let g = 0; g <= i; g++) {
        const f = s + g / i * a;
        p.x = d * Math.cos(f), p.y = d * Math.sin(f), l.push(p.x, p.y, p.z), c.push(0, 0, 1), m.x = (p.x / t + 1) / 2, m.y = (p.y / t + 1) / 2, h.push(m.x, m.y);
      }
      d += u;
    }
    for (let _ = 0; _ < n; _++) {
      const g = _ * (i + 1);
      for (let f = 0; f < i; f++) {
        const v = f + g, x = v, y = v + i + 1, A = v + i + 2, S = v + 1;
        o.push(x, y, S), o.push(y, A, S);
      }
    }
    this.setIndex(o), this.setAttribute("position", new ve(l, 3)), this.setAttribute("normal", new ve(c, 3)), this.setAttribute("uv", new ve(h, 2));
  }
  copy(e) {
    return super.copy(e), this.parameters = Object.assign({}, e.parameters), this;
  }
  /**
   * Factory method for creating an instance of this class from the given
   * JSON object.
   *
   * @param {Object} data - A JSON object representing the serialized geometry.
   * @return {RingGeometry} A new instance.
   */
  static fromJSON(e) {
    return new cc(e.innerRadius, e.outerRadius, e.thetaSegments, e.phiSegments, e.thetaStart, e.thetaLength);
  }
}
class Ta extends Ue {
  /**
   * Constructs a new shape geometry.
   *
   * @param {Shape|Array<Shape>} [shapes] - A shape or an array of shapes.
   * @param {number} [curveSegments=12] - Number of segments per shape.
   */
  constructor(e = new Nn([new H(0, 0.5), new H(-0.5, -0.5), new H(0.5, -0.5)]), t = 12) {
    super(), this.type = "ShapeGeometry", this.parameters = {
      shapes: e,
      curveSegments: t
    };
    const i = [], n = [], s = [], a = [];
    let o = 0, l = 0;
    if (Array.isArray(e) === !1)
      c(e);
    else
      for (let h = 0; h < e.length; h++)
        c(e[h]), this.addGroup(o, l, h), o += l, l = 0;
    this.setIndex(i), this.setAttribute("position", new ve(n, 3)), this.setAttribute("normal", new ve(s, 3)), this.setAttribute("uv", new ve(a, 2));
    function c(h) {
      const d = n.length / 3, u = h.extractPoints(t);
      let p = u.shape;
      const m = u.holes;
      zi.isClockWise(p) === !1 && (p = p.reverse());
      for (let g = 0, f = m.length; g < f; g++) {
        const v = m[g];
        zi.isClockWise(v) === !0 && (m[g] = v.reverse());
      }
      const _ = zi.triangulateShape(p, m);
      for (let g = 0, f = m.length; g < f; g++) {
        const v = m[g];
        p = p.concat(v);
      }
      for (let g = 0, f = p.length; g < f; g++) {
        const v = p[g];
        n.push(v.x, v.y, 0), s.push(0, 0, 1), a.push(v.x, v.y);
      }
      for (let g = 0, f = _.length; g < f; g++) {
        const v = _[g], x = v[0] + d, y = v[1] + d, A = v[2] + d;
        i.push(x, y, A), l += 3;
      }
    }
  }
  copy(e) {
    return super.copy(e), this.parameters = Object.assign({}, e.parameters), this;
  }
  toJSON() {
    const e = super.toJSON(), t = this.parameters.shapes;
    return Jy(t, e);
  }
  /**
   * Factory method for creating an instance of this class from the given
   * JSON object.
   *
   * @param {Object} data - A JSON object representing the serialized geometry.
   * @param {Array<Shape>} shapes - An array of shapes.
   * @return {ShapeGeometry} A new instance.
   */
  static fromJSON(e, t) {
    const i = [];
    for (let n = 0, s = e.shapes.length; n < s; n++) {
      const a = t[e.shapes[n]];
      i.push(a);
    }
    return new Ta(i, e.curveSegments);
  }
}
function Jy(r, e) {
  if (e.shapes = [], Array.isArray(r))
    for (let t = 0, i = r.length; t < i; t++) {
      const n = r[t];
      e.shapes.push(n.uuid);
    }
  else
    e.shapes.push(r.uuid);
  return e;
}
class Ts extends Ue {
  /**
   * Constructs a new sphere geometry.
   *
   * @param {number} [radius=1] - The sphere radius.
   * @param {number} [widthSegments=32] - The number of horizontal segments. Minimum value is `3`.
   * @param {number} [heightSegments=16] - The number of vertical segments. Minimum value is `2`.
   * @param {number} [phiStart=0] - The horizontal starting angle in radians.
   * @param {number} [phiLength=Math.PI*2] - The horizontal sweep angle size.
   * @param {number} [thetaStart=0] - The vertical starting angle in radians.
   * @param {number} [thetaLength=Math.PI] - The vertical sweep angle size.
   */
  constructor(e = 1, t = 32, i = 16, n = 0, s = Math.PI * 2, a = 0, o = Math.PI) {
    super(), this.type = "SphereGeometry", this.parameters = {
      radius: e,
      widthSegments: t,
      heightSegments: i,
      phiStart: n,
      phiLength: s,
      thetaStart: a,
      thetaLength: o
    }, t = Math.max(3, Math.floor(t)), i = Math.max(2, Math.floor(i));
    const l = Math.min(a + o, Math.PI);
    let c = 0;
    const h = [], d = new b(), u = new b(), p = [], m = [], _ = [], g = [];
    for (let f = 0; f <= i; f++) {
      const v = [], x = f / i;
      let y = 0;
      f === 0 && a === 0 ? y = 0.5 / t : f === i && l === Math.PI && (y = -0.5 / t);
      for (let A = 0; A <= t; A++) {
        const S = A / t;
        d.x = -e * Math.cos(n + S * s) * Math.sin(a + x * o), d.y = e * Math.cos(a + x * o), d.z = e * Math.sin(n + S * s) * Math.sin(a + x * o), m.push(d.x, d.y, d.z), u.copy(d).normalize(), _.push(u.x, u.y, u.z), g.push(S + y, 1 - x), v.push(c++);
      }
      h.push(v);
    }
    for (let f = 0; f < i; f++)
      for (let v = 0; v < t; v++) {
        const x = h[f][v + 1], y = h[f][v], A = h[f + 1][v], S = h[f + 1][v + 1];
        (f !== 0 || a > 0) && p.push(x, y, S), (f !== i - 1 || l < Math.PI) && p.push(y, A, S);
      }
    this.setIndex(p), this.setAttribute("position", new ve(m, 3)), this.setAttribute("normal", new ve(_, 3)), this.setAttribute("uv", new ve(g, 2));
  }
  copy(e) {
    return super.copy(e), this.parameters = Object.assign({}, e.parameters), this;
  }
  /**
   * Factory method for creating an instance of this class from the given
   * JSON object.
   *
   * @param {Object} data - A JSON object representing the serialized geometry.
   * @return {SphereGeometry} A new instance.
   */
  static fromJSON(e) {
    return new Ts(e.radius, e.widthSegments, e.heightSegments, e.phiStart, e.phiLength, e.thetaStart, e.thetaLength);
  }
}
class hc extends Hn {
  /**
   * Constructs a new tetrahedron geometry.
   *
   * @param {number} [radius=1] - Radius of the tetrahedron.
   * @param {number} [detail=0] - Setting this to a value greater than `0` adds vertices making it no longer a tetrahedron.
   */
  constructor(e = 1, t = 0) {
    const i = [
      1,
      1,
      1,
      -1,
      -1,
      1,
      -1,
      1,
      -1,
      1,
      -1,
      -1
    ], n = [
      2,
      1,
      0,
      0,
      3,
      2,
      1,
      3,
      0,
      2,
      3,
      1
    ];
    super(i, n, e, t), this.type = "TetrahedronGeometry", this.parameters = {
      radius: e,
      detail: t
    };
  }
  /**
   * Factory method for creating an instance of this class from the given
   * JSON object.
   *
   * @param {Object} data - A JSON object representing the serialized geometry.
   * @return {TetrahedronGeometry} A new instance.
   */
  static fromJSON(e) {
    return new hc(e.radius, e.detail);
  }
}
class dc extends Ue {
  /**
   * Constructs a new torus geometry.
   *
   * @param {number} [radius=1] - Radius of the torus, from the center of the torus to the center of the tube.
   * @param {number} [tube=0.4] - Radius of the tube. Must be smaller than `radius`.
   * @param {number} [radialSegments=12] - The number of radial segments.
   * @param {number} [tubularSegments=48] - The number of tubular segments.
   * @param {number} [arc=Math.PI*2] - Central angle in radians.
   */
  constructor(e = 1, t = 0.4, i = 12, n = 48, s = Math.PI * 2) {
    super(), this.type = "TorusGeometry", this.parameters = {
      radius: e,
      tube: t,
      radialSegments: i,
      tubularSegments: n,
      arc: s
    }, i = Math.floor(i), n = Math.floor(n);
    const a = [], o = [], l = [], c = [], h = new b(), d = new b(), u = new b();
    for (let p = 0; p <= i; p++)
      for (let m = 0; m <= n; m++) {
        const _ = m / n * s, g = p / i * Math.PI * 2;
        d.x = (e + t * Math.cos(g)) * Math.cos(_), d.y = (e + t * Math.cos(g)) * Math.sin(_), d.z = t * Math.sin(g), o.push(d.x, d.y, d.z), h.x = e * Math.cos(_), h.y = e * Math.sin(_), u.subVectors(d, h).normalize(), l.push(u.x, u.y, u.z), c.push(m / n), c.push(p / i);
      }
    for (let p = 1; p <= i; p++)
      for (let m = 1; m <= n; m++) {
        const _ = (n + 1) * p + m - 1, g = (n + 1) * (p - 1) + m - 1, f = (n + 1) * (p - 1) + m, v = (n + 1) * p + m;
        a.push(_, g, v), a.push(g, f, v);
      }
    this.setIndex(a), this.setAttribute("position", new ve(o, 3)), this.setAttribute("normal", new ve(l, 3)), this.setAttribute("uv", new ve(c, 2));
  }
  copy(e) {
    return super.copy(e), this.parameters = Object.assign({}, e.parameters), this;
  }
  /**
   * Factory method for creating an instance of this class from the given
   * JSON object.
   *
   * @param {Object} data - A JSON object representing the serialized geometry.
   * @return {TorusGeometry} A new instance.
   */
  static fromJSON(e) {
    return new dc(e.radius, e.tube, e.radialSegments, e.tubularSegments, e.arc);
  }
}
class uc extends Ue {
  /**
   * Constructs a new torus knot geometry.
   *
   * @param {number} [radius=1] - Radius of the torus knot.
   * @param {number} [tube=0.4] - Radius of the tube.
   * @param {number} [tubularSegments=64] - The number of tubular segments.
   * @param {number} [radialSegments=8] - The number of radial segments.
   * @param {number} [p=2] - This value determines, how many times the geometry winds around its axis of rotational symmetry.
   * @param {number} [q=3] - This value determines, how many times the geometry winds around a circle in the interior of the torus.
   */
  constructor(e = 1, t = 0.4, i = 64, n = 8, s = 2, a = 3) {
    super(), this.type = "TorusKnotGeometry", this.parameters = {
      radius: e,
      tube: t,
      tubularSegments: i,
      radialSegments: n,
      p: s,
      q: a
    }, i = Math.floor(i), n = Math.floor(n);
    const o = [], l = [], c = [], h = [], d = new b(), u = new b(), p = new b(), m = new b(), _ = new b(), g = new b(), f = new b();
    for (let x = 0; x <= i; ++x) {
      const y = x / i * s * Math.PI * 2;
      v(y, s, a, e, p), v(y + 0.01, s, a, e, m), g.subVectors(m, p), f.addVectors(m, p), _.crossVectors(g, f), f.crossVectors(_, g), _.normalize(), f.normalize();
      for (let A = 0; A <= n; ++A) {
        const S = A / n * Math.PI * 2, C = -t * Math.cos(S), P = t * Math.sin(S);
        d.x = p.x + (C * f.x + P * _.x), d.y = p.y + (C * f.y + P * _.y), d.z = p.z + (C * f.z + P * _.z), l.push(d.x, d.y, d.z), u.subVectors(d, p).normalize(), c.push(u.x, u.y, u.z), h.push(x / i), h.push(A / n);
      }
    }
    for (let x = 1; x <= i; x++)
      for (let y = 1; y <= n; y++) {
        const A = (n + 1) * (x - 1) + (y - 1), S = (n + 1) * x + (y - 1), C = (n + 1) * x + y, P = (n + 1) * (x - 1) + y;
        o.push(A, S, P), o.push(S, C, P);
      }
    this.setIndex(o), this.setAttribute("position", new ve(l, 3)), this.setAttribute("normal", new ve(c, 3)), this.setAttribute("uv", new ve(h, 2));
    function v(x, y, A, S, C) {
      const P = Math.cos(x), E = Math.sin(x), w = A / y * x, L = Math.cos(w);
      C.x = S * (2 + L) * 0.5 * P, C.y = S * (2 + L) * E * 0.5, C.z = S * Math.sin(w) * 0.5;
    }
  }
  copy(e) {
    return super.copy(e), this.parameters = Object.assign({}, e.parameters), this;
  }
  /**
   * Factory method for creating an instance of this class from the given
   * JSON object.
   *
   * @param {Object} data - A JSON object representing the serialized geometry.
   * @return {TorusKnotGeometry} A new instance.
   */
  static fromJSON(e) {
    return new uc(e.radius, e.tube, e.tubularSegments, e.radialSegments, e.p, e.q);
  }
}
class pc extends Ue {
  /**
   * Constructs a new tube geometry.
   *
   * @param {Curve} [path=QuadraticBezierCurve3] - A 3D curve defining the path of the tube.
   * @param {number} [tubularSegments=64] - The number of segments that make up the tube.
   * @param {number} [radius=1] -The radius of the tube.
   * @param {number} [radialSegments=8] - The number of segments that make up the cross-section.
   * @param {boolean} [closed=false] - Whether the tube is closed or not.
   */
  constructor(e = new bd(new b(-1, -1, 0), new b(-1, 1, 0), new b(1, 1, 0)), t = 64, i = 1, n = 8, s = !1) {
    super(), this.type = "TubeGeometry", this.parameters = {
      path: e,
      tubularSegments: t,
      radius: i,
      radialSegments: n,
      closed: s
    };
    const a = e.computeFrenetFrames(t, s);
    this.tangents = a.tangents, this.normals = a.normals, this.binormals = a.binormals;
    const o = new b(), l = new b(), c = new H();
    let h = new b();
    const d = [], u = [], p = [], m = [];
    _(), this.setIndex(m), this.setAttribute("position", new ve(d, 3)), this.setAttribute("normal", new ve(u, 3)), this.setAttribute("uv", new ve(p, 2));
    function _() {
      for (let x = 0; x < t; x++)
        g(x);
      g(s === !1 ? t : 0), v(), f();
    }
    function g(x) {
      h = e.getPointAt(x / t, h);
      const y = a.normals[x], A = a.binormals[x];
      for (let S = 0; S <= n; S++) {
        const C = S / n * Math.PI * 2, P = Math.sin(C), E = -Math.cos(C);
        l.x = E * y.x + P * A.x, l.y = E * y.y + P * A.y, l.z = E * y.z + P * A.z, l.normalize(), u.push(l.x, l.y, l.z), o.x = h.x + i * l.x, o.y = h.y + i * l.y, o.z = h.z + i * l.z, d.push(o.x, o.y, o.z);
      }
    }
    function f() {
      for (let x = 1; x <= t; x++)
        for (let y = 1; y <= n; y++) {
          const A = (n + 1) * (x - 1) + (y - 1), S = (n + 1) * x + (y - 1), C = (n + 1) * x + y, P = (n + 1) * (x - 1) + y;
          m.push(A, S, P), m.push(S, C, P);
        }
    }
    function v() {
      for (let x = 0; x <= t; x++)
        for (let y = 0; y <= n; y++)
          c.x = x / t, c.y = y / n, p.push(c.x, c.y);
    }
  }
  copy(e) {
    return super.copy(e), this.parameters = Object.assign({}, e.parameters), this;
  }
  toJSON() {
    const e = super.toJSON();
    return e.path = this.parameters.path.toJSON(), e;
  }
  /**
   * Factory method for creating an instance of this class from the given
   * JSON object.
   *
   * @param {Object} data - A JSON object representing the serialized geometry.
   * @return {TubeGeometry} A new instance.
   */
  static fromJSON(e) {
    return new pc(
      new Il[e.path.type]().fromJSON(e.path),
      e.tubularSegments,
      e.radius,
      e.radialSegments,
      e.closed
    );
  }
}
class Md extends Ue {
  /**
   * Constructs a new wireframe geometry.
   *
   * @param {?BufferGeometry} [geometry=null] - The geometry.
   */
  constructor(e = null) {
    if (super(), this.type = "WireframeGeometry", this.parameters = {
      geometry: e
    }, e !== null) {
      const t = [], i = /* @__PURE__ */ new Set(), n = new b(), s = new b();
      if (e.index !== null) {
        const a = e.attributes.position, o = e.index;
        let l = e.groups;
        l.length === 0 && (l = [{ start: 0, count: o.count, materialIndex: 0 }]);
        for (let c = 0, h = l.length; c < h; ++c) {
          const d = l[c], u = d.start, p = d.count;
          for (let m = u, _ = u + p; m < _; m += 3)
            for (let g = 0; g < 3; g++) {
              const f = o.getX(m + g), v = o.getX(m + (g + 1) % 3);
              n.fromBufferAttribute(a, f), s.fromBufferAttribute(a, v), Vu(n, s, i) === !0 && (t.push(n.x, n.y, n.z), t.push(s.x, s.y, s.z));
            }
        }
      } else {
        const a = e.attributes.position;
        for (let o = 0, l = a.count / 3; o < l; o++)
          for (let c = 0; c < 3; c++) {
            const h = 3 * o + c, d = 3 * o + (c + 1) % 3;
            n.fromBufferAttribute(a, h), s.fromBufferAttribute(a, d), Vu(n, s, i) === !0 && (t.push(n.x, n.y, n.z), t.push(s.x, s.y, s.z));
          }
      }
      this.setAttribute("position", new ve(t, 3));
    }
  }
  copy(e) {
    return super.copy(e), this.parameters = Object.assign({}, e.parameters), this;
  }
}
function Vu(r, e, t) {
  const i = `${r.x},${r.y},${r.z}-${e.x},${e.y},${e.z}`, n = `${e.x},${e.y},${e.z}-${r.x},${r.y},${r.z}`;
  return t.has(i) === !0 || t.has(n) === !0 ? !1 : (t.add(i), t.add(n), !0);
}
var Gu = /* @__PURE__ */ Object.freeze({
  __proto__: null,
  BoxGeometry: Es,
  CapsuleGeometry: nc,
  CircleGeometry: sc,
  ConeGeometry: wr,
  CylinderGeometry: Mr,
  DodecahedronGeometry: rc,
  EdgesGeometry: Sm,
  ExtrudeGeometry: wa,
  IcosahedronGeometry: oc,
  LatheGeometry: lc,
  OctahedronGeometry: Ea,
  PlaneGeometry: Vn,
  PolyhedronGeometry: Hn,
  RingGeometry: cc,
  ShapeGeometry: Ta,
  SphereGeometry: Ts,
  TetrahedronGeometry: hc,
  TorusGeometry: dc,
  TorusKnotGeometry: uc,
  TubeGeometry: pc,
  WireframeGeometry: Md
});
class Im extends qt {
  /**
   * Constructs a new shadow material.
   *
   * @param {Object} [parameters] - An object with one or more properties
   * defining the material's appearance. Any property of the material
   * (including any property from inherited materials) can be passed
   * in here. Color values can be passed any type of value accepted
   * by {@link Color#set}.
   */
  constructor(e) {
    super(), this.isShadowMaterial = !0, this.type = "ShadowMaterial", this.color = new oe(0), this.transparent = !0, this.fog = !0, this.setValues(e);
  }
  copy(e) {
    return super.copy(e), this.color.copy(e.color), this.fog = e.fog, this;
  }
}
class Dm extends Ci {
  /**
   * Constructs a new raw shader material.
   *
   * @param {Object} [parameters] - An object with one or more properties
   * defining the material's appearance. Any property of the material
   * (including any property from inherited materials) can be passed
   * in here. Color values can be passed any type of value accepted
   * by {@link Color#set}.
   */
  constructor(e) {
    super(e), this.isRawShaderMaterial = !0, this.type = "RawShaderMaterial";
  }
}
class Bn extends qt {
  /**
   * Constructs a new mesh standard material.
   *
   * @param {Object} [parameters] - An object with one or more properties
   * defining the material's appearance. Any property of the material
   * (including any property from inherited materials) can be passed
   * in here. Color values can be passed any type of value accepted
   * by {@link Color#set}.
   */
  constructor(e) {
    super(), this.isMeshStandardMaterial = !0, this.type = "MeshStandardMaterial", this.defines = { STANDARD: "" }, this.color = new oe(16777215), this.roughness = 1, this.metalness = 0, this.map = null, this.lightMap = null, this.lightMapIntensity = 1, this.aoMap = null, this.aoMapIntensity = 1, this.emissive = new oe(0), this.emissiveIntensity = 1, this.emissiveMap = null, this.bumpMap = null, this.bumpScale = 1, this.normalMap = null, this.normalMapType = zn, this.normalScale = new H(1, 1), this.displacementMap = null, this.displacementScale = 1, this.displacementBias = 0, this.roughnessMap = null, this.metalnessMap = null, this.alphaMap = null, this.envMap = null, this.envMapRotation = new Ai(), this.envMapIntensity = 1, this.wireframe = !1, this.wireframeLinewidth = 1, this.wireframeLinecap = "round", this.wireframeLinejoin = "round", this.flatShading = !1, this.fog = !0, this.setValues(e);
  }
  copy(e) {
    return super.copy(e), this.defines = { STANDARD: "" }, this.color.copy(e.color), this.roughness = e.roughness, this.metalness = e.metalness, this.map = e.map, this.lightMap = e.lightMap, this.lightMapIntensity = e.lightMapIntensity, this.aoMap = e.aoMap, this.aoMapIntensity = e.aoMapIntensity, this.emissive.copy(e.emissive), this.emissiveMap = e.emissiveMap, this.emissiveIntensity = e.emissiveIntensity, this.bumpMap = e.bumpMap, this.bumpScale = e.bumpScale, this.normalMap = e.normalMap, this.normalMapType = e.normalMapType, this.normalScale.copy(e.normalScale), this.displacementMap = e.displacementMap, this.displacementScale = e.displacementScale, this.displacementBias = e.displacementBias, this.roughnessMap = e.roughnessMap, this.metalnessMap = e.metalnessMap, this.alphaMap = e.alphaMap, this.envMap = e.envMap, this.envMapRotation.copy(e.envMapRotation), this.envMapIntensity = e.envMapIntensity, this.wireframe = e.wireframe, this.wireframeLinewidth = e.wireframeLinewidth, this.wireframeLinecap = e.wireframeLinecap, this.wireframeLinejoin = e.wireframeLinejoin, this.flatShading = e.flatShading, this.fog = e.fog, this;
  }
}
class Nm extends Bn {
  /**
   * Constructs a new mesh physical material.
   *
   * @param {Object} [parameters] - An object with one or more properties
   * defining the material's appearance. Any property of the material
   * (including any property from inherited materials) can be passed
   * in here. Color values can be passed any type of value accepted
   * by {@link Color#set}.
   */
  constructor(e) {
    super(), this.isMeshPhysicalMaterial = !0, this.defines = {
      STANDARD: "",
      PHYSICAL: ""
    }, this.type = "MeshPhysicalMaterial", this.anisotropyRotation = 0, this.anisotropyMap = null, this.clearcoatMap = null, this.clearcoatRoughness = 0, this.clearcoatRoughnessMap = null, this.clearcoatNormalScale = new H(1, 1), this.clearcoatNormalMap = null, this.ior = 1.5, Object.defineProperty(this, "reflectivity", {
      get: function() {
        return Fe(2.5 * (this.ior - 1) / (this.ior + 1), 0, 1);
      },
      set: function(t) {
        this.ior = (1 + 0.4 * t) / (1 - 0.4 * t);
      }
    }), this.iridescenceMap = null, this.iridescenceIOR = 1.3, this.iridescenceThicknessRange = [100, 400], this.iridescenceThicknessMap = null, this.sheenColor = new oe(0), this.sheenColorMap = null, this.sheenRoughness = 1, this.sheenRoughnessMap = null, this.transmissionMap = null, this.thickness = 0, this.thicknessMap = null, this.attenuationDistance = 1 / 0, this.attenuationColor = new oe(1, 1, 1), this.specularIntensity = 1, this.specularIntensityMap = null, this.specularColor = new oe(1, 1, 1), this.specularColorMap = null, this._anisotropy = 0, this._clearcoat = 0, this._dispersion = 0, this._iridescence = 0, this._sheen = 0, this._transmission = 0, this.setValues(e);
  }
  /**
   * The anisotropy strength.
   *
   * @type {number}
   * @default 0
   */
  get anisotropy() {
    return this._anisotropy;
  }
  set anisotropy(e) {
    this._anisotropy > 0 != e > 0 && this.version++, this._anisotropy = e;
  }
  /**
   * Represents the intensity of the clear coat layer, from `0.0` to `1.0`. Use
   * clear coat related properties to enable multilayer materials that have a
   * thin translucent layer over the base layer.
   *
   * @type {number}
   * @default 0
   */
  get clearcoat() {
    return this._clearcoat;
  }
  set clearcoat(e) {
    this._clearcoat > 0 != e > 0 && this.version++, this._clearcoat = e;
  }
  /**
   * The intensity of the iridescence layer, simulating RGB color shift based on the angle between
   * the surface and the viewer, from `0.0` to `1.0`.
   *
   * @type {number}
   * @default 0
   */
  get iridescence() {
    return this._iridescence;
  }
  set iridescence(e) {
    this._iridescence > 0 != e > 0 && this.version++, this._iridescence = e;
  }
  /**
   * Defines the strength of the angular separation of colors (chromatic aberration) transmitting
   * through a relatively clear volume. Any value zero or larger is valid, the typical range of
   * realistic values is `[0, 1]`. This property can be only be used with transmissive objects.
   *
   * @type {number}
   * @default 0
   */
  get dispersion() {
    return this._dispersion;
  }
  set dispersion(e) {
    this._dispersion > 0 != e > 0 && this.version++, this._dispersion = e;
  }
  /**
   * The intensity of the sheen layer, from `0.0` to `1.0`.
   *
   * @type {number}
   * @default 0
   */
  get sheen() {
    return this._sheen;
  }
  set sheen(e) {
    this._sheen > 0 != e > 0 && this.version++, this._sheen = e;
  }
  /**
   * Degree of transmission (or optical transparency), from `0.0` to `1.0`.
   *
   * Thin, transparent or semitransparent, plastic or glass materials remain
   * largely reflective even if they are fully transmissive. The transmission
   * property can be used to model these materials.
   *
   * When transmission is non-zero, `opacity` should be  set to `1`.
   *
   * @type {number}
   * @default 0
   */
  get transmission() {
    return this._transmission;
  }
  set transmission(e) {
    this._transmission > 0 != e > 0 && this.version++, this._transmission = e;
  }
  copy(e) {
    return super.copy(e), this.defines = {
      STANDARD: "",
      PHYSICAL: ""
    }, this.anisotropy = e.anisotropy, this.anisotropyRotation = e.anisotropyRotation, this.anisotropyMap = e.anisotropyMap, this.clearcoat = e.clearcoat, this.clearcoatMap = e.clearcoatMap, this.clearcoatRoughness = e.clearcoatRoughness, this.clearcoatRoughnessMap = e.clearcoatRoughnessMap, this.clearcoatNormalMap = e.clearcoatNormalMap, this.clearcoatNormalScale.copy(e.clearcoatNormalScale), this.dispersion = e.dispersion, this.ior = e.ior, this.iridescence = e.iridescence, this.iridescenceMap = e.iridescenceMap, this.iridescenceIOR = e.iridescenceIOR, this.iridescenceThicknessRange = [...e.iridescenceThicknessRange], this.iridescenceThicknessMap = e.iridescenceThicknessMap, this.sheen = e.sheen, this.sheenColor.copy(e.sheenColor), this.sheenColorMap = e.sheenColorMap, this.sheenRoughness = e.sheenRoughness, this.sheenRoughnessMap = e.sheenRoughnessMap, this.transmission = e.transmission, this.transmissionMap = e.transmissionMap, this.thickness = e.thickness, this.thicknessMap = e.thicknessMap, this.attenuationDistance = e.attenuationDistance, this.attenuationColor.copy(e.attenuationColor), this.specularIntensity = e.specularIntensity, this.specularIntensityMap = e.specularIntensityMap, this.specularColor.copy(e.specularColor), this.specularColorMap = e.specularColorMap, this;
  }
}
class Um extends qt {
  /**
   * Constructs a new mesh phong material.
   *
   * @param {Object} [parameters] - An object with one or more properties
   * defining the material's appearance. Any property of the material
   * (including any property from inherited materials) can be passed
   * in here. Color values can be passed any type of value accepted
   * by {@link Color#set}.
   */
  constructor(e) {
    super(), this.isMeshPhongMaterial = !0, this.type = "MeshPhongMaterial", this.color = new oe(16777215), this.specular = new oe(1118481), this.shininess = 30, this.map = null, this.lightMap = null, this.lightMapIntensity = 1, this.aoMap = null, this.aoMapIntensity = 1, this.emissive = new oe(0), this.emissiveIntensity = 1, this.emissiveMap = null, this.bumpMap = null, this.bumpScale = 1, this.normalMap = null, this.normalMapType = zn, this.normalScale = new H(1, 1), this.displacementMap = null, this.displacementScale = 1, this.displacementBias = 0, this.specularMap = null, this.alphaMap = null, this.envMap = null, this.envMapRotation = new Ai(), this.combine = xa, this.reflectivity = 1, this.refractionRatio = 0.98, this.wireframe = !1, this.wireframeLinewidth = 1, this.wireframeLinecap = "round", this.wireframeLinejoin = "round", this.flatShading = !1, this.fog = !0, this.setValues(e);
  }
  copy(e) {
    return super.copy(e), this.color.copy(e.color), this.specular.copy(e.specular), this.shininess = e.shininess, this.map = e.map, this.lightMap = e.lightMap, this.lightMapIntensity = e.lightMapIntensity, this.aoMap = e.aoMap, this.aoMapIntensity = e.aoMapIntensity, this.emissive.copy(e.emissive), this.emissiveMap = e.emissiveMap, this.emissiveIntensity = e.emissiveIntensity, this.bumpMap = e.bumpMap, this.bumpScale = e.bumpScale, this.normalMap = e.normalMap, this.normalMapType = e.normalMapType, this.normalScale.copy(e.normalScale), this.displacementMap = e.displacementMap, this.displacementScale = e.displacementScale, this.displacementBias = e.displacementBias, this.specularMap = e.specularMap, this.alphaMap = e.alphaMap, this.envMap = e.envMap, this.envMapRotation.copy(e.envMapRotation), this.combine = e.combine, this.reflectivity = e.reflectivity, this.refractionRatio = e.refractionRatio, this.wireframe = e.wireframe, this.wireframeLinewidth = e.wireframeLinewidth, this.wireframeLinecap = e.wireframeLinecap, this.wireframeLinejoin = e.wireframeLinejoin, this.flatShading = e.flatShading, this.fog = e.fog, this;
  }
}
class Om extends qt {
  /**
   * Constructs a new mesh toon material.
   *
   * @param {Object} [parameters] - An object with one or more properties
   * defining the material's appearance. Any property of the material
   * (including any property from inherited materials) can be passed
   * in here. Color values can be passed any type of value accepted
   * by {@link Color#set}.
   */
  constructor(e) {
    super(), this.isMeshToonMaterial = !0, this.defines = { TOON: "" }, this.type = "MeshToonMaterial", this.color = new oe(16777215), this.map = null, this.gradientMap = null, this.lightMap = null, this.lightMapIntensity = 1, this.aoMap = null, this.aoMapIntensity = 1, this.emissive = new oe(0), this.emissiveIntensity = 1, this.emissiveMap = null, this.bumpMap = null, this.bumpScale = 1, this.normalMap = null, this.normalMapType = zn, this.normalScale = new H(1, 1), this.displacementMap = null, this.displacementScale = 1, this.displacementBias = 0, this.alphaMap = null, this.wireframe = !1, this.wireframeLinewidth = 1, this.wireframeLinecap = "round", this.wireframeLinejoin = "round", this.fog = !0, this.setValues(e);
  }
  copy(e) {
    return super.copy(e), this.color.copy(e.color), this.map = e.map, this.gradientMap = e.gradientMap, this.lightMap = e.lightMap, this.lightMapIntensity = e.lightMapIntensity, this.aoMap = e.aoMap, this.aoMapIntensity = e.aoMapIntensity, this.emissive.copy(e.emissive), this.emissiveMap = e.emissiveMap, this.emissiveIntensity = e.emissiveIntensity, this.bumpMap = e.bumpMap, this.bumpScale = e.bumpScale, this.normalMap = e.normalMap, this.normalMapType = e.normalMapType, this.normalScale.copy(e.normalScale), this.displacementMap = e.displacementMap, this.displacementScale = e.displacementScale, this.displacementBias = e.displacementBias, this.alphaMap = e.alphaMap, this.wireframe = e.wireframe, this.wireframeLinewidth = e.wireframeLinewidth, this.wireframeLinecap = e.wireframeLinecap, this.wireframeLinejoin = e.wireframeLinejoin, this.fog = e.fog, this;
  }
}
class Fm extends qt {
  /**
   * Constructs a new mesh normal material.
   *
   * @param {Object} [parameters] - An object with one or more properties
   * defining the material's appearance. Any property of the material
   * (including any property from inherited materials) can be passed
   * in here. Color values can be passed any type of value accepted
   * by {@link Color#set}.
   */
  constructor(e) {
    super(), this.isMeshNormalMaterial = !0, this.type = "MeshNormalMaterial", this.bumpMap = null, this.bumpScale = 1, this.normalMap = null, this.normalMapType = zn, this.normalScale = new H(1, 1), this.displacementMap = null, this.displacementScale = 1, this.displacementBias = 0, this.wireframe = !1, this.wireframeLinewidth = 1, this.flatShading = !1, this.setValues(e);
  }
  copy(e) {
    return super.copy(e), this.bumpMap = e.bumpMap, this.bumpScale = e.bumpScale, this.normalMap = e.normalMap, this.normalMapType = e.normalMapType, this.normalScale.copy(e.normalScale), this.displacementMap = e.displacementMap, this.displacementScale = e.displacementScale, this.displacementBias = e.displacementBias, this.wireframe = e.wireframe, this.wireframeLinewidth = e.wireframeLinewidth, this.flatShading = e.flatShading, this;
  }
}
class Bm extends qt {
  /**
   * Constructs a new mesh lambert material.
   *
   * @param {Object} [parameters] - An object with one or more properties
   * defining the material's appearance. Any property of the material
   * (including any property from inherited materials) can be passed
   * in here. Color values can be passed any type of value accepted
   * by {@link Color#set}.
   */
  constructor(e) {
    super(), this.isMeshLambertMaterial = !0, this.type = "MeshLambertMaterial", this.color = new oe(16777215), this.map = null, this.lightMap = null, this.lightMapIntensity = 1, this.aoMap = null, this.aoMapIntensity = 1, this.emissive = new oe(0), this.emissiveIntensity = 1, this.emissiveMap = null, this.bumpMap = null, this.bumpScale = 1, this.normalMap = null, this.normalMapType = zn, this.normalScale = new H(1, 1), this.displacementMap = null, this.displacementScale = 1, this.displacementBias = 0, this.specularMap = null, this.alphaMap = null, this.envMap = null, this.envMapRotation = new Ai(), this.combine = xa, this.reflectivity = 1, this.refractionRatio = 0.98, this.wireframe = !1, this.wireframeLinewidth = 1, this.wireframeLinecap = "round", this.wireframeLinejoin = "round", this.flatShading = !1, this.fog = !0, this.setValues(e);
  }
  copy(e) {
    return super.copy(e), this.color.copy(e.color), this.map = e.map, this.lightMap = e.lightMap, this.lightMapIntensity = e.lightMapIntensity, this.aoMap = e.aoMap, this.aoMapIntensity = e.aoMapIntensity, this.emissive.copy(e.emissive), this.emissiveMap = e.emissiveMap, this.emissiveIntensity = e.emissiveIntensity, this.bumpMap = e.bumpMap, this.bumpScale = e.bumpScale, this.normalMap = e.normalMap, this.normalMapType = e.normalMapType, this.normalScale.copy(e.normalScale), this.displacementMap = e.displacementMap, this.displacementScale = e.displacementScale, this.displacementBias = e.displacementBias, this.specularMap = e.specularMap, this.alphaMap = e.alphaMap, this.envMap = e.envMap, this.envMapRotation.copy(e.envMapRotation), this.combine = e.combine, this.reflectivity = e.reflectivity, this.refractionRatio = e.refractionRatio, this.wireframe = e.wireframe, this.wireframeLinewidth = e.wireframeLinewidth, this.wireframeLinecap = e.wireframeLinecap, this.wireframeLinejoin = e.wireframeLinejoin, this.flatShading = e.flatShading, this.fog = e.fog, this;
  }
}
class wd extends qt {
  /**
   * Constructs a new mesh depth material.
   *
   * @param {Object} [parameters] - An object with one or more properties
   * defining the material's appearance. Any property of the material
   * (including any property from inherited materials) can be passed
   * in here. Color values can be passed any type of value accepted
   * by {@link Color#set}.
   */
  constructor(e) {
    super(), this.isMeshDepthMaterial = !0, this.type = "MeshDepthMaterial", this.depthPacking = Kf, this.map = null, this.alphaMap = null, this.displacementMap = null, this.displacementScale = 1, this.displacementBias = 0, this.wireframe = !1, this.wireframeLinewidth = 1, this.setValues(e);
  }
  copy(e) {
    return super.copy(e), this.depthPacking = e.depthPacking, this.map = e.map, this.alphaMap = e.alphaMap, this.displacementMap = e.displacementMap, this.displacementScale = e.displacementScale, this.displacementBias = e.displacementBias, this.wireframe = e.wireframe, this.wireframeLinewidth = e.wireframeLinewidth, this;
  }
}
class Ed extends qt {
  /**
   * Constructs a new mesh distance material.
   *
   * @param {Object} [parameters] - An object with one or more properties
   * defining the material's appearance. Any property of the material
   * (including any property from inherited materials) can be passed
   * in here. Color values can be passed any type of value accepted
   * by {@link Color#set}.
   */
  constructor(e) {
    super(), this.isMeshDistanceMaterial = !0, this.type = "MeshDistanceMaterial", this.map = null, this.alphaMap = null, this.displacementMap = null, this.displacementScale = 1, this.displacementBias = 0, this.setValues(e);
  }
  copy(e) {
    return super.copy(e), this.map = e.map, this.alphaMap = e.alphaMap, this.displacementMap = e.displacementMap, this.displacementScale = e.displacementScale, this.displacementBias = e.displacementBias, this;
  }
}
class km extends qt {
  /**
   * Constructs a new mesh matcap material.
   *
   * @param {Object} [parameters] - An object with one or more properties
   * defining the material's appearance. Any property of the material
   * (including any property from inherited materials) can be passed
   * in here. Color values can be passed any type of value accepted
   * by {@link Color#set}.
   */
  constructor(e) {
    super(), this.isMeshMatcapMaterial = !0, this.defines = { MATCAP: "" }, this.type = "MeshMatcapMaterial", this.color = new oe(16777215), this.matcap = null, this.map = null, this.bumpMap = null, this.bumpScale = 1, this.normalMap = null, this.normalMapType = zn, this.normalScale = new H(1, 1), this.displacementMap = null, this.displacementScale = 1, this.displacementBias = 0, this.alphaMap = null, this.flatShading = !1, this.fog = !0, this.setValues(e);
  }
  copy(e) {
    return super.copy(e), this.defines = { MATCAP: "" }, this.color.copy(e.color), this.matcap = e.matcap, this.map = e.map, this.bumpMap = e.bumpMap, this.bumpScale = e.bumpScale, this.normalMap = e.normalMap, this.normalMapType = e.normalMapType, this.normalScale.copy(e.normalScale), this.displacementMap = e.displacementMap, this.displacementScale = e.displacementScale, this.displacementBias = e.displacementBias, this.alphaMap = e.alphaMap, this.flatShading = e.flatShading, this.fog = e.fog, this;
  }
}
class Td extends It {
  /**
   * Constructs a new line dashed material.
   *
   * @param {Object} [parameters] - An object with one or more properties
   * defining the material's appearance. Any property of the material
   * (including any property from inherited materials) can be passed
   * in here. Color values can be passed any type of value accepted
   * by {@link Color#set}.
   */
  constructor(e) {
    super(), this.isLineDashedMaterial = !0, this.type = "LineDashedMaterial", this.scale = 1, this.dashSize = 3, this.gapSize = 1, this.setValues(e);
  }
  copy(e) {
    return super.copy(e), this.scale = e.scale, this.dashSize = e.dashSize, this.gapSize = e.gapSize, this;
  }
}
function ps(r, e) {
  return !r || r.constructor === e ? r : typeof e.BYTES_PER_ELEMENT == "number" ? new e(r) : Array.prototype.slice.call(r);
}
function zm(r) {
  return ArrayBuffer.isView(r) && !(r instanceof DataView);
}
function Hm(r) {
  function e(n, s) {
    return r[n] - r[s];
  }
  const t = r.length, i = new Array(t);
  for (let n = 0; n !== t; ++n) i[n] = n;
  return i.sort(e), i;
}
function kh(r, e, t) {
  const i = r.length, n = new r.constructor(i);
  for (let s = 0, a = 0; a !== i; ++s) {
    const o = t[s] * e;
    for (let l = 0; l !== e; ++l)
      n[a++] = r[o + l];
  }
  return n;
}
function Ad(r, e, t, i) {
  let n = 1, s = r[0];
  for (; s !== void 0 && s[i] === void 0; )
    s = r[n++];
  if (s === void 0) return;
  let a = s[i];
  if (a !== void 0)
    if (Array.isArray(a))
      do
        a = s[i], a !== void 0 && (e.push(s.time), t.push(...a)), s = r[n++];
      while (s !== void 0);
    else if (a.toArray !== void 0)
      do
        a = s[i], a !== void 0 && (e.push(s.time), a.toArray(t, t.length)), s = r[n++];
      while (s !== void 0);
    else
      do
        a = s[i], a !== void 0 && (e.push(s.time), t.push(a)), s = r[n++];
      while (s !== void 0);
}
function Qy(r, e, t, i, n = 30) {
  const s = r.clone();
  s.name = e;
  const a = [];
  for (let l = 0; l < s.tracks.length; ++l) {
    const c = s.tracks[l], h = c.getValueSize(), d = [], u = [];
    for (let p = 0; p < c.times.length; ++p) {
      const m = c.times[p] * n;
      if (!(m < t || m >= i)) {
        d.push(c.times[p]);
        for (let _ = 0; _ < h; ++_)
          u.push(c.values[p * h + _]);
      }
    }
    d.length !== 0 && (c.times = ps(d, c.times.constructor), c.values = ps(u, c.values.constructor), a.push(c));
  }
  s.tracks = a;
  let o = 1 / 0;
  for (let l = 0; l < s.tracks.length; ++l)
    o > s.tracks[l].times[0] && (o = s.tracks[l].times[0]);
  for (let l = 0; l < s.tracks.length; ++l)
    s.tracks[l].shift(-1 * o);
  return s.resetDuration(), s;
}
function e0(r, e = 0, t = r, i = 30) {
  i <= 0 && (i = 30);
  const n = t.tracks.length, s = e / i;
  for (let a = 0; a < n; ++a) {
    const o = t.tracks[a], l = o.ValueTypeName;
    if (l === "bool" || l === "string") continue;
    const c = r.tracks.find(function(f) {
      return f.name === o.name && f.ValueTypeName === l;
    });
    if (c === void 0) continue;
    let h = 0;
    const d = o.getValueSize();
    o.createInterpolant.isInterpolantFactoryMethodGLTFCubicSpline && (h = d / 3);
    let u = 0;
    const p = c.getValueSize();
    c.createInterpolant.isInterpolantFactoryMethodGLTFCubicSpline && (u = p / 3);
    const m = o.times.length - 1;
    let _;
    if (s <= o.times[0]) {
      const f = h, v = d - h;
      _ = o.values.slice(f, v);
    } else if (s >= o.times[m]) {
      const f = m * d + h, v = f + d - h;
      _ = o.values.slice(f, v);
    } else {
      const f = o.createInterpolant(), v = h, x = d - h;
      f.evaluate(s), _ = f.resultBuffer.slice(v, x);
    }
    l === "quaternion" && new ot().fromArray(_).normalize().conjugate().toArray(_);
    const g = c.times.length;
    for (let f = 0; f < g; ++f) {
      const v = f * p + u;
      if (l === "quaternion")
        ot.multiplyQuaternionsFlat(
          c.values,
          v,
          _,
          0,
          c.values,
          v
        );
      else {
        const x = p - u * 2;
        for (let y = 0; y < x; ++y)
          c.values[v + y] -= _[y];
      }
    }
  }
  return r.blendMode = ad, r;
}
class t0 {
  /**
   * Converts an array to a specific type
   *
   * @static
   * @param {TypedArray|Array} array - The array to convert.
   * @param {TypedArray.constructor} type - The constructor of a type array.
   * @return {TypedArray} The converted array
   */
  static convertArray(e, t) {
    return ps(e, t);
  }
  /**
   * Returns `true` if the given object is a typed array.
   *
   * @static
   * @param {any} object - The object to check.
   * @return {boolean} Whether the given object is a typed array.
   */
  static isTypedArray(e) {
    return zm(e);
  }
  /**
   * Returns an array by which times and values can be sorted.
   *
   * @static
   * @param {Array<number>} times - The keyframe time values.
   * @return {Array<number>} The array.
   */
  static getKeyframeOrder(e) {
    return Hm(e);
  }
  /**
   * Sorts the given array by the previously computed order via `getKeyframeOrder()`.
   *
   * @static
   * @param {Array<number>} values - The values to sort.
   * @param {number} stride - The stride.
   * @param {Array<number>} order - The sort order.
   * @return {Array<number>} The sorted values.
   */
  static sortedArray(e, t, i) {
    return kh(e, t, i);
  }
  /**
   * Used for parsing AOS keyframe formats.
   *
   * @static
   * @param {Array<number>} jsonKeys - A list of JSON keyframes.
   * @param {Array<number>} times - This array will be filled with keyframe times by this method.
   * @param {Array<number>} values - This array will be filled with keyframe values by this method.
   * @param {string} valuePropertyName - The name of the property to use.
   */
  static flattenJSON(e, t, i, n) {
    Ad(e, t, i, n);
  }
  /**
   * Creates a new clip, containing only the segment of the original clip between the given frames.
   *
   * @static
   * @param {AnimationClip} sourceClip - The values to sort.
   * @param {string} name - The name of the clip.
   * @param {number} startFrame - The start frame.
   * @param {number} endFrame - The end frame.
   * @param {number} [fps=30] - The FPS.
   * @return {AnimationClip} The new sub clip.
   */
  static subclip(e, t, i, n, s = 30) {
    return Qy(e, t, i, n, s);
  }
  /**
   * Converts the keyframes of the given animation clip to an additive format.
   *
   * @static
   * @param {AnimationClip} targetClip - The clip to make additive.
   * @param {number} [referenceFrame=0] - The reference frame.
   * @param {AnimationClip} [referenceClip=targetClip] - The reference clip.
   * @param {number} [fps=30] - The FPS.
   * @return {AnimationClip} The updated clip which is now additive.
   */
  static makeClipAdditive(e, t = 0, i = e, n = 30) {
    return e0(e, t, i, n);
  }
}
class Aa {
  /**
   * Constructs a new interpolant.
   *
   * @param {TypedArray} parameterPositions - The parameter positions hold the interpolation factors.
   * @param {TypedArray} sampleValues - The sample values.
   * @param {number} sampleSize - The sample size
   * @param {TypedArray} [resultBuffer] - The result buffer.
   */
  constructor(e, t, i, n) {
    this.parameterPositions = e, this._cachedIndex = 0, this.resultBuffer = n !== void 0 ? n : new t.constructor(i), this.sampleValues = t, this.valueSize = i, this.settings = null, this.DefaultSettings_ = {};
  }
  /**
   * Evaluate the interpolant at position `t`.
   *
   * @param {number} t - The interpolation factor.
   * @return {TypedArray} The result buffer.
   */
  evaluate(e) {
    const t = this.parameterPositions;
    let i = this._cachedIndex, n = t[i], s = t[i - 1];
    e: {
      t: {
        let a;
        i: {
          n: if (!(e < n)) {
            for (let o = i + 2; ; ) {
              if (n === void 0) {
                if (e < s) break n;
                return i = t.length, this._cachedIndex = i, this.copySampleValue_(i - 1);
              }
              if (i === o) break;
              if (s = n, n = t[++i], e < n)
                break t;
            }
            a = t.length;
            break i;
          }
          if (!(e >= s)) {
            const o = t[1];
            e < o && (i = 2, s = o);
            for (let l = i - 2; ; ) {
              if (s === void 0)
                return this._cachedIndex = 0, this.copySampleValue_(0);
              if (i === l) break;
              if (n = s, s = t[--i - 1], e >= s)
                break t;
            }
            a = i, i = 0;
            break i;
          }
          break e;
        }
        for (; i < a; ) {
          const o = i + a >>> 1;
          e < t[o] ? a = o : i = o + 1;
        }
        if (n = t[i], s = t[i - 1], s === void 0)
          return this._cachedIndex = 0, this.copySampleValue_(0);
        if (n === void 0)
          return i = t.length, this._cachedIndex = i, this.copySampleValue_(i - 1);
      }
      this._cachedIndex = i, this.intervalChanged_(i, s, n);
    }
    return this.interpolate_(i, s, e, n);
  }
  /**
   * Returns the interpolation settings.
   *
   * @return {Object} The interpolation settings.
   */
  getSettings_() {
    return this.settings || this.DefaultSettings_;
  }
  /**
   * Copies a sample value to the result buffer.
   *
   * @param {number} index - An index into the sample value buffer.
   * @return {TypedArray} The result buffer.
   */
  copySampleValue_(e) {
    const t = this.resultBuffer, i = this.sampleValues, n = this.valueSize, s = e * n;
    for (let a = 0; a !== n; ++a)
      t[a] = i[s + a];
    return t;
  }
  /**
   * Copies a sample value to the result buffer.
   *
   * @abstract
   * @param {number} i1 - An index into the sample value buffer.
   * @param {number} t0 - The previous interpolation factor.
   * @param {number} t - The current interpolation factor.
   * @param {number} t1 - The next interpolation factor.
   * @return {TypedArray} The result buffer.
   */
  interpolate_() {
    throw new Error("call to abstract method");
  }
  /**
   * Optional method that is executed when the interval has changed.
   *
   * @param {number} i1 - An index into the sample value buffer.
   * @param {number} t0 - The previous interpolation factor.
   * @param {number} t - The current interpolation factor.
   */
  intervalChanged_() {
  }
}
class Vm extends Aa {
  /**
   * Constructs a new cubic interpolant.
   *
   * @param {TypedArray} parameterPositions - The parameter positions hold the interpolation factors.
   * @param {TypedArray} sampleValues - The sample values.
   * @param {number} sampleSize - The sample size
   * @param {TypedArray} [resultBuffer] - The result buffer.
   */
  constructor(e, t, i, n) {
    super(e, t, i, n), this._weightPrev = -0, this._offsetPrev = -0, this._weightNext = -0, this._offsetNext = -0, this.DefaultSettings_ = {
      endingStart: ds,
      endingEnd: ds
    };
  }
  intervalChanged_(e, t, i) {
    const n = this.parameterPositions;
    let s = e - 2, a = e + 1, o = n[s], l = n[a];
    if (o === void 0)
      switch (this.getSettings_().endingStart) {
        case us:
          s = e, o = 2 * t - i;
          break;
        case oa:
          s = n.length - 2, o = t + n[s] - n[s + 1];
          break;
        default:
          s = e, o = i;
      }
    if (l === void 0)
      switch (this.getSettings_().endingEnd) {
        case us:
          a = e, l = 2 * i - t;
          break;
        case oa:
          a = 1, l = i + n[1] - n[0];
          break;
        default:
          a = e - 1, l = t;
      }
    const c = (i - t) * 0.5, h = this.valueSize;
    this._weightPrev = c / (t - o), this._weightNext = c / (l - i), this._offsetPrev = s * h, this._offsetNext = a * h;
  }
  interpolate_(e, t, i, n) {
    const s = this.resultBuffer, a = this.sampleValues, o = this.valueSize, l = e * o, c = l - o, h = this._offsetPrev, d = this._offsetNext, u = this._weightPrev, p = this._weightNext, m = (i - t) / (n - t), _ = m * m, g = _ * m, f = -u * g + 2 * u * _ - u * m, v = (1 + u) * g + (-1.5 - 2 * u) * _ + (-0.5 + u) * m + 1, x = (-1 - p) * g + (1.5 + p) * _ + 0.5 * m, y = p * g - p * _;
    for (let A = 0; A !== o; ++A)
      s[A] = f * a[h + A] + v * a[c + A] + x * a[l + A] + y * a[d + A];
    return s;
  }
}
class Cd extends Aa {
  /**
   * Constructs a new linear interpolant.
   *
   * @param {TypedArray} parameterPositions - The parameter positions hold the interpolation factors.
   * @param {TypedArray} sampleValues - The sample values.
   * @param {number} sampleSize - The sample size
   * @param {TypedArray} [resultBuffer] - The result buffer.
   */
  constructor(e, t, i, n) {
    super(e, t, i, n);
  }
  interpolate_(e, t, i, n) {
    const s = this.resultBuffer, a = this.sampleValues, o = this.valueSize, l = e * o, c = l - o, h = (i - t) / (n - t), d = 1 - h;
    for (let u = 0; u !== o; ++u)
      s[u] = a[c + u] * d + a[l + u] * h;
    return s;
  }
}
class Gm extends Aa {
  /**
   * Constructs a new discrete interpolant.
   *
   * @param {TypedArray} parameterPositions - The parameter positions hold the interpolation factors.
   * @param {TypedArray} sampleValues - The sample values.
   * @param {number} sampleSize - The sample size
   * @param {TypedArray} [resultBuffer] - The result buffer.
   */
  constructor(e, t, i, n) {
    super(e, t, i, n);
  }
  interpolate_(e) {
    return this.copySampleValue_(e - 1);
  }
}
class Ni {
  /**
   * Constructs a new keyframe track.
   *
   * @param {string} name - The keyframe track's name.
   * @param {Array<number>} times - A list of keyframe times.
   * @param {Array<number|string|boolean>} values - A list of keyframe values.
   * @param {(InterpolateLinear|InterpolateDiscrete|InterpolateSmooth)} [interpolation] - The interpolation type.
   */
  constructor(e, t, i, n) {
    if (e === void 0) throw new Error("THREE.KeyframeTrack: track name is undefined");
    if (t === void 0 || t.length === 0) throw new Error("THREE.KeyframeTrack: no keyframes in track named " + e);
    this.name = e, this.times = ps(t, this.TimeBufferType), this.values = ps(i, this.ValueBufferType), this.setInterpolation(n || this.DefaultInterpolation);
  }
  /**
   * Converts the keyframe track to JSON.
   *
   * @static
   * @param {KeyframeTrack} track - The keyframe track to serialize.
   * @return {Object} The serialized keyframe track as JSON.
   */
  static toJSON(e) {
    const t = e.constructor;
    let i;
    if (t.toJSON !== this.toJSON)
      i = t.toJSON(e);
    else {
      i = {
        name: e.name,
        times: ps(e.times, Array),
        values: ps(e.values, Array)
      };
      const n = e.getInterpolation();
      n !== e.DefaultInterpolation && (i.interpolation = n);
    }
    return i.type = e.ValueTypeName, i;
  }
  /**
   * Factory method for creating a new discrete interpolant.
   *
   * @static
   * @param {TypedArray} [result] - The result buffer.
   * @return {DiscreteInterpolant} The new interpolant.
   */
  InterpolantFactoryMethodDiscrete(e) {
    return new Gm(this.times, this.values, this.getValueSize(), e);
  }
  /**
   * Factory method for creating a new linear interpolant.
   *
   * @static
   * @param {TypedArray} [result] - The result buffer.
   * @return {LinearInterpolant} The new interpolant.
   */
  InterpolantFactoryMethodLinear(e) {
    return new Cd(this.times, this.values, this.getValueSize(), e);
  }
  /**
   * Factory method for creating a new smooth interpolant.
   *
   * @static
   * @param {TypedArray} [result] - The result buffer.
   * @return {CubicInterpolant} The new interpolant.
   */
  InterpolantFactoryMethodSmooth(e) {
    return new Vm(this.times, this.values, this.getValueSize(), e);
  }
  /**
   * Defines the interpolation factor method for this keyframe track.
   *
   * @param {(InterpolateLinear|InterpolateDiscrete|InterpolateSmooth)} interpolation - The interpolation type.
   * @return {KeyframeTrack} A reference to this keyframe track.
   */
  setInterpolation(e) {
    let t;
    switch (e) {
      case aa:
        t = this.InterpolantFactoryMethodDiscrete;
        break;
      case Rl:
        t = this.InterpolantFactoryMethodLinear;
        break;
      case zo:
        t = this.InterpolantFactoryMethodSmooth;
        break;
    }
    if (t === void 0) {
      const i = "unsupported interpolation for " + this.ValueTypeName + " keyframe track named " + this.name;
      if (this.createInterpolant === void 0)
        if (e !== this.DefaultInterpolation)
          this.setInterpolation(this.DefaultInterpolation);
        else
          throw new Error(i);
      return console.warn("THREE.KeyframeTrack:", i), this;
    }
    return this.createInterpolant = t, this;
  }
  /**
   * Returns the current interpolation type.
   *
   * @return {(InterpolateLinear|InterpolateDiscrete|InterpolateSmooth)} The interpolation type.
   */
  getInterpolation() {
    switch (this.createInterpolant) {
      case this.InterpolantFactoryMethodDiscrete:
        return aa;
      case this.InterpolantFactoryMethodLinear:
        return Rl;
      case this.InterpolantFactoryMethodSmooth:
        return zo;
    }
  }
  /**
   * Returns the value size.
   *
   * @return {number} The value size.
   */
  getValueSize() {
    return this.values.length / this.times.length;
  }
  /**
   * Moves all keyframes either forward or backward in time.
   *
   * @param {number} timeOffset - The offset to move the time values.
   * @return {KeyframeTrack} A reference to this keyframe track.
   */
  shift(e) {
    if (e !== 0) {
      const t = this.times;
      for (let i = 0, n = t.length; i !== n; ++i)
        t[i] += e;
    }
    return this;
  }
  /**
   * Scale all keyframe times by a factor (useful for frame - seconds conversions).
   *
   * @param {number} timeScale - The time scale.
   * @return {KeyframeTrack} A reference to this keyframe track.
   */
  scale(e) {
    if (e !== 1) {
      const t = this.times;
      for (let i = 0, n = t.length; i !== n; ++i)
        t[i] *= e;
    }
    return this;
  }
  /**
   * Removes keyframes before and after animation without changing any values within the defined time range.
   *
   * Note: The method does not shift around keys to the start of the track time, because for interpolated
   * keys this will change their values
   *
   * @param {number} startTime - The start time.
   * @param {number} endTime - The end time.
   * @return {KeyframeTrack} A reference to this keyframe track.
   */
  trim(e, t) {
    const i = this.times, n = i.length;
    let s = 0, a = n - 1;
    for (; s !== n && i[s] < e; )
      ++s;
    for (; a !== -1 && i[a] > t; )
      --a;
    if (++a, s !== 0 || a !== n) {
      s >= a && (a = Math.max(a, 1), s = a - 1);
      const o = this.getValueSize();
      this.times = i.slice(s, a), this.values = this.values.slice(s * o, a * o);
    }
    return this;
  }
  /**
   * Performs minimal validation on the keyframe track. Returns `true` if the values
   * are valid.
   *
   * @return {boolean} Whether the keyframes are valid or not.
   */
  validate() {
    let e = !0;
    const t = this.getValueSize();
    t - Math.floor(t) !== 0 && (console.error("THREE.KeyframeTrack: Invalid value size in track.", this), e = !1);
    const i = this.times, n = this.values, s = i.length;
    s === 0 && (console.error("THREE.KeyframeTrack: Track is empty.", this), e = !1);
    let a = null;
    for (let o = 0; o !== s; o++) {
      const l = i[o];
      if (typeof l == "number" && isNaN(l)) {
        console.error("THREE.KeyframeTrack: Time is not a valid number.", this, o, l), e = !1;
        break;
      }
      if (a !== null && a > l) {
        console.error("THREE.KeyframeTrack: Out of order keys.", this, o, l, a), e = !1;
        break;
      }
      a = l;
    }
    if (n !== void 0 && zm(n))
      for (let o = 0, l = n.length; o !== l; ++o) {
        const c = n[o];
        if (isNaN(c)) {
          console.error("THREE.KeyframeTrack: Value is not a valid number.", this, o, c), e = !1;
          break;
        }
      }
    return e;
  }
  /**
   * Optimizes this keyframe track by removing equivalent sequential keys (which are
   * common in morph target sequences).
   *
   * @return {AnimationClip} A reference to this animation clip.
   */
  optimize() {
    const e = this.times.slice(), t = this.values.slice(), i = this.getValueSize(), n = this.getInterpolation() === zo, s = e.length - 1;
    let a = 1;
    for (let o = 1; o < s; ++o) {
      let l = !1;
      const c = e[o], h = e[o + 1];
      if (c !== h && (o !== 1 || c !== e[0]))
        if (n)
          l = !0;
        else {
          const d = o * i, u = d - i, p = d + i;
          for (let m = 0; m !== i; ++m) {
            const _ = t[d + m];
            if (_ !== t[u + m] || _ !== t[p + m]) {
              l = !0;
              break;
            }
          }
        }
      if (l) {
        if (o !== a) {
          e[a] = e[o];
          const d = o * i, u = a * i;
          for (let p = 0; p !== i; ++p)
            t[u + p] = t[d + p];
        }
        ++a;
      }
    }
    if (s > 0) {
      e[a] = e[s];
      for (let o = s * i, l = a * i, c = 0; c !== i; ++c)
        t[l + c] = t[o + c];
      ++a;
    }
    return a !== e.length ? (this.times = e.slice(0, a), this.values = t.slice(0, a * i)) : (this.times = e, this.values = t), this;
  }
  /**
   * Returns a new keyframe track with copied values from this instance.
   *
   * @return {KeyframeTrack} A clone of this instance.
   */
  clone() {
    const e = this.times.slice(), t = this.values.slice(), i = this.constructor, n = new i(this.name, e, t);
    return n.createInterpolant = this.createInterpolant, n;
  }
}
Ni.prototype.ValueTypeName = "";
Ni.prototype.TimeBufferType = Float32Array;
Ni.prototype.ValueBufferType = Float32Array;
Ni.prototype.DefaultInterpolation = Rl;
class As extends Ni {
  /**
   * Constructs a new boolean keyframe track.
   *
   * This keyframe track type has no `interpolation` parameter because the
   * interpolation is always discrete.
   *
   * @param {string} name - The keyframe track's name.
   * @param {Array<number>} times - A list of keyframe times.
   * @param {Array<boolean>} values - A list of keyframe values.
   */
  constructor(e, t, i) {
    super(e, t, i);
  }
}
As.prototype.ValueTypeName = "bool";
As.prototype.ValueBufferType = Array;
As.prototype.DefaultInterpolation = aa;
As.prototype.InterpolantFactoryMethodLinear = void 0;
As.prototype.InterpolantFactoryMethodSmooth = void 0;
class Rd extends Ni {
  /**
   * Constructs a new color keyframe track.
   *
   * @param {string} name - The keyframe track's name.
   * @param {Array<number>} times - A list of keyframe times.
   * @param {Array<number>} values - A list of keyframe values.
   * @param {(InterpolateLinear|InterpolateDiscrete|InterpolateSmooth)} [interpolation] - The interpolation type.
   */
  constructor(e, t, i, n) {
    super(e, t, i, n);
  }
}
Rd.prototype.ValueTypeName = "color";
class _a extends Ni {
  /**
   * Constructs a new number keyframe track.
   *
   * @param {string} name - The keyframe track's name.
   * @param {Array<number>} times - A list of keyframe times.
   * @param {Array<number>} values - A list of keyframe values.
   * @param {(InterpolateLinear|InterpolateDiscrete|InterpolateSmooth)} [interpolation] - The interpolation type.
   */
  constructor(e, t, i, n) {
    super(e, t, i, n);
  }
}
_a.prototype.ValueTypeName = "number";
class Wm extends Aa {
  /**
   * Constructs a new SLERP interpolant.
   *
   * @param {TypedArray} parameterPositions - The parameter positions hold the interpolation factors.
   * @param {TypedArray} sampleValues - The sample values.
   * @param {number} sampleSize - The sample size
   * @param {TypedArray} [resultBuffer] - The result buffer.
   */
  constructor(e, t, i, n) {
    super(e, t, i, n);
  }
  interpolate_(e, t, i, n) {
    const s = this.resultBuffer, a = this.sampleValues, o = this.valueSize, l = (i - t) / (n - t);
    let c = e * o;
    for (let h = c + o; c !== h; c += 4)
      ot.slerpFlat(s, 0, a, c - o, a, c, l);
    return s;
  }
}
class Ss extends Ni {
  /**
   * Constructs a new Quaternion keyframe track.
   *
   * @param {string} name - The keyframe track's name.
   * @param {Array<number>} times - A list of keyframe times.
   * @param {Array<number>} values - A list of keyframe values.
   * @param {(InterpolateLinear|InterpolateDiscrete|InterpolateSmooth)} [interpolation] - The interpolation type.
   */
  constructor(e, t, i, n) {
    super(e, t, i, n);
  }
  /**
   * Overwritten so the method returns Quaternion based interpolant.
   *
   * @static
   * @param {TypedArray} [result] - The result buffer.
   * @return {QuaternionLinearInterpolant} The new interpolant.
   */
  InterpolantFactoryMethodLinear(e) {
    return new Wm(this.times, this.values, this.getValueSize(), e);
  }
}
Ss.prototype.ValueTypeName = "quaternion";
Ss.prototype.InterpolantFactoryMethodSmooth = void 0;
class Cs extends Ni {
  /**
   * Constructs a new string keyframe track.
   *
   * This keyframe track type has no `interpolation` parameter because the
   * interpolation is always discrete.
   *
   * @param {string} name - The keyframe track's name.
   * @param {Array<number>} times - A list of keyframe times.
   * @param {Array<string>} values - A list of keyframe values.
   */
  constructor(e, t, i) {
    super(e, t, i);
  }
}
Cs.prototype.ValueTypeName = "string";
Cs.prototype.ValueBufferType = Array;
Cs.prototype.DefaultInterpolation = aa;
Cs.prototype.InterpolantFactoryMethodLinear = void 0;
Cs.prototype.InterpolantFactoryMethodSmooth = void 0;
class Ms extends Ni {
  /**
   * Constructs a new vector keyframe track.
   *
   * @param {string} name - The keyframe track's name.
   * @param {Array<number>} times - A list of keyframe times.
   * @param {Array<number>} values - A list of keyframe values.
   * @param {(InterpolateLinear|InterpolateDiscrete|InterpolateSmooth)} [interpolation] - The interpolation type.
   */
  constructor(e, t, i, n) {
    super(e, t, i, n);
  }
}
Ms.prototype.ValueTypeName = "vector";
class yr {
  /**
   * Constructs a new animation clip.
   *
   * Note: Instead of instantiating an AnimationClip directly with the constructor, you can
   * use the static interface of this class for creating clips. In most cases though, animation clips
   * will automatically be created by loaders when importing animated 3D assets.
   *
   * @param {string} [name=''] - The clip's name.
   * @param {number} [duration=-1] - The clip's duration in seconds. If a negative value is passed,
   * the duration will be calculated from the passed keyframes.
   * @param {Array<KeyframeTrack>} tracks - An array of keyframe tracks.
   * @param {(NormalAnimationBlendMode|AdditiveAnimationBlendMode)} [blendMode=NormalAnimationBlendMode] - Defines how the animation
   * is blended/combined when two or more animations are simultaneously played.
   */
  constructor(e = "", t = -1, i = [], n = Gl) {
    this.name = e, this.tracks = i, this.duration = t, this.blendMode = n, this.uuid = Ti(), this.userData = {}, this.duration < 0 && this.resetDuration();
  }
  /**
   * Factory method for creating an animation clip from the given JSON.
   *
   * @static
   * @param {Object} json - The serialized animation clip.
   * @return {AnimationClip} The new animation clip.
   */
  static parse(e) {
    const t = [], i = e.tracks, n = 1 / (e.fps || 1);
    for (let a = 0, o = i.length; a !== o; ++a)
      t.push(n0(i[a]).scale(n));
    const s = new this(e.name, e.duration, t, e.blendMode);
    return s.uuid = e.uuid, s.userData = JSON.parse(e.userData || "{}"), s;
  }
  /**
   * Serializes the given animation clip into JSON.
   *
   * @static
   * @param {AnimationClip} clip - The animation clip to serialize.
   * @return {Object} The JSON object.
   */
  static toJSON(e) {
    const t = [], i = e.tracks, n = {
      name: e.name,
      duration: e.duration,
      tracks: t,
      uuid: e.uuid,
      blendMode: e.blendMode,
      userData: JSON.stringify(e.userData)
    };
    for (let s = 0, a = i.length; s !== a; ++s)
      t.push(Ni.toJSON(i[s]));
    return n;
  }
  /**
   * Returns a new animation clip from the passed morph targets array of a
   * geometry, taking a name and the number of frames per second.
   *
   * Note: The fps parameter is required, but the animation speed can be
   * overridden via {@link AnimationAction#setDuration}.
   *
   * @static
   * @param {string} name - The name of the animation clip.
   * @param {Array<Object>} morphTargetSequence - A sequence of morph targets.
   * @param {number} fps - The Frames-Per-Second value.
   * @param {boolean} noLoop - Whether the clip should be no loop or not.
   * @return {AnimationClip} The new animation clip.
   */
  static CreateFromMorphTargetSequence(e, t, i, n) {
    const s = t.length, a = [];
    for (let o = 0; o < s; o++) {
      let l = [], c = [];
      l.push(
        (o + s - 1) % s,
        o,
        (o + 1) % s
      ), c.push(0, 1, 0);
      const h = Hm(l);
      l = kh(l, 1, h), c = kh(c, 1, h), !n && l[0] === 0 && (l.push(s), c.push(c[0])), a.push(
        new _a(
          ".morphTargetInfluences[" + t[o].name + "]",
          l,
          c
        ).scale(1 / i)
      );
    }
    return new this(e, -1, a);
  }
  /**
   * Searches for an animation clip by name, taking as its first parameter
   * either an array of clips, or a mesh or geometry that contains an
   * array named "animations" property.
   *
   * @static
   * @param {(Array<AnimationClip>|Object3D)} objectOrClipArray - The array or object to search through.
   * @param {string} name - The name to search for.
   * @return {?AnimationClip} The found animation clip. Returns `null` if no clip has been found.
   */
  static findByName(e, t) {
    let i = e;
    if (!Array.isArray(e)) {
      const n = e;
      i = n.geometry && n.geometry.animations || n.animations;
    }
    for (let n = 0; n < i.length; n++)
      if (i[n].name === t)
        return i[n];
    return null;
  }
  /**
   * Returns an array of new AnimationClips created from the morph target
   * sequences of a geometry, trying to sort morph target names into
   * animation-group-based patterns like "Walk_001, Walk_002, Run_001, Run_002...".
   *
   * See {@link MD2Loader#parse} as an example for how the method should be used.
   *
   * @static
   * @param {Array<Object>} morphTargets - A sequence of morph targets.
   * @param {number} fps - The Frames-Per-Second value.
   * @param {boolean} noLoop - Whether the clip should be no loop or not.
   * @return {Array<AnimationClip>} An array of new animation clips.
   */
  static CreateClipsFromMorphTargetSequences(e, t, i) {
    const n = {}, s = /^([\w-]*?)([\d]+)$/;
    for (let o = 0, l = e.length; o < l; o++) {
      const c = e[o], h = c.name.match(s);
      if (h && h.length > 1) {
        const d = h[1];
        let u = n[d];
        u || (n[d] = u = []), u.push(c);
      }
    }
    const a = [];
    for (const o in n)
      a.push(this.CreateFromMorphTargetSequence(o, n[o], t, i));
    return a;
  }
  /**
   * Parses the `animation.hierarchy` format and returns a new animation clip.
   *
   * @static
   * @deprecated since r175.
   * @param {Object} animation - A serialized animation clip as JSON.
   * @param {Array<Bones>} bones - An array of bones.
   * @return {?AnimationClip} The new animation clip.
   */
  static parseAnimation(e, t) {
    if (console.warn("THREE.AnimationClip: parseAnimation() is deprecated and will be removed with r185"), !e)
      return console.error("THREE.AnimationClip: No animation in JSONLoader data."), null;
    const i = function(d, u, p, m, _) {
      if (p.length !== 0) {
        const g = [], f = [];
        Ad(p, g, f, m), g.length !== 0 && _.push(new d(u, g, f));
      }
    }, n = [], s = e.name || "default", a = e.fps || 30, o = e.blendMode;
    let l = e.length || -1;
    const c = e.hierarchy || [];
    for (let d = 0; d < c.length; d++) {
      const u = c[d].keys;
      if (!(!u || u.length === 0))
        if (u[0].morphTargets) {
          const p = {};
          let m;
          for (m = 0; m < u.length; m++)
            if (u[m].morphTargets)
              for (let _ = 0; _ < u[m].morphTargets.length; _++)
                p[u[m].morphTargets[_]] = -1;
          for (const _ in p) {
            const g = [], f = [];
            for (let v = 0; v !== u[m].morphTargets.length; ++v) {
              const x = u[m];
              g.push(x.time), f.push(x.morphTarget === _ ? 1 : 0);
            }
            n.push(new _a(".morphTargetInfluence[" + _ + "]", g, f));
          }
          l = p.length * a;
        } else {
          const p = ".bones[" + t[d].name + "]";
          i(
            Ms,
            p + ".position",
            u,
            "pos",
            n
          ), i(
            Ss,
            p + ".quaternion",
            u,
            "rot",
            n
          ), i(
            Ms,
            p + ".scale",
            u,
            "scl",
            n
          );
        }
    }
    return n.length === 0 ? null : new this(s, l, n, o);
  }
  /**
   * Sets the duration of this clip to the duration of its longest keyframe track.
   *
   * @return {AnimationClip} A reference to this animation clip.
   */
  resetDuration() {
    const e = this.tracks;
    let t = 0;
    for (let i = 0, n = e.length; i !== n; ++i) {
      const s = this.tracks[i];
      t = Math.max(t, s.times[s.times.length - 1]);
    }
    return this.duration = t, this;
  }
  /**
   * Trims all tracks to the clip's duration.
   *
   * @return {AnimationClip} A reference to this animation clip.
   */
  trim() {
    for (let e = 0; e < this.tracks.length; e++)
      this.tracks[e].trim(0, this.duration);
    return this;
  }
  /**
   * Performs minimal validation on each track in the clip. Returns `true` if all
   * tracks are valid.
   *
   * @return {boolean} Whether the clip's keyframes are valid or not.
   */
  validate() {
    let e = !0;
    for (let t = 0; t < this.tracks.length; t++)
      e = e && this.tracks[t].validate();
    return e;
  }
  /**
   * Optimizes each track by removing equivalent sequential keys (which are
   * common in morph target sequences).
   *
   * @return {AnimationClip} A reference to this animation clip.
   */
  optimize() {
    for (let e = 0; e < this.tracks.length; e++)
      this.tracks[e].optimize();
    return this;
  }
  /**
   * Returns a new animation clip with copied values from this instance.
   *
   * @return {AnimationClip} A clone of this instance.
   */
  clone() {
    const e = [];
    for (let i = 0; i < this.tracks.length; i++)
      e.push(this.tracks[i].clone());
    const t = new this.constructor(this.name, this.duration, e, this.blendMode);
    return t.userData = JSON.parse(JSON.stringify(this.userData)), t;
  }
  /**
   * Serializes this animation clip into JSON.
   *
   * @return {Object} The JSON object.
   */
  toJSON() {
    return this.constructor.toJSON(this);
  }
}
function i0(r) {
  switch (r.toLowerCase()) {
    case "scalar":
    case "double":
    case "float":
    case "number":
    case "integer":
      return _a;
    case "vector":
    case "vector2":
    case "vector3":
    case "vector4":
      return Ms;
    case "color":
      return Rd;
    case "quaternion":
      return Ss;
    case "bool":
    case "boolean":
      return As;
    case "string":
      return Cs;
  }
  throw new Error("THREE.KeyframeTrack: Unsupported typeName: " + r);
}
function n0(r) {
  if (r.type === void 0)
    throw new Error("THREE.KeyframeTrack: track type undefined, can not parse");
  const e = i0(r.type);
  if (r.times === void 0) {
    const t = [], i = [];
    Ad(r.keys, t, i, "value"), r.times = t, r.values = i;
  }
  return e.parse !== void 0 ? e.parse(r) : new e(r.name, r.times, r.values, r.interpolation);
}
const Qi = {
  /**
   * Whether caching is enabled or not.
   *
   * @static
   * @type {boolean}
   * @default false
   */
  enabled: !1,
  /**
   * A dictionary that holds cached files.
   *
   * @static
   * @type {Object<string,Object>}
   */
  files: {},
  /**
   * Adds a cache entry with a key to reference the file. If this key already
   * holds a file, it is overwritten.
   *
   * @static
   * @param {string} key - The key to reference the cached file.
   * @param {Object} file -  The file to be cached.
   */
  add: function(r, e) {
    this.enabled !== !1 && (this.files[r] = e);
  },
  /**
   * Gets the cached value for the given key.
   *
   * @static
   * @param {string} key - The key to reference the cached file.
   * @return {Object|undefined} The cached file. If the key does not exist `undefined` is returned.
   */
  get: function(r) {
    if (this.enabled !== !1)
      return this.files[r];
  },
  /**
   * Removes the cached file associated with the given key.
   *
   * @static
   * @param {string} key - The key to reference the cached file.
   */
  remove: function(r) {
    delete this.files[r];
  },
  /**
   * Remove all values from the cache.
   *
   * @static
   */
  clear: function() {
    this.files = {};
  }
};
class Pd {
  /**
   * Constructs a new loading manager.
   *
   * @param {Function} [onLoad] - Executes when all items have been loaded.
   * @param {Function} [onProgress] - Executes when single items have been loaded.
   * @param {Function} [onError] - Executes when an error occurs.
   */
  constructor(e, t, i) {
    const n = this;
    let s = !1, a = 0, o = 0, l;
    const c = [];
    this.onStart = void 0, this.onLoad = e, this.onProgress = t, this.onError = i, this.abortController = new AbortController(), this.itemStart = function(h) {
      o++, s === !1 && n.onStart !== void 0 && n.onStart(h, a, o), s = !0;
    }, this.itemEnd = function(h) {
      a++, n.onProgress !== void 0 && n.onProgress(h, a, o), a === o && (s = !1, n.onLoad !== void 0 && n.onLoad());
    }, this.itemError = function(h) {
      n.onError !== void 0 && n.onError(h);
    }, this.resolveURL = function(h) {
      return l ? l(h) : h;
    }, this.setURLModifier = function(h) {
      return l = h, this;
    }, this.addHandler = function(h, d) {
      return c.push(h, d), this;
    }, this.removeHandler = function(h) {
      const d = c.indexOf(h);
      return d !== -1 && c.splice(d, 2), this;
    }, this.getHandler = function(h) {
      for (let d = 0, u = c.length; d < u; d += 2) {
        const p = c[d], m = c[d + 1];
        if (p.global && (p.lastIndex = 0), p.test(h))
          return m;
      }
      return null;
    }, this.abort = function() {
      return this.abortController.abort(), this.abortController = new AbortController(), this;
    };
  }
}
const Xm = /* @__PURE__ */ new Pd();
class gi {
  /**
   * Constructs a new loader.
   *
   * @param {LoadingManager} [manager] - The loading manager.
   */
  constructor(e) {
    this.manager = e !== void 0 ? e : Xm, this.crossOrigin = "anonymous", this.withCredentials = !1, this.path = "", this.resourcePath = "", this.requestHeader = {};
  }
  /**
   * This method needs to be implemented by all concrete loaders. It holds the
   * logic for loading assets from the backend.
   *
   * @abstract
   * @param {string} url - The path/URL of the file to be loaded.
   * @param {Function} onLoad - Executed when the loading process has been finished.
   * @param {onProgressCallback} [onProgress] - Executed while the loading is in progress.
   * @param {onErrorCallback} [onError] - Executed when errors occur.
   */
  load() {
  }
  /**
   * A async version of {@link Loader#load}.
   *
   * @param {string} url - The path/URL of the file to be loaded.
   * @param {onProgressCallback} [onProgress] - Executed while the loading is in progress.
   * @return {Promise} A Promise that resolves when the asset has been loaded.
   */
  loadAsync(e, t) {
    const i = this;
    return new Promise(function(n, s) {
      i.load(e, n, t, s);
    });
  }
  /**
   * This method needs to be implemented by all concrete loaders. It holds the
   * logic for parsing the asset into three.js entities.
   *
   * @abstract
   * @param {any} data - The data to parse.
   */
  parse() {
  }
  /**
   * Sets the `crossOrigin` String to implement CORS for loading the URL
   * from a different domain that allows CORS.
   *
   * @param {string} crossOrigin - The `crossOrigin` value.
   * @return {Loader} A reference to this instance.
   */
  setCrossOrigin(e) {
    return this.crossOrigin = e, this;
  }
  /**
   * Whether the XMLHttpRequest uses credentials such as cookies, authorization
   * headers or TLS client certificates, see [XMLHttpRequest.withCredentials]{@link https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest/withCredentials}.
   *
   * Note: This setting has no effect if you are loading files locally or from the same domain.
   *
   * @param {boolean} value - The `withCredentials` value.
   * @return {Loader} A reference to this instance.
   */
  setWithCredentials(e) {
    return this.withCredentials = e, this;
  }
  /**
   * Sets the base path for the asset.
   *
   * @param {string} path - The base path.
   * @return {Loader} A reference to this instance.
   */
  setPath(e) {
    return this.path = e, this;
  }
  /**
   * Sets the base path for dependent resources like textures.
   *
   * @param {string} resourcePath - The resource path.
   * @return {Loader} A reference to this instance.
   */
  setResourcePath(e) {
    return this.resourcePath = e, this;
  }
  /**
   * Sets the given request header.
   *
   * @param {Object} requestHeader - A [request header]{@link https://developer.mozilla.org/en-US/docs/Glossary/Request_header}
   * for configuring the HTTP request.
   * @return {Loader} A reference to this instance.
   */
  setRequestHeader(e) {
    return this.requestHeader = e, this;
  }
  /**
   * This method can be implemented in loaders for aborting ongoing requests.
   *
   * @abstract
   * @return {Loader} A reference to this instance.
   */
  abort() {
    return this;
  }
}
gi.DEFAULT_MATERIAL_NAME = "__DEFAULT";
const dn = {};
class s0 extends Error {
  constructor(e, t) {
    super(e), this.response = t;
  }
}
class vn extends gi {
  /**
   * Constructs a new file loader.
   *
   * @param {LoadingManager} [manager] - The loading manager.
   */
  constructor(e) {
    super(e), this.mimeType = "", this.responseType = "", this._abortController = new AbortController();
  }
  /**
   * Starts loading from the given URL and pass the loaded response to the `onLoad()` callback.
   *
   * @param {string} url - The path/URL of the file to be loaded. This can also be a data URI.
   * @param {function(any)} onLoad - Executed when the loading process has been finished.
   * @param {onProgressCallback} [onProgress] - Executed while the loading is in progress.
   * @param {onErrorCallback} [onError] - Executed when errors occur.
   * @return {any|undefined} The cached resource if available.
   */
  load(e, t, i, n) {
    e === void 0 && (e = ""), this.path !== void 0 && (e = this.path + e), e = this.manager.resolveURL(e);
    const s = Qi.get(`file:${e}`);
    if (s !== void 0)
      return this.manager.itemStart(e), setTimeout(() => {
        t && t(s), this.manager.itemEnd(e);
      }, 0), s;
    if (dn[e] !== void 0) {
      dn[e].push({
        onLoad: t,
        onProgress: i,
        onError: n
      });
      return;
    }
    dn[e] = [], dn[e].push({
      onLoad: t,
      onProgress: i,
      onError: n
    });
    const a = new Request(e, {
      headers: new Headers(this.requestHeader),
      credentials: this.withCredentials ? "include" : "same-origin",
      signal: typeof AbortSignal.any == "function" ? AbortSignal.any([this._abortController.signal, this.manager.abortController.signal]) : this._abortController.signal
    }), o = this.mimeType, l = this.responseType;
    fetch(a).then((c) => {
      if (c.status === 200 || c.status === 0) {
        if (c.status === 0 && console.warn("THREE.FileLoader: HTTP Status 0 received."), typeof ReadableStream > "u" || c.body === void 0 || c.body.getReader === void 0)
          return c;
        const h = dn[e], d = c.body.getReader(), u = c.headers.get("X-File-Size") || c.headers.get("Content-Length"), p = u ? parseInt(u) : 0, m = p !== 0;
        let _ = 0;
        const g = new ReadableStream({
          start(f) {
            v();
            function v() {
              d.read().then(({ done: x, value: y }) => {
                if (x)
                  f.close();
                else {
                  _ += y.byteLength;
                  const A = new ProgressEvent("progress", { lengthComputable: m, loaded: _, total: p });
                  for (let S = 0, C = h.length; S < C; S++) {
                    const P = h[S];
                    P.onProgress && P.onProgress(A);
                  }
                  f.enqueue(y), v();
                }
              }, (x) => {
                f.error(x);
              });
            }
          }
        });
        return new Response(g);
      } else
        throw new s0(`fetch for "${c.url}" responded with ${c.status}: ${c.statusText}`, c);
    }).then((c) => {
      switch (l) {
        case "arraybuffer":
          return c.arrayBuffer();
        case "blob":
          return c.blob();
        case "document":
          return c.text().then((h) => new DOMParser().parseFromString(h, o));
        case "json":
          return c.json();
        default:
          if (o === "")
            return c.text();
          {
            const d = /charset="?([^;"\s]*)"?/i.exec(o), u = d && d[1] ? d[1].toLowerCase() : void 0, p = new TextDecoder(u);
            return c.arrayBuffer().then((m) => p.decode(m));
          }
      }
    }).then((c) => {
      Qi.add(`file:${e}`, c);
      const h = dn[e];
      delete dn[e];
      for (let d = 0, u = h.length; d < u; d++) {
        const p = h[d];
        p.onLoad && p.onLoad(c);
      }
    }).catch((c) => {
      const h = dn[e];
      if (h === void 0)
        throw this.manager.itemError(e), c;
      delete dn[e];
      for (let d = 0, u = h.length; d < u; d++) {
        const p = h[d];
        p.onError && p.onError(c);
      }
      this.manager.itemError(e);
    }).finally(() => {
      this.manager.itemEnd(e);
    }), this.manager.itemStart(e);
  }
  /**
   * Sets the expected response type.
   *
   * @param {('arraybuffer'|'blob'|'document'|'json'|'')} value - The response type.
   * @return {FileLoader} A reference to this file loader.
   */
  setResponseType(e) {
    return this.responseType = e, this;
  }
  /**
   * Sets the expected mime type of the loaded file.
   *
   * @param {string} value - The mime type.
   * @return {FileLoader} A reference to this file loader.
   */
  setMimeType(e) {
    return this.mimeType = e, this;
  }
  /**
   * Aborts ongoing fetch requests.
   *
   * @return {FileLoader} A reference to this instance.
   */
  abort() {
    return this._abortController.abort(), this._abortController = new AbortController(), this;
  }
}
class r0 extends gi {
  /**
   * Constructs a new animation loader.
   *
   * @param {LoadingManager} [manager] - The loading manager.
   */
  constructor(e) {
    super(e);
  }
  /**
   * Starts loading from the given URL and pass the loaded animations as an array
   * holding instances of {@link AnimationClip} to the `onLoad()` callback.
   *
   * @param {string} url - The path/URL of the file to be loaded. This can also be a data URI.
   * @param {function(Array<AnimationClip>)} onLoad - Executed when the loading process has been finished.
   * @param {onProgressCallback} onProgress - Executed while the loading is in progress.
   * @param {onErrorCallback} onError - Executed when errors occur.
   */
  load(e, t, i, n) {
    const s = this, a = new vn(this.manager);
    a.setPath(this.path), a.setRequestHeader(this.requestHeader), a.setWithCredentials(this.withCredentials), a.load(e, function(o) {
      try {
        t(s.parse(JSON.parse(o)));
      } catch (l) {
        n ? n(l) : console.error(l), s.manager.itemError(e);
      }
    }, i, n);
  }
  /**
   * Parses the given JSON object and returns an array of animation clips.
   *
   * @param {Object} json - The serialized animation clips.
   * @return {Array<AnimationClip>} The parsed animation clips.
   */
  parse(e) {
    const t = [];
    for (let i = 0; i < e.length; i++) {
      const n = yr.parse(e[i]);
      t.push(n);
    }
    return t;
  }
}
class a0 extends gi {
  /**
   * Constructs a new compressed texture loader.
   *
   * @param {LoadingManager} [manager] - The loading manager.
   */
  constructor(e) {
    super(e);
  }
  /**
   * Starts loading from the given URL and passes the loaded compressed texture
   * to the `onLoad()` callback. The method also returns a new texture object which can
   * directly be used for material creation. If you do it this way, the texture
   * may pop up in your scene once the respective loading process is finished.
   *
   * @param {string} url - The path/URL of the file to be loaded. This can also be a data URI.
   * @param {function(CompressedTexture)} onLoad - Executed when the loading process has been finished.
   * @param {onProgressCallback} onProgress - Executed while the loading is in progress.
   * @param {onErrorCallback} onError - Executed when errors occur.
   * @return {CompressedTexture} The compressed texture.
   */
  load(e, t, i, n) {
    const s = this, a = [], o = new ic(), l = new vn(this.manager);
    l.setPath(this.path), l.setResponseType("arraybuffer"), l.setRequestHeader(this.requestHeader), l.setWithCredentials(s.withCredentials);
    let c = 0;
    function h(d) {
      l.load(e[d], function(u) {
        const p = s.parse(u, !0);
        a[d] = {
          width: p.width,
          height: p.height,
          format: p.format,
          mipmaps: p.mipmaps
        }, c += 1, c === 6 && (p.mipmapCount === 1 && (o.minFilter = Pt), o.image = a, o.format = p.format, o.needsUpdate = !0, t && t(o));
      }, i, n);
    }
    if (Array.isArray(e))
      for (let d = 0, u = e.length; d < u; ++d)
        h(d);
    else
      l.load(e, function(d) {
        const u = s.parse(d, !0);
        if (u.isCubemap) {
          const p = u.mipmaps.length / u.mipmapCount;
          for (let m = 0; m < p; m++) {
            a[m] = { mipmaps: [] };
            for (let _ = 0; _ < u.mipmapCount; _++)
              a[m].mipmaps.push(u.mipmaps[m * u.mipmapCount + _]), a[m].format = u.format, a[m].width = u.width, a[m].height = u.height;
          }
          o.image = a;
        } else
          o.image.width = u.width, o.image.height = u.height, o.mipmaps = u.mipmaps;
        u.mipmapCount === 1 && (o.minFilter = Pt), o.format = u.format, o.needsUpdate = !0, t && t(o);
      }, i, n);
    return o;
  }
}
const Zs = /* @__PURE__ */ new WeakMap();
class ya extends gi {
  /**
   * Constructs a new image loader.
   *
   * @param {LoadingManager} [manager] - The loading manager.
   */
  constructor(e) {
    super(e);
  }
  /**
   * Starts loading from the given URL and passes the loaded image
   * to the `onLoad()` callback. The method also returns a new `Image` object which can
   * directly be used for texture creation. If you do it this way, the texture
   * may pop up in your scene once the respective loading process is finished.
   *
   * @param {string} url - The path/URL of the file to be loaded. This can also be a data URI.
   * @param {function(Image)} onLoad - Executed when the loading process has been finished.
   * @param {onProgressCallback} onProgress - Unsupported in this loader.
   * @param {onErrorCallback} onError - Executed when errors occur.
   * @return {Image} The image.
   */
  load(e, t, i, n) {
    this.path !== void 0 && (e = this.path + e), e = this.manager.resolveURL(e);
    const s = this, a = Qi.get(`image:${e}`);
    if (a !== void 0) {
      if (a.complete === !0)
        s.manager.itemStart(e), setTimeout(function() {
          t && t(a), s.manager.itemEnd(e);
        }, 0);
      else {
        let d = Zs.get(a);
        d === void 0 && (d = [], Zs.set(a, d)), d.push({ onLoad: t, onError: n });
      }
      return a;
    }
    const o = ua("img");
    function l() {
      h(), t && t(this);
      const d = Zs.get(this) || [];
      for (let u = 0; u < d.length; u++) {
        const p = d[u];
        p.onLoad && p.onLoad(this);
      }
      Zs.delete(this), s.manager.itemEnd(e);
    }
    function c(d) {
      h(), n && n(d), Qi.remove(`image:${e}`);
      const u = Zs.get(this) || [];
      for (let p = 0; p < u.length; p++) {
        const m = u[p];
        m.onError && m.onError(d);
      }
      Zs.delete(this), s.manager.itemError(e), s.manager.itemEnd(e);
    }
    function h() {
      o.removeEventListener("load", l, !1), o.removeEventListener("error", c, !1);
    }
    return o.addEventListener("load", l, !1), o.addEventListener("error", c, !1), e.slice(0, 5) !== "data:" && this.crossOrigin !== void 0 && (o.crossOrigin = this.crossOrigin), Qi.add(`image:${e}`, o), s.manager.itemStart(e), o.src = e, o;
  }
}
class o0 extends gi {
  /**
   * Constructs a new cube texture loader.
   *
   * @param {LoadingManager} [manager] - The loading manager.
   */
  constructor(e) {
    super(e);
  }
  /**
   * Starts loading from the given URL and pass the fully loaded cube texture
   * to the `onLoad()` callback. The method also returns a new cube texture object which can
   * directly be used for material creation. If you do it this way, the cube texture
   * may pop up in your scene once the respective loading process is finished.
   *
   * @param {Array<string>} urls - Array of 6 URLs to images, one for each side of the
   * cube texture. The urls should be specified in the following order: pos-x,
   * neg-x, pos-y, neg-y, pos-z, neg-z. An array of data URIs are allowed as well.
   * @param {function(CubeTexture)} onLoad - Executed when the loading process has been finished.
   * @param {onProgressCallback} onProgress - Unsupported in this loader.
   * @param {onErrorCallback} onError - Executed when errors occur.
   * @return {CubeTexture} The cube texture.
   */
  load(e, t, i, n) {
    const s = new Sa();
    s.colorSpace = Qt;
    const a = new ya(this.manager);
    a.setCrossOrigin(this.crossOrigin), a.setPath(this.path);
    let o = 0;
    function l(c) {
      a.load(e[c], function(h) {
        s.images[c] = h, o++, o === 6 && (s.needsUpdate = !0, t && t(s));
      }, void 0, n);
    }
    for (let c = 0; c < e.length; ++c)
      l(c);
    return s;
  }
}
class l0 extends gi {
  /**
   * Constructs a new data texture loader.
   *
   * @param {LoadingManager} [manager] - The loading manager.
   */
  constructor(e) {
    super(e);
  }
  /**
   * Starts loading from the given URL and passes the loaded data texture
   * to the `onLoad()` callback. The method also returns a new texture object which can
   * directly be used for material creation. If you do it this way, the texture
   * may pop up in your scene once the respective loading process is finished.
   *
   * @param {string} url - The path/URL of the file to be loaded. This can also be a data URI.
   * @param {function(DataTexture)} onLoad - Executed when the loading process has been finished.
   * @param {onProgressCallback} onProgress - Executed while the loading is in progress.
   * @param {onErrorCallback} onError - Executed when errors occur.
   * @return {DataTexture} The data texture.
   */
  load(e, t, i, n) {
    const s = this, a = new tn(), o = new vn(this.manager);
    return o.setResponseType("arraybuffer"), o.setRequestHeader(this.requestHeader), o.setPath(this.path), o.setWithCredentials(s.withCredentials), o.load(e, function(l) {
      let c;
      try {
        c = s.parse(l);
      } catch (h) {
        if (n !== void 0)
          n(h);
        else {
          console.error(h);
          return;
        }
      }
      c.image !== void 0 ? a.image = c.image : c.data !== void 0 && (a.image.width = c.width, a.image.height = c.height, a.image.data = c.data), a.wrapS = c.wrapS !== void 0 ? c.wrapS : fi, a.wrapT = c.wrapT !== void 0 ? c.wrapT : fi, a.magFilter = c.magFilter !== void 0 ? c.magFilter : Pt, a.minFilter = c.minFilter !== void 0 ? c.minFilter : Pt, a.anisotropy = c.anisotropy !== void 0 ? c.anisotropy : 1, c.colorSpace !== void 0 && (a.colorSpace = c.colorSpace), c.flipY !== void 0 && (a.flipY = c.flipY), c.format !== void 0 && (a.format = c.format), c.type !== void 0 && (a.type = c.type), c.mipmaps !== void 0 && (a.mipmaps = c.mipmaps, a.minFilter = Ji), c.mipmapCount === 1 && (a.minFilter = Pt), c.generateMipmaps !== void 0 && (a.generateMipmaps = c.generateMipmaps), a.needsUpdate = !0, t && t(a, c);
    }, i, n), a;
  }
}
class c0 extends gi {
  /**
   * Constructs a new texture loader.
   *
   * @param {LoadingManager} [manager] - The loading manager.
   */
  constructor(e) {
    super(e);
  }
  /**
   * Starts loading from the given URL and pass the fully loaded texture
   * to the `onLoad()` callback. The method also returns a new texture object which can
   * directly be used for material creation. If you do it this way, the texture
   * may pop up in your scene once the respective loading process is finished.
   *
   * @param {string} url - The path/URL of the file to be loaded. This can also be a data URI.
   * @param {function(Texture)} onLoad - Executed when the loading process has been finished.
   * @param {onProgressCallback} onProgress - Unsupported in this loader.
   * @param {onErrorCallback} onError - Executed when errors occur.
   * @return {Texture} The texture.
   */
  load(e, t, i, n) {
    const s = new Et(), a = new ya(this.manager);
    return a.setCrossOrigin(this.crossOrigin), a.setPath(this.path), a.load(e, function(o) {
      s.image = o, s.needsUpdate = !0, t !== void 0 && t(s);
    }, i, n), s;
  }
}
class Gn extends tt {
  /**
   * Constructs a new light.
   *
   * @param {(number|Color|string)} [color=0xffffff] - The light's color.
   * @param {number} [intensity=1] - The light's strength/intensity.
   */
  constructor(e, t = 1) {
    super(), this.isLight = !0, this.type = "Light", this.color = new oe(e), this.intensity = t;
  }
  /**
   * Frees the GPU-related resources allocated by this instance. Call this
   * method whenever this instance is no longer used in your app.
   */
  dispose() {
  }
  copy(e, t) {
    return super.copy(e, t), this.color.copy(e.color), this.intensity = e.intensity, this;
  }
  toJSON(e) {
    const t = super.toJSON(e);
    return t.object.color = this.color.getHex(), t.object.intensity = this.intensity, this.groundColor !== void 0 && (t.object.groundColor = this.groundColor.getHex()), this.distance !== void 0 && (t.object.distance = this.distance), this.angle !== void 0 && (t.object.angle = this.angle), this.decay !== void 0 && (t.object.decay = this.decay), this.penumbra !== void 0 && (t.object.penumbra = this.penumbra), this.shadow !== void 0 && (t.object.shadow = this.shadow.toJSON()), this.target !== void 0 && (t.object.target = this.target.uuid), t;
  }
}
class qm extends Gn {
  /**
   * Constructs a new hemisphere light.
   *
   * @param {(number|Color|string)} [skyColor=0xffffff] - The light's sky color.
   * @param {(number|Color|string)} [groundColor=0xffffff] - The light's ground color.
   * @param {number} [intensity=1] - The light's strength/intensity.
   */
  constructor(e, t, i) {
    super(e, i), this.isHemisphereLight = !0, this.type = "HemisphereLight", this.position.copy(tt.DEFAULT_UP), this.updateMatrix(), this.groundColor = new oe(t);
  }
  copy(e, t) {
    return super.copy(e, t), this.groundColor.copy(e.groundColor), this;
  }
}
const Kc = /* @__PURE__ */ new Ne(), Wu = /* @__PURE__ */ new b(), Xu = /* @__PURE__ */ new b();
class Ld {
  /**
   * Constructs a new light shadow.
   *
   * @param {Camera} camera - The light's view of the world.
   */
  constructor(e) {
    this.camera = e, this.intensity = 1, this.bias = 0, this.normalBias = 0, this.radius = 1, this.blurSamples = 8, this.mapSize = new H(512, 512), this.mapType = Hi, this.map = null, this.mapPass = null, this.matrix = new Ne(), this.autoUpdate = !0, this.needsUpdate = !1, this._frustum = new Sr(), this._frameExtents = new H(1, 1), this._viewportCount = 1, this._viewports = [
      new Ye(0, 0, 1, 1)
    ];
  }
  /**
   * Used internally by the renderer to get the number of viewports that need
   * to be rendered for this shadow.
   *
   * @return {number} The viewport count.
   */
  getViewportCount() {
    return this._viewportCount;
  }
  /**
   * Gets the shadow cameras frustum. Used internally by the renderer to cull objects.
   *
   * @return {Frustum} The shadow camera frustum.
   */
  getFrustum() {
    return this._frustum;
  }
  /**
   * Update the matrices for the camera and shadow, used internally by the renderer.
   *
   * @param {Light} light - The light for which the shadow is being rendered.
   */
  updateMatrices(e) {
    const t = this.camera, i = this.matrix;
    Wu.setFromMatrixPosition(e.matrixWorld), t.position.copy(Wu), Xu.setFromMatrixPosition(e.target.matrixWorld), t.lookAt(Xu), t.updateMatrixWorld(), Kc.multiplyMatrices(t.projectionMatrix, t.matrixWorldInverse), this._frustum.setFromProjectionMatrix(Kc, t.coordinateSystem, t.reversedDepth), t.reversedDepth ? i.set(
      0.5,
      0,
      0,
      0.5,
      0,
      0.5,
      0,
      0.5,
      0,
      0,
      1,
      0,
      0,
      0,
      0,
      1
    ) : i.set(
      0.5,
      0,
      0,
      0.5,
      0,
      0.5,
      0,
      0.5,
      0,
      0,
      0.5,
      0.5,
      0,
      0,
      0,
      1
    ), i.multiply(Kc);
  }
  /**
   * Returns a viewport definition for the given viewport index.
   *
   * @param {number} viewportIndex - The viewport index.
   * @return {Vector4} The viewport.
   */
  getViewport(e) {
    return this._viewports[e];
  }
  /**
   * Returns the frame extends.
   *
   * @return {Vector2} The frame extends.
   */
  getFrameExtents() {
    return this._frameExtents;
  }
  /**
   * Frees the GPU-related resources allocated by this instance. Call this
   * method whenever this instance is no longer used in your app.
   */
  dispose() {
    this.map && this.map.dispose(), this.mapPass && this.mapPass.dispose();
  }
  /**
   * Copies the values of the given light shadow instance to this instance.
   *
   * @param {LightShadow} source - The light shadow to copy.
   * @return {LightShadow} A reference to this light shadow instance.
   */
  copy(e) {
    return this.camera = e.camera.clone(), this.intensity = e.intensity, this.bias = e.bias, this.radius = e.radius, this.autoUpdate = e.autoUpdate, this.needsUpdate = e.needsUpdate, this.normalBias = e.normalBias, this.blurSamples = e.blurSamples, this.mapSize.copy(e.mapSize), this;
  }
  /**
   * Returns a new light shadow instance with copied values from this instance.
   *
   * @return {LightShadow} A clone of this instance.
   */
  clone() {
    return new this.constructor().copy(this);
  }
  /**
   * Serializes the light shadow into JSON.
   *
   * @return {Object} A JSON object representing the serialized light shadow.
   * @see {@link ObjectLoader#parse}
   */
  toJSON() {
    const e = {};
    return this.intensity !== 1 && (e.intensity = this.intensity), this.bias !== 0 && (e.bias = this.bias), this.normalBias !== 0 && (e.normalBias = this.normalBias), this.radius !== 1 && (e.radius = this.radius), (this.mapSize.x !== 512 || this.mapSize.y !== 512) && (e.mapSize = this.mapSize.toArray()), e.camera = this.camera.toJSON(!1).object, delete e.camera.matrix, e;
  }
}
class h0 extends Ld {
  /**
   * Constructs a new spot light shadow.
   */
  constructor() {
    super(new kt(50, 1, 0.5, 500)), this.isSpotLightShadow = !0, this.focus = 1, this.aspect = 1;
  }
  updateMatrices(e) {
    const t = this.camera, i = fr * 2 * e.angle * this.focus, n = this.mapSize.width / this.mapSize.height * this.aspect, s = e.distance || t.far;
    (i !== t.fov || n !== t.aspect || s !== t.far) && (t.fov = i, t.aspect = n, t.far = s, t.updateProjectionMatrix()), super.updateMatrices(e);
  }
  copy(e) {
    return super.copy(e), this.focus = e.focus, this;
  }
}
class Zm extends Gn {
  /**
   * Constructs a new spot light.
   *
   * @param {(number|Color|string)} [color=0xffffff] - The light's color.
   * @param {number} [intensity=1] - The light's strength/intensity measured in candela (cd).
   * @param {number} [distance=0] - Maximum range of the light. `0` means no limit.
   * @param {number} [angle=Math.PI/3] - Maximum angle of light dispersion from its direction whose upper bound is `Math.PI/2`.
   * @param {number} [penumbra=0] - Percent of the spotlight cone that is attenuated due to penumbra. Value range is `[0,1]`.
   * @param {number} [decay=2] - The amount the light dims along the distance of the light.
   */
  constructor(e, t, i = 0, n = Math.PI / 3, s = 0, a = 2) {
    super(e, t), this.isSpotLight = !0, this.type = "SpotLight", this.position.copy(tt.DEFAULT_UP), this.updateMatrix(), this.target = new tt(), this.distance = i, this.angle = n, this.penumbra = s, this.decay = a, this.map = null, this.shadow = new h0();
  }
  /**
   * The light's power. Power is the luminous power of the light measured in lumens (lm).
   *  Changing the power will also change the light's intensity.
   *
   * @type {number}
   */
  get power() {
    return this.intensity * Math.PI;
  }
  set power(e) {
    this.intensity = e / Math.PI;
  }
  dispose() {
    this.shadow.dispose();
  }
  copy(e, t) {
    return super.copy(e, t), this.distance = e.distance, this.angle = e.angle, this.penumbra = e.penumbra, this.decay = e.decay, this.target = e.target.clone(), this.shadow = e.shadow.clone(), this;
  }
}
const qu = /* @__PURE__ */ new Ne(), Br = /* @__PURE__ */ new b(), Jc = /* @__PURE__ */ new b();
class d0 extends Ld {
  /**
   * Constructs a new point light shadow.
   */
  constructor() {
    super(new kt(90, 1, 0.5, 500)), this.isPointLightShadow = !0, this._frameExtents = new H(4, 2), this._viewportCount = 6, this._viewports = [
      // These viewports map a cube-map onto a 2D texture with the
      // following orientation:
      //
      //  xzXZ
      //   y Y
      //
      // X - Positive x direction
      // x - Negative x direction
      // Y - Positive y direction
      // y - Negative y direction
      // Z - Positive z direction
      // z - Negative z direction
      // positive X
      new Ye(2, 1, 1, 1),
      // negative X
      new Ye(0, 1, 1, 1),
      // positive Z
      new Ye(3, 1, 1, 1),
      // negative Z
      new Ye(1, 1, 1, 1),
      // positive Y
      new Ye(3, 0, 1, 1),
      // negative Y
      new Ye(1, 0, 1, 1)
    ], this._cubeDirections = [
      new b(1, 0, 0),
      new b(-1, 0, 0),
      new b(0, 0, 1),
      new b(0, 0, -1),
      new b(0, 1, 0),
      new b(0, -1, 0)
    ], this._cubeUps = [
      new b(0, 1, 0),
      new b(0, 1, 0),
      new b(0, 1, 0),
      new b(0, 1, 0),
      new b(0, 0, 1),
      new b(0, 0, -1)
    ];
  }
  /**
   * Update the matrices for the camera and shadow, used internally by the renderer.
   *
   * @param {Light} light - The light for which the shadow is being rendered.
   * @param {number} [viewportIndex=0] - The viewport index.
   */
  updateMatrices(e, t = 0) {
    const i = this.camera, n = this.matrix, s = e.distance || i.far;
    s !== i.far && (i.far = s, i.updateProjectionMatrix()), Br.setFromMatrixPosition(e.matrixWorld), i.position.copy(Br), Jc.copy(i.position), Jc.add(this._cubeDirections[t]), i.up.copy(this._cubeUps[t]), i.lookAt(Jc), i.updateMatrixWorld(), n.makeTranslation(-Br.x, -Br.y, -Br.z), qu.multiplyMatrices(i.projectionMatrix, i.matrixWorldInverse), this._frustum.setFromProjectionMatrix(qu, i.coordinateSystem, i.reversedDepth);
  }
}
class Ym extends Gn {
  /**
   * Constructs a new point light.
   *
   * @param {(number|Color|string)} [color=0xffffff] - The light's color.
   * @param {number} [intensity=1] - The light's strength/intensity measured in candela (cd).
   * @param {number} [distance=0] - Maximum range of the light. `0` means no limit.
   * @param {number} [decay=2] - The amount the light dims along the distance of the light.
   */
  constructor(e, t, i = 0, n = 2) {
    super(e, t), this.isPointLight = !0, this.type = "PointLight", this.distance = i, this.decay = n, this.shadow = new d0();
  }
  /**
   * The light's power. Power is the luminous power of the light measured in lumens (lm).
   * Changing the power will also change the light's intensity.
   *
   * @type {number}
   */
  get power() {
    return this.intensity * 4 * Math.PI;
  }
  set power(e) {
    this.intensity = e / (4 * Math.PI);
  }
  dispose() {
    this.shadow.dispose();
  }
  copy(e, t) {
    return super.copy(e, t), this.distance = e.distance, this.decay = e.decay, this.shadow = e.shadow.clone(), this;
  }
}
class kn extends Yl {
  /**
   * Constructs a new orthographic camera.
   *
   * @param {number} [left=-1] - The left plane of the camera's frustum.
   * @param {number} [right=1] - The right plane of the camera's frustum.
   * @param {number} [top=1] - The top plane of the camera's frustum.
   * @param {number} [bottom=-1] - The bottom plane of the camera's frustum.
   * @param {number} [near=0.1] - The camera's near plane.
   * @param {number} [far=2000] - The camera's far plane.
   */
  constructor(e = -1, t = 1, i = 1, n = -1, s = 0.1, a = 2e3) {
    super(), this.isOrthographicCamera = !0, this.type = "OrthographicCamera", this.zoom = 1, this.view = null, this.left = e, this.right = t, this.top = i, this.bottom = n, this.near = s, this.far = a, this.updateProjectionMatrix();
  }
  copy(e, t) {
    return super.copy(e, t), this.left = e.left, this.right = e.right, this.top = e.top, this.bottom = e.bottom, this.near = e.near, this.far = e.far, this.zoom = e.zoom, this.view = e.view === null ? null : Object.assign({}, e.view), this;
  }
  /**
   * Sets an offset in a larger frustum. This is useful for multi-window or
   * multi-monitor/multi-machine setups.
   *
   * @param {number} fullWidth - The full width of multiview setup.
   * @param {number} fullHeight - The full height of multiview setup.
   * @param {number} x - The horizontal offset of the subcamera.
   * @param {number} y - The vertical offset of the subcamera.
   * @param {number} width - The width of subcamera.
   * @param {number} height - The height of subcamera.
   * @see {@link PerspectiveCamera#setViewOffset}
   */
  setViewOffset(e, t, i, n, s, a) {
    this.view === null && (this.view = {
      enabled: !0,
      fullWidth: 1,
      fullHeight: 1,
      offsetX: 0,
      offsetY: 0,
      width: 1,
      height: 1
    }), this.view.enabled = !0, this.view.fullWidth = e, this.view.fullHeight = t, this.view.offsetX = i, this.view.offsetY = n, this.view.width = s, this.view.height = a, this.updateProjectionMatrix();
  }
  /**
   * Removes the view offset from the projection matrix.
   */
  clearViewOffset() {
    this.view !== null && (this.view.enabled = !1), this.updateProjectionMatrix();
  }
  /**
   * Updates the camera's projection matrix. Must be called after any change of
   * camera properties.
   */
  updateProjectionMatrix() {
    const e = (this.right - this.left) / (2 * this.zoom), t = (this.top - this.bottom) / (2 * this.zoom), i = (this.right + this.left) / 2, n = (this.top + this.bottom) / 2;
    let s = i - e, a = i + e, o = n + t, l = n - t;
    if (this.view !== null && this.view.enabled) {
      const c = (this.right - this.left) / this.view.fullWidth / this.zoom, h = (this.top - this.bottom) / this.view.fullHeight / this.zoom;
      s += c * this.view.offsetX, a = s + c * this.view.width, o -= h * this.view.offsetY, l = o - h * this.view.height;
    }
    this.projectionMatrix.makeOrthographic(s, a, o, l, this.near, this.far, this.coordinateSystem, this.reversedDepth), this.projectionMatrixInverse.copy(this.projectionMatrix).invert();
  }
  toJSON(e) {
    const t = super.toJSON(e);
    return t.object.zoom = this.zoom, t.object.left = this.left, t.object.right = this.right, t.object.top = this.top, t.object.bottom = this.bottom, t.object.near = this.near, t.object.far = this.far, this.view !== null && (t.object.view = Object.assign({}, this.view)), t;
  }
}
class u0 extends Ld {
  /**
   * Constructs a new directional light shadow.
   */
  constructor() {
    super(new kn(-5, 5, 5, -5, 0.5, 500)), this.isDirectionalLightShadow = !0;
  }
}
class Id extends Gn {
  /**
   * Constructs a new directional light.
   *
   * @param {(number|Color|string)} [color=0xffffff] - The light's color.
   * @param {number} [intensity=1] - The light's strength/intensity.
   */
  constructor(e, t) {
    super(e, t), this.isDirectionalLight = !0, this.type = "DirectionalLight", this.position.copy(tt.DEFAULT_UP), this.updateMatrix(), this.target = new tt(), this.shadow = new u0();
  }
  dispose() {
    this.shadow.dispose();
  }
  copy(e) {
    return super.copy(e), this.target = e.target.clone(), this.shadow = e.shadow.clone(), this;
  }
}
class Dd extends Gn {
  /**
   * Constructs a new ambient light.
   *
   * @param {(number|Color|string)} [color=0xffffff] - The light's color.
   * @param {number} [intensity=1] - The light's strength/intensity.
   */
  constructor(e, t) {
    super(e, t), this.isAmbientLight = !0, this.type = "AmbientLight";
  }
}
class jm extends Gn {
  /**
   * Constructs a new area light.
   *
   * @param {(number|Color|string)} [color=0xffffff] - The light's color.
   * @param {number} [intensity=1] - The light's strength/intensity.
   * @param {number} [width=10] - The width of the light.
   * @param {number} [height=10] - The height of the light.
   */
  constructor(e, t, i = 10, n = 10) {
    super(e, t), this.isRectAreaLight = !0, this.type = "RectAreaLight", this.width = i, this.height = n;
  }
  /**
   * The light's power. Power is the luminous power of the light measured in lumens (lm).
   * Changing the power will also change the light's intensity.
   *
   * @type {number}
   */
  get power() {
    return this.intensity * this.width * this.height * Math.PI;
  }
  set power(e) {
    this.intensity = e / (this.width * this.height * Math.PI);
  }
  copy(e) {
    return super.copy(e), this.width = e.width, this.height = e.height, this;
  }
  toJSON(e) {
    const t = super.toJSON(e);
    return t.object.width = this.width, t.object.height = this.height, t;
  }
}
class $m {
  /**
   * Constructs a new spherical harmonics.
   */
  constructor() {
    this.isSphericalHarmonics3 = !0, this.coefficients = [];
    for (let e = 0; e < 9; e++)
      this.coefficients.push(new b());
  }
  /**
   * Sets the given SH coefficients to this instance by copying
   * the values.
   *
   * @param {Array<Vector3>} coefficients - The SH coefficients.
   * @return {SphericalHarmonics3} A reference to this spherical harmonics.
   */
  set(e) {
    for (let t = 0; t < 9; t++)
      this.coefficients[t].copy(e[t]);
    return this;
  }
  /**
   * Sets all SH coefficients to `0`.
   *
   * @return {SphericalHarmonics3} A reference to this spherical harmonics.
   */
  zero() {
    for (let e = 0; e < 9; e++)
      this.coefficients[e].set(0, 0, 0);
    return this;
  }
  /**
   * Returns the radiance in the direction of the given normal.
   *
   * @param {Vector3} normal - The normal vector (assumed to be unit length)
   * @param {Vector3} target - The target vector that is used to store the method's result.
   * @return {Vector3} The radiance.
   */
  getAt(e, t) {
    const i = e.x, n = e.y, s = e.z, a = this.coefficients;
    return t.copy(a[0]).multiplyScalar(0.282095), t.addScaledVector(a[1], 0.488603 * n), t.addScaledVector(a[2], 0.488603 * s), t.addScaledVector(a[3], 0.488603 * i), t.addScaledVector(a[4], 1.092548 * (i * n)), t.addScaledVector(a[5], 1.092548 * (n * s)), t.addScaledVector(a[6], 0.315392 * (3 * s * s - 1)), t.addScaledVector(a[7], 1.092548 * (i * s)), t.addScaledVector(a[8], 0.546274 * (i * i - n * n)), t;
  }
  /**
   * Returns the irradiance (radiance convolved with cosine lobe) in the
   * direction of the given normal.
   *
   * @param {Vector3} normal - The normal vector (assumed to be unit length)
   * @param {Vector3} target - The target vector that is used to store the method's result.
   * @return {Vector3} The irradiance.
   */
  getIrradianceAt(e, t) {
    const i = e.x, n = e.y, s = e.z, a = this.coefficients;
    return t.copy(a[0]).multiplyScalar(0.886227), t.addScaledVector(a[1], 2 * 0.511664 * n), t.addScaledVector(a[2], 2 * 0.511664 * s), t.addScaledVector(a[3], 2 * 0.511664 * i), t.addScaledVector(a[4], 2 * 0.429043 * i * n), t.addScaledVector(a[5], 2 * 0.429043 * n * s), t.addScaledVector(a[6], 0.743125 * s * s - 0.247708), t.addScaledVector(a[7], 2 * 0.429043 * i * s), t.addScaledVector(a[8], 0.429043 * (i * i - n * n)), t;
  }
  /**
   * Adds the given SH to this instance.
   *
   * @param {SphericalHarmonics3} sh - The SH to add.
   * @return {SphericalHarmonics3} A reference to this spherical harmonics.
   */
  add(e) {
    for (let t = 0; t < 9; t++)
      this.coefficients[t].add(e.coefficients[t]);
    return this;
  }
  /**
   * A convenience method for performing {@link SphericalHarmonics3#add} and
   * {@link SphericalHarmonics3#scale} at once.
   *
   * @param {SphericalHarmonics3} sh - The SH to add.
   * @param {number} s - The scale factor.
   * @return {SphericalHarmonics3} A reference to this spherical harmonics.
   */
  addScaledSH(e, t) {
    for (let i = 0; i < 9; i++)
      this.coefficients[i].addScaledVector(e.coefficients[i], t);
    return this;
  }
  /**
   * Scales this SH by the given scale factor.
   *
   * @param {number} s - The scale factor.
   * @return {SphericalHarmonics3} A reference to this spherical harmonics.
   */
  scale(e) {
    for (let t = 0; t < 9; t++)
      this.coefficients[t].multiplyScalar(e);
    return this;
  }
  /**
   * Linear interpolates between the given SH and this instance by the given
   * alpha factor.
   *
   * @param {SphericalHarmonics3} sh - The SH to interpolate with.
   * @param {number} alpha - The alpha factor.
   * @return {SphericalHarmonics3} A reference to this spherical harmonics.
   */
  lerp(e, t) {
    for (let i = 0; i < 9; i++)
      this.coefficients[i].lerp(e.coefficients[i], t);
    return this;
  }
  /**
   * Returns `true` if this spherical harmonics is equal with the given one.
   *
   * @param {SphericalHarmonics3} sh - The spherical harmonics to test for equality.
   * @return {boolean} Whether this spherical harmonics is equal with the given one.
   */
  equals(e) {
    for (let t = 0; t < 9; t++)
      if (!this.coefficients[t].equals(e.coefficients[t]))
        return !1;
    return !0;
  }
  /**
   * Copies the values of the given spherical harmonics to this instance.
   *
   * @param {SphericalHarmonics3} sh - The spherical harmonics to copy.
   * @return {SphericalHarmonics3} A reference to this spherical harmonics.
   */
  copy(e) {
    return this.set(e.coefficients);
  }
  /**
   * Returns a new spherical harmonics with copied values from this instance.
   *
   * @return {SphericalHarmonics3} A clone of this instance.
   */
  clone() {
    return new this.constructor().copy(this);
  }
  /**
   * Sets the SH coefficients of this instance from the given array.
   *
   * @param {Array<number>} array - An array holding the SH coefficients.
   * @param {number} [offset=0] - The array offset where to start copying.
   * @return {SphericalHarmonics3} A clone of this instance.
   */
  fromArray(e, t = 0) {
    const i = this.coefficients;
    for (let n = 0; n < 9; n++)
      i[n].fromArray(e, t + n * 3);
    return this;
  }
  /**
   * Returns an array with the SH coefficients, or copies them into the provided
   * array. The coefficients are represented as numbers.
   *
   * @param {Array<number>} [array=[]] - The target array.
   * @param {number} [offset=0] - The array offset where to start copying.
   * @return {Array<number>} An array with flat SH coefficients.
   */
  toArray(e = [], t = 0) {
    const i = this.coefficients;
    for (let n = 0; n < 9; n++)
      i[n].toArray(e, t + n * 3);
    return e;
  }
  /**
   * Computes the SH basis for the given normal vector.
   *
   * @param {Vector3} normal - The normal.
   * @param {Array<number>} shBasis - The target array holding the SH basis.
   */
  static getBasisAt(e, t) {
    const i = e.x, n = e.y, s = e.z;
    t[0] = 0.282095, t[1] = 0.488603 * n, t[2] = 0.488603 * s, t[3] = 0.488603 * i, t[4] = 1.092548 * i * n, t[5] = 1.092548 * n * s, t[6] = 0.315392 * (3 * s * s - 1), t[7] = 1.092548 * i * s, t[8] = 0.546274 * (i * i - n * n);
  }
}
class Km extends Gn {
  /**
   * Constructs a new light probe.
   *
   * @param {SphericalHarmonics3} sh - The spherical harmonics which represents encoded lighting information.
   * @param {number} [intensity=1] - The light's strength/intensity.
   */
  constructor(e = new $m(), t = 1) {
    super(void 0, t), this.isLightProbe = !0, this.sh = e;
  }
  copy(e) {
    return super.copy(e), this.sh.copy(e.sh), this;
  }
  /**
   * Deserializes the light prove from the given JSON.
   *
   * @param {Object} json - The JSON holding the serialized light probe.
   * @return {LightProbe} A reference to this light probe.
   */
  fromJSON(e) {
    return this.intensity = e.intensity, this.sh.fromArray(e.sh), this;
  }
  toJSON(e) {
    const t = super.toJSON(e);
    return t.object.sh = this.sh.toArray(), t;
  }
}
class fc extends gi {
  /**
   * Constructs a new material loader.
   *
   * @param {LoadingManager} [manager] - The loading manager.
   */
  constructor(e) {
    super(e), this.textures = {};
  }
  /**
   * Starts loading from the given URL and pass the loaded material to the `onLoad()` callback.
   *
   * @param {string} url - The path/URL of the file to be loaded. This can also be a data URI.
   * @param {function(Material)} onLoad - Executed when the loading process has been finished.
   * @param {onProgressCallback} onProgress - Executed while the loading is in progress.
   * @param {onErrorCallback} onError - Executed when errors occur.
   */
  load(e, t, i, n) {
    const s = this, a = new vn(s.manager);
    a.setPath(s.path), a.setRequestHeader(s.requestHeader), a.setWithCredentials(s.withCredentials), a.load(e, function(o) {
      try {
        t(s.parse(JSON.parse(o)));
      } catch (l) {
        n ? n(l) : console.error(l), s.manager.itemError(e);
      }
    }, i, n);
  }
  /**
   * Parses the given JSON object and returns a material.
   *
   * @param {Object} json - The serialized material.
   * @return {Material} The parsed material.
   */
  parse(e) {
    const t = this.textures;
    function i(s) {
      return t[s] === void 0 && console.warn("THREE.MaterialLoader: Undefined texture", s), t[s];
    }
    const n = this.createMaterialFromType(e.type);
    if (e.uuid !== void 0 && (n.uuid = e.uuid), e.name !== void 0 && (n.name = e.name), e.color !== void 0 && n.color !== void 0 && n.color.setHex(e.color), e.roughness !== void 0 && (n.roughness = e.roughness), e.metalness !== void 0 && (n.metalness = e.metalness), e.sheen !== void 0 && (n.sheen = e.sheen), e.sheenColor !== void 0 && (n.sheenColor = new oe().setHex(e.sheenColor)), e.sheenRoughness !== void 0 && (n.sheenRoughness = e.sheenRoughness), e.emissive !== void 0 && n.emissive !== void 0 && n.emissive.setHex(e.emissive), e.specular !== void 0 && n.specular !== void 0 && n.specular.setHex(e.specular), e.specularIntensity !== void 0 && (n.specularIntensity = e.specularIntensity), e.specularColor !== void 0 && n.specularColor !== void 0 && n.specularColor.setHex(e.specularColor), e.shininess !== void 0 && (n.shininess = e.shininess), e.clearcoat !== void 0 && (n.clearcoat = e.clearcoat), e.clearcoatRoughness !== void 0 && (n.clearcoatRoughness = e.clearcoatRoughness), e.dispersion !== void 0 && (n.dispersion = e.dispersion), e.iridescence !== void 0 && (n.iridescence = e.iridescence), e.iridescenceIOR !== void 0 && (n.iridescenceIOR = e.iridescenceIOR), e.iridescenceThicknessRange !== void 0 && (n.iridescenceThicknessRange = e.iridescenceThicknessRange), e.transmission !== void 0 && (n.transmission = e.transmission), e.thickness !== void 0 && (n.thickness = e.thickness), e.attenuationDistance !== void 0 && (n.attenuationDistance = e.attenuationDistance), e.attenuationColor !== void 0 && n.attenuationColor !== void 0 && n.attenuationColor.setHex(e.attenuationColor), e.anisotropy !== void 0 && (n.anisotropy = e.anisotropy), e.anisotropyRotation !== void 0 && (n.anisotropyRotation = e.anisotropyRotation), e.fog !== void 0 && (n.fog = e.fog), e.flatShading !== void 0 && (n.flatShading = e.flatShading), e.blending !== void 0 && (n.blending = e.blending), e.combine !== void 0 && (n.combine = e.combine), e.side !== void 0 && (n.side = e.side), e.shadowSide !== void 0 && (n.shadowSide = e.shadowSide), e.opacity !== void 0 && (n.opacity = e.opacity), e.transparent !== void 0 && (n.transparent = e.transparent), e.alphaTest !== void 0 && (n.alphaTest = e.alphaTest), e.alphaHash !== void 0 && (n.alphaHash = e.alphaHash), e.depthFunc !== void 0 && (n.depthFunc = e.depthFunc), e.depthTest !== void 0 && (n.depthTest = e.depthTest), e.depthWrite !== void 0 && (n.depthWrite = e.depthWrite), e.colorWrite !== void 0 && (n.colorWrite = e.colorWrite), e.blendSrc !== void 0 && (n.blendSrc = e.blendSrc), e.blendDst !== void 0 && (n.blendDst = e.blendDst), e.blendEquation !== void 0 && (n.blendEquation = e.blendEquation), e.blendSrcAlpha !== void 0 && (n.blendSrcAlpha = e.blendSrcAlpha), e.blendDstAlpha !== void 0 && (n.blendDstAlpha = e.blendDstAlpha), e.blendEquationAlpha !== void 0 && (n.blendEquationAlpha = e.blendEquationAlpha), e.blendColor !== void 0 && n.blendColor !== void 0 && n.blendColor.setHex(e.blendColor), e.blendAlpha !== void 0 && (n.blendAlpha = e.blendAlpha), e.stencilWriteMask !== void 0 && (n.stencilWriteMask = e.stencilWriteMask), e.stencilFunc !== void 0 && (n.stencilFunc = e.stencilFunc), e.stencilRef !== void 0 && (n.stencilRef = e.stencilRef), e.stencilFuncMask !== void 0 && (n.stencilFuncMask = e.stencilFuncMask), e.stencilFail !== void 0 && (n.stencilFail = e.stencilFail), e.stencilZFail !== void 0 && (n.stencilZFail = e.stencilZFail), e.stencilZPass !== void 0 && (n.stencilZPass = e.stencilZPass), e.stencilWrite !== void 0 && (n.stencilWrite = e.stencilWrite), e.wireframe !== void 0 && (n.wireframe = e.wireframe), e.wireframeLinewidth !== void 0 && (n.wireframeLinewidth = e.wireframeLinewidth), e.wireframeLinecap !== void 0 && (n.wireframeLinecap = e.wireframeLinecap), e.wireframeLinejoin !== void 0 && (n.wireframeLinejoin = e.wireframeLinejoin), e.rotation !== void 0 && (n.rotation = e.rotation), e.linewidth !== void 0 && (n.linewidth = e.linewidth), e.dashSize !== void 0 && (n.dashSize = e.dashSize), e.gapSize !== void 0 && (n.gapSize = e.gapSize), e.scale !== void 0 && (n.scale = e.scale), e.polygonOffset !== void 0 && (n.polygonOffset = e.polygonOffset), e.polygonOffsetFactor !== void 0 && (n.polygonOffsetFactor = e.polygonOffsetFactor), e.polygonOffsetUnits !== void 0 && (n.polygonOffsetUnits = e.polygonOffsetUnits), e.dithering !== void 0 && (n.dithering = e.dithering), e.alphaToCoverage !== void 0 && (n.alphaToCoverage = e.alphaToCoverage), e.premultipliedAlpha !== void 0 && (n.premultipliedAlpha = e.premultipliedAlpha), e.forceSinglePass !== void 0 && (n.forceSinglePass = e.forceSinglePass), e.visible !== void 0 && (n.visible = e.visible), e.toneMapped !== void 0 && (n.toneMapped = e.toneMapped), e.userData !== void 0 && (n.userData = e.userData), e.vertexColors !== void 0 && (typeof e.vertexColors == "number" ? n.vertexColors = e.vertexColors > 0 : n.vertexColors = e.vertexColors), e.uniforms !== void 0)
      for (const s in e.uniforms) {
        const a = e.uniforms[s];
        switch (n.uniforms[s] = {}, a.type) {
          case "t":
            n.uniforms[s].value = i(a.value);
            break;
          case "c":
            n.uniforms[s].value = new oe().setHex(a.value);
            break;
          case "v2":
            n.uniforms[s].value = new H().fromArray(a.value);
            break;
          case "v3":
            n.uniforms[s].value = new b().fromArray(a.value);
            break;
          case "v4":
            n.uniforms[s].value = new Ye().fromArray(a.value);
            break;
          case "m3":
            n.uniforms[s].value = new He().fromArray(a.value);
            break;
          case "m4":
            n.uniforms[s].value = new Ne().fromArray(a.value);
            break;
          default:
            n.uniforms[s].value = a.value;
        }
      }
    if (e.defines !== void 0 && (n.defines = e.defines), e.vertexShader !== void 0 && (n.vertexShader = e.vertexShader), e.fragmentShader !== void 0 && (n.fragmentShader = e.fragmentShader), e.glslVersion !== void 0 && (n.glslVersion = e.glslVersion), e.extensions !== void 0)
      for (const s in e.extensions)
        n.extensions[s] = e.extensions[s];
    if (e.lights !== void 0 && (n.lights = e.lights), e.clipping !== void 0 && (n.clipping = e.clipping), e.size !== void 0 && (n.size = e.size), e.sizeAttenuation !== void 0 && (n.sizeAttenuation = e.sizeAttenuation), e.map !== void 0 && (n.map = i(e.map)), e.matcap !== void 0 && (n.matcap = i(e.matcap)), e.alphaMap !== void 0 && (n.alphaMap = i(e.alphaMap)), e.bumpMap !== void 0 && (n.bumpMap = i(e.bumpMap)), e.bumpScale !== void 0 && (n.bumpScale = e.bumpScale), e.normalMap !== void 0 && (n.normalMap = i(e.normalMap)), e.normalMapType !== void 0 && (n.normalMapType = e.normalMapType), e.normalScale !== void 0) {
      let s = e.normalScale;
      Array.isArray(s) === !1 && (s = [s, s]), n.normalScale = new H().fromArray(s);
    }
    return e.displacementMap !== void 0 && (n.displacementMap = i(e.displacementMap)), e.displacementScale !== void 0 && (n.displacementScale = e.displacementScale), e.displacementBias !== void 0 && (n.displacementBias = e.displacementBias), e.roughnessMap !== void 0 && (n.roughnessMap = i(e.roughnessMap)), e.metalnessMap !== void 0 && (n.metalnessMap = i(e.metalnessMap)), e.emissiveMap !== void 0 && (n.emissiveMap = i(e.emissiveMap)), e.emissiveIntensity !== void 0 && (n.emissiveIntensity = e.emissiveIntensity), e.specularMap !== void 0 && (n.specularMap = i(e.specularMap)), e.specularIntensityMap !== void 0 && (n.specularIntensityMap = i(e.specularIntensityMap)), e.specularColorMap !== void 0 && (n.specularColorMap = i(e.specularColorMap)), e.envMap !== void 0 && (n.envMap = i(e.envMap)), e.envMapRotation !== void 0 && n.envMapRotation.fromArray(e.envMapRotation), e.envMapIntensity !== void 0 && (n.envMapIntensity = e.envMapIntensity), e.reflectivity !== void 0 && (n.reflectivity = e.reflectivity), e.refractionRatio !== void 0 && (n.refractionRatio = e.refractionRatio), e.lightMap !== void 0 && (n.lightMap = i(e.lightMap)), e.lightMapIntensity !== void 0 && (n.lightMapIntensity = e.lightMapIntensity), e.aoMap !== void 0 && (n.aoMap = i(e.aoMap)), e.aoMapIntensity !== void 0 && (n.aoMapIntensity = e.aoMapIntensity), e.gradientMap !== void 0 && (n.gradientMap = i(e.gradientMap)), e.clearcoatMap !== void 0 && (n.clearcoatMap = i(e.clearcoatMap)), e.clearcoatRoughnessMap !== void 0 && (n.clearcoatRoughnessMap = i(e.clearcoatRoughnessMap)), e.clearcoatNormalMap !== void 0 && (n.clearcoatNormalMap = i(e.clearcoatNormalMap)), e.clearcoatNormalScale !== void 0 && (n.clearcoatNormalScale = new H().fromArray(e.clearcoatNormalScale)), e.iridescenceMap !== void 0 && (n.iridescenceMap = i(e.iridescenceMap)), e.iridescenceThicknessMap !== void 0 && (n.iridescenceThicknessMap = i(e.iridescenceThicknessMap)), e.transmissionMap !== void 0 && (n.transmissionMap = i(e.transmissionMap)), e.thicknessMap !== void 0 && (n.thicknessMap = i(e.thicknessMap)), e.anisotropyMap !== void 0 && (n.anisotropyMap = i(e.anisotropyMap)), e.sheenColorMap !== void 0 && (n.sheenColorMap = i(e.sheenColorMap)), e.sheenRoughnessMap !== void 0 && (n.sheenRoughnessMap = i(e.sheenRoughnessMap)), n;
  }
  /**
   * Textures are not embedded in the material JSON so they have
   * to be injected before the loading process starts.
   *
   * @param {Object} value - A dictionary holding textures for material properties.
   * @return {MaterialLoader} A reference to this material loader.
   */
  setTextures(e) {
    return this.textures = e, this;
  }
  /**
   * Creates a material for the given type.
   *
   * @param {string} type - The material type.
   * @return {Material} The new material.
   */
  createMaterialFromType(e) {
    return fc.createMaterialFromType(e);
  }
  /**
   * Creates a material for the given type.
   *
   * @static
   * @param {string} type - The material type.
   * @return {Material} The new material.
   */
  static createMaterialFromType(e) {
    const t = {
      ShadowMaterial: Im,
      SpriteMaterial: Jl,
      RawShaderMaterial: Dm,
      ShaderMaterial: Ci,
      PointsMaterial: tc,
      MeshPhysicalMaterial: Nm,
      MeshStandardMaterial: Bn,
      MeshPhongMaterial: Um,
      MeshToonMaterial: Om,
      MeshNormalMaterial: Fm,
      MeshLambertMaterial: Bm,
      MeshDepthMaterial: wd,
      MeshDistanceMaterial: Ed,
      MeshBasicMaterial: Ht,
      MeshMatcapMaterial: km,
      LineDashedMaterial: Td,
      LineBasicMaterial: It,
      Material: qt
    };
    return new t[e]();
  }
}
class zh {
  /**
   * Extracts the base URL from the given URL.
   *
   * @param {string} url -The URL to extract the base URL from.
   * @return {string} The extracted base URL.
   */
  static extractUrlBase(e) {
    const t = e.lastIndexOf("/");
    return t === -1 ? "./" : e.slice(0, t + 1);
  }
  /**
   * Resolves relative URLs against the given path. Absolute paths, data urls,
   * and blob URLs will be returned as is. Invalid URLs will return an empty
   * string.
   *
   * @param {string} url -The URL to resolve.
   * @param {string} path - The base path for relative URLs to be resolved against.
   * @return {string} The resolved URL.
   */
  static resolveURL(e, t) {
    return typeof e != "string" || e === "" ? "" : (/^https?:\/\//i.test(t) && /^\//.test(e) && (t = t.replace(/(^https?:\/\/[^\/]+).*/i, "$1")), /^(https?:)?\/\//i.test(e) || /^data:.*,.*$/i.test(e) || /^blob:.*$/i.test(e) ? e : t + e);
  }
}
class mc extends Ue {
  /**
   * Constructs a new instanced buffer geometry.
   */
  constructor() {
    super(), this.isInstancedBufferGeometry = !0, this.type = "InstancedBufferGeometry", this.instanceCount = 1 / 0;
  }
  copy(e) {
    return super.copy(e), this.instanceCount = e.instanceCount, this;
  }
  toJSON() {
    const e = super.toJSON();
    return e.instanceCount = this.instanceCount, e.isInstancedBufferGeometry = !0, e;
  }
}
class Jm extends gi {
  /**
   * Constructs a new geometry loader.
   *
   * @param {LoadingManager} [manager] - The loading manager.
   */
  constructor(e) {
    super(e);
  }
  /**
   * Starts loading from the given URL and pass the loaded geometry to the `onLoad()` callback.
   *
   * @param {string} url - The path/URL of the file to be loaded. This can also be a data URI.
   * @param {function(BufferGeometry)} onLoad - Executed when the loading process has been finished.
   * @param {onProgressCallback} onProgress - Executed while the loading is in progress.
   * @param {onErrorCallback} onError - Executed when errors occur.
   */
  load(e, t, i, n) {
    const s = this, a = new vn(s.manager);
    a.setPath(s.path), a.setRequestHeader(s.requestHeader), a.setWithCredentials(s.withCredentials), a.load(e, function(o) {
      try {
        t(s.parse(JSON.parse(o)));
      } catch (l) {
        n ? n(l) : console.error(l), s.manager.itemError(e);
      }
    }, i, n);
  }
  /**
   * Parses the given JSON object and returns a geometry.
   *
   * @param {Object} json - The serialized geometry.
   * @return {BufferGeometry} The parsed geometry.
   */
  parse(e) {
    const t = {}, i = {};
    function n(p, m) {
      if (t[m] !== void 0) return t[m];
      const g = p.interleavedBuffers[m], f = s(p, g.buffer), v = sr(g.type, f), x = new Kl(v, g.stride);
      return x.uuid = g.uuid, t[m] = x, x;
    }
    function s(p, m) {
      if (i[m] !== void 0) return i[m];
      const g = p.arrayBuffers[m], f = new Uint32Array(g).buffer;
      return i[m] = f, f;
    }
    const a = e.isInstancedBufferGeometry ? new mc() : new Ue(), o = e.data.index;
    if (o !== void 0) {
      const p = sr(o.type, o.array);
      a.setIndex(new it(p, 1));
    }
    const l = e.data.attributes;
    for (const p in l) {
      const m = l[p];
      let _;
      if (m.isInterleavedBufferAttribute) {
        const g = n(e.data, m.data);
        _ = new Ei(g, m.itemSize, m.offset, m.normalized);
      } else {
        const g = sr(m.type, m.array), f = m.isInstancedBufferAttribute ? gr : it;
        _ = new f(g, m.itemSize, m.normalized);
      }
      m.name !== void 0 && (_.name = m.name), m.usage !== void 0 && _.setUsage(m.usage), a.setAttribute(p, _);
    }
    const c = e.data.morphAttributes;
    if (c)
      for (const p in c) {
        const m = c[p], _ = [];
        for (let g = 0, f = m.length; g < f; g++) {
          const v = m[g];
          let x;
          if (v.isInterleavedBufferAttribute) {
            const y = n(e.data, v.data);
            x = new Ei(y, v.itemSize, v.offset, v.normalized);
          } else {
            const y = sr(v.type, v.array);
            x = new it(y, v.itemSize, v.normalized);
          }
          v.name !== void 0 && (x.name = v.name), _.push(x);
        }
        a.morphAttributes[p] = _;
      }
    e.data.morphTargetsRelative && (a.morphTargetsRelative = !0);
    const d = e.data.groups || e.data.drawcalls || e.data.offsets;
    if (d !== void 0)
      for (let p = 0, m = d.length; p !== m; ++p) {
        const _ = d[p];
        a.addGroup(_.start, _.count, _.materialIndex);
      }
    const u = e.data.boundingSphere;
    return u !== void 0 && (a.boundingSphere = new Lt().fromJSON(u)), e.name && (a.name = e.name), e.userData && (a.userData = e.userData), a;
  }
}
class p0 extends gi {
  /**
   * Constructs a new object loader.
   *
   * @param {LoadingManager} [manager] - The loading manager.
   */
  constructor(e) {
    super(e);
  }
  /**
   * Starts loading from the given URL and pass the loaded 3D object to the `onLoad()` callback.
   *
   * @param {string} url - The path/URL of the file to be loaded. This can also be a data URI.
   * @param {function(Object3D)} onLoad - Executed when the loading process has been finished.
   * @param {onProgressCallback} onProgress - Executed while the loading is in progress.
   * @param {onErrorCallback} onError - Executed when errors occur.
   */
  load(e, t, i, n) {
    const s = this, a = this.path === "" ? zh.extractUrlBase(e) : this.path;
    this.resourcePath = this.resourcePath || a;
    const o = new vn(this.manager);
    o.setPath(this.path), o.setRequestHeader(this.requestHeader), o.setWithCredentials(this.withCredentials), o.load(e, function(l) {
      let c = null;
      try {
        c = JSON.parse(l);
      } catch (d) {
        n !== void 0 && n(d), console.error("THREE:ObjectLoader: Can't parse " + e + ".", d.message);
        return;
      }
      const h = c.metadata;
      if (h === void 0 || h.type === void 0 || h.type.toLowerCase() === "geometry") {
        n !== void 0 && n(new Error("THREE.ObjectLoader: Can't load " + e)), console.error("THREE.ObjectLoader: Can't load " + e);
        return;
      }
      s.parse(c, t);
    }, i, n);
  }
  /**
   * Async version of {@link ObjectLoader#load}.
   *
   * @async
   * @param {string} url - The path/URL of the file to be loaded. This can also be a data URI.
   * @param {onProgressCallback} onProgress - Executed while the loading is in progress.
   * @return {Promise<Object3D>} A Promise that resolves with the loaded 3D object.
   */
  async loadAsync(e, t) {
    const i = this, n = this.path === "" ? zh.extractUrlBase(e) : this.path;
    this.resourcePath = this.resourcePath || n;
    const s = new vn(this.manager);
    s.setPath(this.path), s.setRequestHeader(this.requestHeader), s.setWithCredentials(this.withCredentials);
    const a = await s.loadAsync(e, t), o = JSON.parse(a), l = o.metadata;
    if (l === void 0 || l.type === void 0 || l.type.toLowerCase() === "geometry")
      throw new Error("THREE.ObjectLoader: Can't load " + e);
    return await i.parseAsync(o);
  }
  /**
   * Parses the given JSON. This is used internally by {@link ObjectLoader#load}
   * but can also be used directly to parse a previously loaded JSON structure.
   *
   * @param {Object} json - The serialized 3D object.
   * @param {onLoad} onLoad - Executed when all resources (e.g. textures) have been fully loaded.
   * @return {Object3D} The parsed 3D object.
   */
  parse(e, t) {
    const i = this.parseAnimations(e.animations), n = this.parseShapes(e.shapes), s = this.parseGeometries(e.geometries, n), a = this.parseImages(e.images, function() {
      t !== void 0 && t(c);
    }), o = this.parseTextures(e.textures, a), l = this.parseMaterials(e.materials, o), c = this.parseObject(e.object, s, l, o, i), h = this.parseSkeletons(e.skeletons, c);
    if (this.bindSkeletons(c, h), this.bindLightTargets(c), t !== void 0) {
      let d = !1;
      for (const u in a)
        if (a[u].data instanceof HTMLImageElement) {
          d = !0;
          break;
        }
      d === !1 && t(c);
    }
    return c;
  }
  /**
   * Async version of {@link ObjectLoader#parse}.
   *
   * @param {Object} json - The serialized 3D object.
   * @return {Promise<Object3D>} A Promise that resolves with the parsed 3D object.
   */
  async parseAsync(e) {
    const t = this.parseAnimations(e.animations), i = this.parseShapes(e.shapes), n = this.parseGeometries(e.geometries, i), s = await this.parseImagesAsync(e.images), a = this.parseTextures(e.textures, s), o = this.parseMaterials(e.materials, a), l = this.parseObject(e.object, n, o, a, t), c = this.parseSkeletons(e.skeletons, l);
    return this.bindSkeletons(l, c), this.bindLightTargets(l), l;
  }
  // internals
  parseShapes(e) {
    const t = {};
    if (e !== void 0)
      for (let i = 0, n = e.length; i < n; i++) {
        const s = new Nn().fromJSON(e[i]);
        t[s.uuid] = s;
      }
    return t;
  }
  parseSkeletons(e, t) {
    const i = {}, n = {};
    if (t.traverse(function(s) {
      s.isBone && (n[s.uuid] = s);
    }), e !== void 0)
      for (let s = 0, a = e.length; s < a; s++) {
        const o = new Ql().fromJSON(e[s], n);
        i[o.uuid] = o;
      }
    return i;
  }
  parseGeometries(e, t) {
    const i = {};
    if (e !== void 0) {
      const n = new Jm();
      for (let s = 0, a = e.length; s < a; s++) {
        let o;
        const l = e[s];
        switch (l.type) {
          case "BufferGeometry":
          case "InstancedBufferGeometry":
            o = n.parse(l);
            break;
          default:
            l.type in Gu ? o = Gu[l.type].fromJSON(l, t) : console.warn(`THREE.ObjectLoader: Unsupported geometry type "${l.type}"`);
        }
        o.uuid = l.uuid, l.name !== void 0 && (o.name = l.name), l.userData !== void 0 && (o.userData = l.userData), i[l.uuid] = o;
      }
    }
    return i;
  }
  parseMaterials(e, t) {
    const i = {}, n = {};
    if (e !== void 0) {
      const s = new fc();
      s.setTextures(t);
      for (let a = 0, o = e.length; a < o; a++) {
        const l = e[a];
        i[l.uuid] === void 0 && (i[l.uuid] = s.parse(l)), n[l.uuid] = i[l.uuid];
      }
    }
    return n;
  }
  parseAnimations(e) {
    const t = {};
    if (e !== void 0)
      for (let i = 0; i < e.length; i++) {
        const n = e[i], s = yr.parse(n);
        t[s.uuid] = s;
      }
    return t;
  }
  parseImages(e, t) {
    const i = this, n = {};
    let s;
    function a(l) {
      return i.manager.itemStart(l), s.load(l, function() {
        i.manager.itemEnd(l);
      }, void 0, function() {
        i.manager.itemError(l), i.manager.itemEnd(l);
      });
    }
    function o(l) {
      if (typeof l == "string") {
        const c = l, h = /^(\/\/)|([a-z]+:(\/\/)?)/i.test(c) ? c : i.resourcePath + c;
        return a(h);
      } else
        return l.data ? {
          data: sr(l.type, l.data),
          width: l.width,
          height: l.height
        } : null;
    }
    if (e !== void 0 && e.length > 0) {
      const l = new Pd(t);
      s = new ya(l), s.setCrossOrigin(this.crossOrigin);
      for (let c = 0, h = e.length; c < h; c++) {
        const d = e[c], u = d.url;
        if (Array.isArray(u)) {
          const p = [];
          for (let m = 0, _ = u.length; m < _; m++) {
            const g = u[m], f = o(g);
            f !== null && (f instanceof HTMLImageElement ? p.push(f) : p.push(new tn(f.data, f.width, f.height)));
          }
          n[d.uuid] = new In(p);
        } else {
          const p = o(d.url);
          n[d.uuid] = new In(p);
        }
      }
    }
    return n;
  }
  async parseImagesAsync(e) {
    const t = this, i = {};
    let n;
    async function s(a) {
      if (typeof a == "string") {
        const o = a, l = /^(\/\/)|([a-z]+:(\/\/)?)/i.test(o) ? o : t.resourcePath + o;
        return await n.loadAsync(l);
      } else
        return a.data ? {
          data: sr(a.type, a.data),
          width: a.width,
          height: a.height
        } : null;
    }
    if (e !== void 0 && e.length > 0) {
      n = new ya(this.manager), n.setCrossOrigin(this.crossOrigin);
      for (let a = 0, o = e.length; a < o; a++) {
        const l = e[a], c = l.url;
        if (Array.isArray(c)) {
          const h = [];
          for (let d = 0, u = c.length; d < u; d++) {
            const p = c[d], m = await s(p);
            m !== null && (m instanceof HTMLImageElement ? h.push(m) : h.push(new tn(m.data, m.width, m.height)));
          }
          i[l.uuid] = new In(h);
        } else {
          const h = await s(l.url);
          i[l.uuid] = new In(h);
        }
      }
    }
    return i;
  }
  parseTextures(e, t) {
    function i(s, a) {
      return typeof s == "number" ? s : (console.warn("THREE.ObjectLoader.parseTexture: Constant should be in numeric form.", s), a[s]);
    }
    const n = {};
    if (e !== void 0)
      for (let s = 0, a = e.length; s < a; s++) {
        const o = e[s];
        o.image === void 0 && console.warn('THREE.ObjectLoader: No "image" specified for', o.uuid), t[o.image] === void 0 && console.warn("THREE.ObjectLoader: Undefined image", o.image);
        const l = t[o.image], c = l.data;
        let h;
        Array.isArray(c) ? (h = new Sa(), c.length === 6 && (h.needsUpdate = !0)) : (c && c.data ? h = new tn() : h = new Et(), c && (h.needsUpdate = !0)), h.source = l, h.uuid = o.uuid, o.name !== void 0 && (h.name = o.name), o.mapping !== void 0 && (h.mapping = i(o.mapping, f0)), o.channel !== void 0 && (h.channel = o.channel), o.offset !== void 0 && h.offset.fromArray(o.offset), o.repeat !== void 0 && h.repeat.fromArray(o.repeat), o.center !== void 0 && h.center.fromArray(o.center), o.rotation !== void 0 && (h.rotation = o.rotation), o.wrap !== void 0 && (h.wrapS = i(o.wrap[0], Zu), h.wrapT = i(o.wrap[1], Zu)), o.format !== void 0 && (h.format = o.format), o.internalFormat !== void 0 && (h.internalFormat = o.internalFormat), o.type !== void 0 && (h.type = o.type), o.colorSpace !== void 0 && (h.colorSpace = o.colorSpace), o.minFilter !== void 0 && (h.minFilter = i(o.minFilter, Yu)), o.magFilter !== void 0 && (h.magFilter = i(o.magFilter, Yu)), o.anisotropy !== void 0 && (h.anisotropy = o.anisotropy), o.flipY !== void 0 && (h.flipY = o.flipY), o.generateMipmaps !== void 0 && (h.generateMipmaps = o.generateMipmaps), o.premultiplyAlpha !== void 0 && (h.premultiplyAlpha = o.premultiplyAlpha), o.unpackAlignment !== void 0 && (h.unpackAlignment = o.unpackAlignment), o.compareFunction !== void 0 && (h.compareFunction = o.compareFunction), o.userData !== void 0 && (h.userData = o.userData), n[o.uuid] = h;
      }
    return n;
  }
  parseObject(e, t, i, n, s) {
    let a;
    function o(u) {
      return t[u] === void 0 && console.warn("THREE.ObjectLoader: Undefined geometry", u), t[u];
    }
    function l(u) {
      if (u !== void 0) {
        if (Array.isArray(u)) {
          const p = [];
          for (let m = 0, _ = u.length; m < _; m++) {
            const g = u[m];
            i[g] === void 0 && console.warn("THREE.ObjectLoader: Undefined material", g), p.push(i[g]);
          }
          return p;
        }
        return i[u] === void 0 && console.warn("THREE.ObjectLoader: Undefined material", u), i[u];
      }
    }
    function c(u) {
      return n[u] === void 0 && console.warn("THREE.ObjectLoader: Undefined texture", u), n[u];
    }
    let h, d;
    switch (e.type) {
      case "Scene":
        a = new Ma(), e.background !== void 0 && (Number.isInteger(e.background) ? a.background = new oe(e.background) : a.background = c(e.background)), e.environment !== void 0 && (a.environment = c(e.environment)), e.fog !== void 0 && (e.fog.type === "Fog" ? a.fog = new $l(e.fog.color, e.fog.near, e.fog.far) : e.fog.type === "FogExp2" && (a.fog = new jl(e.fog.color, e.fog.density)), e.fog.name !== "" && (a.fog.name = e.fog.name)), e.backgroundBlurriness !== void 0 && (a.backgroundBlurriness = e.backgroundBlurriness), e.backgroundIntensity !== void 0 && (a.backgroundIntensity = e.backgroundIntensity), e.backgroundRotation !== void 0 && a.backgroundRotation.fromArray(e.backgroundRotation), e.environmentIntensity !== void 0 && (a.environmentIntensity = e.environmentIntensity), e.environmentRotation !== void 0 && a.environmentRotation.fromArray(e.environmentRotation);
        break;
      case "PerspectiveCamera":
        a = new kt(e.fov, e.aspect, e.near, e.far), e.focus !== void 0 && (a.focus = e.focus), e.zoom !== void 0 && (a.zoom = e.zoom), e.filmGauge !== void 0 && (a.filmGauge = e.filmGauge), e.filmOffset !== void 0 && (a.filmOffset = e.filmOffset), e.view !== void 0 && (a.view = Object.assign({}, e.view));
        break;
      case "OrthographicCamera":
        a = new kn(e.left, e.right, e.top, e.bottom, e.near, e.far), e.zoom !== void 0 && (a.zoom = e.zoom), e.view !== void 0 && (a.view = Object.assign({}, e.view));
        break;
      case "AmbientLight":
        a = new Dd(e.color, e.intensity);
        break;
      case "DirectionalLight":
        a = new Id(e.color, e.intensity), a.target = e.target || "";
        break;
      case "PointLight":
        a = new Ym(e.color, e.intensity, e.distance, e.decay);
        break;
      case "RectAreaLight":
        a = new jm(e.color, e.intensity, e.width, e.height);
        break;
      case "SpotLight":
        a = new Zm(e.color, e.intensity, e.distance, e.angle, e.penumbra, e.decay), a.target = e.target || "";
        break;
      case "HemisphereLight":
        a = new qm(e.color, e.groundColor, e.intensity);
        break;
      case "LightProbe":
        a = new Km().fromJSON(e);
        break;
      case "SkinnedMesh":
        h = o(e.geometry), d = l(e.material), a = new _m(h, d), e.bindMode !== void 0 && (a.bindMode = e.bindMode), e.bindMatrix !== void 0 && a.bindMatrix.fromArray(e.bindMatrix), e.skeleton !== void 0 && (a.skeleton = e.skeleton);
        break;
      case "Mesh":
        h = o(e.geometry), d = l(e.material), a = new Je(h, d);
        break;
      case "InstancedMesh":
        h = o(e.geometry), d = l(e.material);
        const u = e.count, p = e.instanceMatrix, m = e.instanceColor;
        a = new ym(h, d, u), a.instanceMatrix = new gr(new Float32Array(p.array), 16), m !== void 0 && (a.instanceColor = new gr(new Float32Array(m.array), m.itemSize));
        break;
      case "BatchedMesh":
        h = o(e.geometry), d = l(e.material), a = new vm(e.maxInstanceCount, e.maxVertexCount, e.maxIndexCount, d), a.geometry = h, a.perObjectFrustumCulled = e.perObjectFrustumCulled, a.sortObjects = e.sortObjects, a._drawRanges = e.drawRanges, a._reservedRanges = e.reservedRanges, a._geometryInfo = e.geometryInfo.map((_) => {
          let g = null, f = null;
          return _.boundingBox !== void 0 && (g = new Tt().fromJSON(_.boundingBox)), _.boundingSphere !== void 0 && (f = new Lt().fromJSON(_.boundingSphere)), {
            ..._,
            boundingBox: g,
            boundingSphere: f
          };
        }), a._instanceInfo = e.instanceInfo, a._availableInstanceIds = e._availableInstanceIds, a._availableGeometryIds = e._availableGeometryIds, a._nextIndexStart = e.nextIndexStart, a._nextVertexStart = e.nextVertexStart, a._geometryCount = e.geometryCount, a._maxInstanceCount = e.maxInstanceCount, a._maxVertexCount = e.maxVertexCount, a._maxIndexCount = e.maxIndexCount, a._geometryInitialized = e.geometryInitialized, a._matricesTexture = c(e.matricesTexture.uuid), a._indirectTexture = c(e.indirectTexture.uuid), e.colorsTexture !== void 0 && (a._colorsTexture = c(e.colorsTexture.uuid)), e.boundingSphere !== void 0 && (a.boundingSphere = new Lt().fromJSON(e.boundingSphere)), e.boundingBox !== void 0 && (a.boundingBox = new Tt().fromJSON(e.boundingBox));
        break;
      case "LOD":
        a = new gm();
        break;
      case "Line":
        a = new Fn(o(e.geometry), l(e.material));
        break;
      case "LineLoop":
        a = new xm(o(e.geometry), l(e.material));
        break;
      case "LineSegments":
        a = new ei(o(e.geometry), l(e.material));
        break;
      case "PointCloud":
      case "Points":
        a = new pd(o(e.geometry), l(e.material));
        break;
      case "Sprite":
        a = new Qr(l(e.material));
        break;
      case "Group":
        a = new li();
        break;
      case "Bone":
        a = new ud();
        break;
      default:
        a = new tt();
    }
    if (a.uuid = e.uuid, e.name !== void 0 && (a.name = e.name), e.matrix !== void 0 ? (a.matrix.fromArray(e.matrix), e.matrixAutoUpdate !== void 0 && (a.matrixAutoUpdate = e.matrixAutoUpdate), a.matrixAutoUpdate && a.matrix.decompose(a.position, a.quaternion, a.scale)) : (e.position !== void 0 && a.position.fromArray(e.position), e.rotation !== void 0 && a.rotation.fromArray(e.rotation), e.quaternion !== void 0 && a.quaternion.fromArray(e.quaternion), e.scale !== void 0 && a.scale.fromArray(e.scale)), e.up !== void 0 && a.up.fromArray(e.up), e.castShadow !== void 0 && (a.castShadow = e.castShadow), e.receiveShadow !== void 0 && (a.receiveShadow = e.receiveShadow), e.shadow && (e.shadow.intensity !== void 0 && (a.shadow.intensity = e.shadow.intensity), e.shadow.bias !== void 0 && (a.shadow.bias = e.shadow.bias), e.shadow.normalBias !== void 0 && (a.shadow.normalBias = e.shadow.normalBias), e.shadow.radius !== void 0 && (a.shadow.radius = e.shadow.radius), e.shadow.mapSize !== void 0 && a.shadow.mapSize.fromArray(e.shadow.mapSize), e.shadow.camera !== void 0 && (a.shadow.camera = this.parseObject(e.shadow.camera))), e.visible !== void 0 && (a.visible = e.visible), e.frustumCulled !== void 0 && (a.frustumCulled = e.frustumCulled), e.renderOrder !== void 0 && (a.renderOrder = e.renderOrder), e.userData !== void 0 && (a.userData = e.userData), e.layers !== void 0 && (a.layers.mask = e.layers), e.children !== void 0) {
      const u = e.children;
      for (let p = 0; p < u.length; p++)
        a.add(this.parseObject(u[p], t, i, n, s));
    }
    if (e.animations !== void 0) {
      const u = e.animations;
      for (let p = 0; p < u.length; p++) {
        const m = u[p];
        a.animations.push(s[m]);
      }
    }
    if (e.type === "LOD") {
      e.autoUpdate !== void 0 && (a.autoUpdate = e.autoUpdate);
      const u = e.levels;
      for (let p = 0; p < u.length; p++) {
        const m = u[p], _ = a.getObjectByProperty("uuid", m.object);
        _ !== void 0 && a.addLevel(_, m.distance, m.hysteresis);
      }
    }
    return a;
  }
  bindSkeletons(e, t) {
    Object.keys(t).length !== 0 && e.traverse(function(i) {
      if (i.isSkinnedMesh === !0 && i.skeleton !== void 0) {
        const n = t[i.skeleton];
        n === void 0 ? console.warn("THREE.ObjectLoader: No skeleton found with UUID:", i.skeleton) : i.bind(n, i.bindMatrix);
      }
    });
  }
  bindLightTargets(e) {
    e.traverse(function(t) {
      if (t.isDirectionalLight || t.isSpotLight) {
        const i = t.target, n = e.getObjectByProperty("uuid", i);
        n !== void 0 ? t.target = n : t.target = new tt();
      }
    });
  }
}
const f0 = {
  UVMapping: Ol,
  CubeReflectionMapping: _n,
  CubeRefractionMapping: Un,
  EquirectangularReflectionMapping: na,
  EquirectangularRefractionMapping: sa,
  CubeUVReflectionMapping: xr
}, Zu = {
  RepeatWrapping: xs,
  ClampToEdgeWrapping: fi,
  MirroredRepeatWrapping: ra
}, Yu = {
  NearestFilter: Xt,
  NearestMipmapNearestFilter: $h,
  NearestMipmapLinearFilter: nr,
  LinearFilter: Pt,
  LinearMipmapNearestFilter: Zr,
  LinearMipmapLinearFilter: Ji
}, Qc = /* @__PURE__ */ new WeakMap();
class m0 extends gi {
  /**
   * Constructs a new image bitmap loader.
   *
   * @param {LoadingManager} [manager] - The loading manager.
   */
  constructor(e) {
    super(e), this.isImageBitmapLoader = !0, typeof createImageBitmap > "u" && console.warn("THREE.ImageBitmapLoader: createImageBitmap() not supported."), typeof fetch > "u" && console.warn("THREE.ImageBitmapLoader: fetch() not supported."), this.options = { premultiplyAlpha: "none" }, this._abortController = new AbortController();
  }
  /**
   * Sets the given loader options. The structure of the object must match the `options` parameter of
   * [createImageBitmap]{@link https://developer.mozilla.org/en-US/docs/Web/API/Window/createImageBitmap}.
   *
   * @param {Object} options - The loader options to set.
   * @return {ImageBitmapLoader} A reference to this image bitmap loader.
   */
  setOptions(e) {
    return this.options = e, this;
  }
  /**
   * Starts loading from the given URL and pass the loaded image bitmap to the `onLoad()` callback.
   *
   * @param {string} url - The path/URL of the file to be loaded. This can also be a data URI.
   * @param {function(ImageBitmap)} onLoad - Executed when the loading process has been finished.
   * @param {onProgressCallback} onProgress - Unsupported in this loader.
   * @param {onErrorCallback} onError - Executed when errors occur.
   * @return {ImageBitmap|undefined} The image bitmap.
   */
  load(e, t, i, n) {
    e === void 0 && (e = ""), this.path !== void 0 && (e = this.path + e), e = this.manager.resolveURL(e);
    const s = this, a = Qi.get(`image-bitmap:${e}`);
    if (a !== void 0) {
      if (s.manager.itemStart(e), a.then) {
        a.then((c) => {
          if (Qc.has(a) === !0)
            n && n(Qc.get(a)), s.manager.itemError(e), s.manager.itemEnd(e);
          else
            return t && t(c), s.manager.itemEnd(e), c;
        });
        return;
      }
      return setTimeout(function() {
        t && t(a), s.manager.itemEnd(e);
      }, 0), a;
    }
    const o = {};
    o.credentials = this.crossOrigin === "anonymous" ? "same-origin" : "include", o.headers = this.requestHeader, o.signal = typeof AbortSignal.any == "function" ? AbortSignal.any([this._abortController.signal, this.manager.abortController.signal]) : this._abortController.signal;
    const l = fetch(e, o).then(function(c) {
      return c.blob();
    }).then(function(c) {
      return createImageBitmap(c, Object.assign(s.options, { colorSpaceConversion: "none" }));
    }).then(function(c) {
      return Qi.add(`image-bitmap:${e}`, c), t && t(c), s.manager.itemEnd(e), c;
    }).catch(function(c) {
      n && n(c), Qc.set(l, c), Qi.remove(`image-bitmap:${e}`), s.manager.itemError(e), s.manager.itemEnd(e);
    });
    Qi.add(`image-bitmap:${e}`, l), s.manager.itemStart(e);
  }
  /**
   * Aborts ongoing fetch requests.
   *
   * @return {ImageBitmapLoader} A reference to this instance.
   */
  abort() {
    return this._abortController.abort(), this._abortController = new AbortController(), this;
  }
}
let uo;
class Nd {
  /**
   * Returns the global native audio context.
   *
   * @return {AudioContext} The native audio context.
   */
  static getContext() {
    return uo === void 0 && (uo = new (window.AudioContext || window.webkitAudioContext)()), uo;
  }
  /**
   * Allows to set the global native audio context from outside.
   *
   * @param {AudioContext} value - The native context to set.
   */
  static setContext(e) {
    uo = e;
  }
}
class g0 extends gi {
  /**
   * Constructs a new audio loader.
   *
   * @param {LoadingManager} [manager] - The loading manager.
   */
  constructor(e) {
    super(e);
  }
  /**
   * Starts loading from the given URL and passes the loaded audio buffer
   * to the `onLoad()` callback.
   *
   * @param {string} url - The path/URL of the file to be loaded. This can also be a data URI.
   * @param {function(AudioBuffer)} onLoad - Executed when the loading process has been finished.
   * @param {onProgressCallback} onProgress - Executed while the loading is in progress.
   * @param {onErrorCallback} onError - Executed when errors occur.
   */
  load(e, t, i, n) {
    const s = this, a = new vn(this.manager);
    a.setResponseType("arraybuffer"), a.setPath(this.path), a.setRequestHeader(this.requestHeader), a.setWithCredentials(this.withCredentials), a.load(e, function(l) {
      try {
        const c = l.slice(0);
        Nd.getContext().decodeAudioData(c, function(d) {
          t(d);
        }).catch(o);
      } catch (c) {
        o(c);
      }
    }, i, n);
    function o(l) {
      n ? n(l) : console.error(l), s.manager.itemError(e);
    }
  }
}
const ju = /* @__PURE__ */ new Ne(), $u = /* @__PURE__ */ new Ne(), Jn = /* @__PURE__ */ new Ne();
class _0 {
  /**
   * Constructs a new stereo camera.
   */
  constructor() {
    this.type = "StereoCamera", this.aspect = 1, this.eyeSep = 0.064, this.cameraL = new kt(), this.cameraL.layers.enable(1), this.cameraL.matrixAutoUpdate = !1, this.cameraR = new kt(), this.cameraR.layers.enable(2), this.cameraR.matrixAutoUpdate = !1, this._cache = {
      focus: null,
      fov: null,
      aspect: null,
      near: null,
      far: null,
      zoom: null,
      eyeSep: null
    };
  }
  /**
   * Updates the stereo camera based on the given perspective camera.
   *
   * @param {PerspectiveCamera} camera - The perspective camera.
   */
  update(e) {
    const t = this._cache;
    if (t.focus !== e.focus || t.fov !== e.fov || t.aspect !== e.aspect * this.aspect || t.near !== e.near || t.far !== e.far || t.zoom !== e.zoom || t.eyeSep !== this.eyeSep) {
      t.focus = e.focus, t.fov = e.fov, t.aspect = e.aspect * this.aspect, t.near = e.near, t.far = e.far, t.zoom = e.zoom, t.eyeSep = this.eyeSep, Jn.copy(e.projectionMatrix);
      const n = t.eyeSep / 2, s = n * t.near / t.focus, a = t.near * Math.tan(ms * t.fov * 0.5) / t.zoom;
      let o, l;
      $u.elements[12] = -n, ju.elements[12] = n, o = -a * t.aspect + s, l = a * t.aspect + s, Jn.elements[0] = 2 * t.near / (l - o), Jn.elements[8] = (l + o) / (l - o), this.cameraL.projectionMatrix.copy(Jn), o = -a * t.aspect - s, l = a * t.aspect - s, Jn.elements[0] = 2 * t.near / (l - o), Jn.elements[8] = (l + o) / (l - o), this.cameraR.projectionMatrix.copy(Jn);
    }
    this.cameraL.matrixWorld.copy(e.matrixWorld).multiply($u), this.cameraR.matrixWorld.copy(e.matrixWorld).multiply(ju);
  }
}
class Qm extends kt {
  /**
   * Constructs a new array camera.
   *
   * @param {Array<PerspectiveCamera>} [array=[]] - An array of perspective sub cameras.
   */
  constructor(e = []) {
    super(), this.isArrayCamera = !0, this.isMultiViewCamera = !1, this.cameras = e;
  }
}
class Ud {
  /**
   * Constructs a new clock.
   *
   * @param {boolean} [autoStart=true] - Whether to automatically start the clock when
   * `getDelta()` is called for the first time.
   */
  constructor(e = !0) {
    this.autoStart = e, this.startTime = 0, this.oldTime = 0, this.elapsedTime = 0, this.running = !1;
  }
  /**
   * Starts the clock. When `autoStart` is set to `true`, the method is automatically
   * called by the class.
   */
  start() {
    this.startTime = performance.now(), this.oldTime = this.startTime, this.elapsedTime = 0, this.running = !0;
  }
  /**
   * Stops the clock.
   */
  stop() {
    this.getElapsedTime(), this.running = !1, this.autoStart = !1;
  }
  /**
   * Returns the elapsed time in seconds.
   *
   * @return {number} The elapsed time.
   */
  getElapsedTime() {
    return this.getDelta(), this.elapsedTime;
  }
  /**
   * Returns the delta time in seconds.
   *
   * @return {number} The delta time.
   */
  getDelta() {
    let e = 0;
    if (this.autoStart && !this.running)
      return this.start(), 0;
    if (this.running) {
      const t = performance.now();
      e = (t - this.oldTime) / 1e3, this.oldTime = t, this.elapsedTime += e;
    }
    return e;
  }
}
const Qn = /* @__PURE__ */ new b(), eh = /* @__PURE__ */ new ot(), y0 = /* @__PURE__ */ new b(), es = /* @__PURE__ */ new b(), ts = /* @__PURE__ */ new b();
class v0 extends tt {
  /**
   * Constructs a new audio listener.
   */
  constructor() {
    super(), this.type = "AudioListener", this.context = Nd.getContext(), this.gain = this.context.createGain(), this.gain.connect(this.context.destination), this.filter = null, this.timeDelta = 0, this._clock = new Ud();
  }
  /**
   * Returns the listener's input node.
   *
   * This method is used by other audio nodes to connect to this listener.
   *
   * @return {GainNode} The input node.
   */
  getInput() {
    return this.gain;
  }
  /**
   * Removes the current filter from this listener.
   *
   * @return {AudioListener} A reference to this listener.
   */
  removeFilter() {
    return this.filter !== null && (this.gain.disconnect(this.filter), this.filter.disconnect(this.context.destination), this.gain.connect(this.context.destination), this.filter = null), this;
  }
  /**
   * Returns the current set filter.
   *
   * @return {?AudioNode} The filter.
   */
  getFilter() {
    return this.filter;
  }
  /**
   * Sets the given filter to this listener.
   *
   * @param {AudioNode} value - The filter to set.
   * @return {AudioListener} A reference to this listener.
   */
  setFilter(e) {
    return this.filter !== null ? (this.gain.disconnect(this.filter), this.filter.disconnect(this.context.destination)) : this.gain.disconnect(this.context.destination), this.filter = e, this.gain.connect(this.filter), this.filter.connect(this.context.destination), this;
  }
  /**
   * Returns the applications master volume.
   *
   * @return {number} The master volume.
   */
  getMasterVolume() {
    return this.gain.gain.value;
  }
  /**
   * Sets the applications master volume. This volume setting affects
   * all audio nodes in the scene.
   *
   * @param {number} value - The master volume to set.
   * @return {AudioListener} A reference to this listener.
   */
  setMasterVolume(e) {
    return this.gain.gain.setTargetAtTime(e, this.context.currentTime, 0.01), this;
  }
  updateMatrixWorld(e) {
    super.updateMatrixWorld(e);
    const t = this.context.listener;
    if (this.timeDelta = this._clock.getDelta(), this.matrixWorld.decompose(Qn, eh, y0), es.set(0, 0, -1).applyQuaternion(eh), ts.set(0, 1, 0).applyQuaternion(eh), t.positionX) {
      const i = this.context.currentTime + this.timeDelta;
      t.positionX.linearRampToValueAtTime(Qn.x, i), t.positionY.linearRampToValueAtTime(Qn.y, i), t.positionZ.linearRampToValueAtTime(Qn.z, i), t.forwardX.linearRampToValueAtTime(es.x, i), t.forwardY.linearRampToValueAtTime(es.y, i), t.forwardZ.linearRampToValueAtTime(es.z, i), t.upX.linearRampToValueAtTime(ts.x, i), t.upY.linearRampToValueAtTime(ts.y, i), t.upZ.linearRampToValueAtTime(ts.z, i);
    } else
      t.setPosition(Qn.x, Qn.y, Qn.z), t.setOrientation(es.x, es.y, es.z, ts.x, ts.y, ts.z);
  }
}
class eg extends tt {
  /**
   * Constructs a new audio.
   *
   * @param {AudioListener} listener - The global audio listener.
   */
  constructor(e) {
    super(), this.type = "Audio", this.listener = e, this.context = e.context, this.gain = this.context.createGain(), this.gain.connect(e.getInput()), this.autoplay = !1, this.buffer = null, this.detune = 0, this.loop = !1, this.loopStart = 0, this.loopEnd = 0, this.offset = 0, this.duration = void 0, this.playbackRate = 1, this.isPlaying = !1, this.hasPlaybackControl = !0, this.source = null, this.sourceType = "empty", this._startedAt = 0, this._progress = 0, this._connected = !1, this.filters = [];
  }
  /**
   * Returns the output audio node.
   *
   * @return {GainNode} The output node.
   */
  getOutput() {
    return this.gain;
  }
  /**
   * Sets the given audio node as the source of this instance.
   *
   * {@link Audio#sourceType} is set to `audioNode` and {@link Audio#hasPlaybackControl} to `false`.
   *
   * @param {AudioNode} audioNode - The audio node like an instance of `OscillatorNode`.
   * @return {Audio} A reference to this instance.
   */
  setNodeSource(e) {
    return this.hasPlaybackControl = !1, this.sourceType = "audioNode", this.source = e, this.connect(), this;
  }
  /**
   * Sets the given media element as the source of this instance.
   *
   * {@link Audio#sourceType} is set to `mediaNode` and {@link Audio#hasPlaybackControl} to `false`.
   *
   * @param {HTMLMediaElement} mediaElement - The media element.
   * @return {Audio} A reference to this instance.
   */
  setMediaElementSource(e) {
    return this.hasPlaybackControl = !1, this.sourceType = "mediaNode", this.source = this.context.createMediaElementSource(e), this.connect(), this;
  }
  /**
   * Sets the given media stream as the source of this instance.
   *
   * {@link Audio#sourceType} is set to `mediaStreamNode` and {@link Audio#hasPlaybackControl} to `false`.
   *
   * @param {MediaStream} mediaStream - The media stream.
   * @return {Audio} A reference to this instance.
   */
  setMediaStreamSource(e) {
    return this.hasPlaybackControl = !1, this.sourceType = "mediaStreamNode", this.source = this.context.createMediaStreamSource(e), this.connect(), this;
  }
  /**
   * Sets the given audio buffer as the source of this instance.
   *
   * {@link Audio#sourceType} is set to `buffer` and {@link Audio#hasPlaybackControl} to `true`.
   *
   * @param {AudioBuffer} audioBuffer - The audio buffer.
   * @return {Audio} A reference to this instance.
   */
  setBuffer(e) {
    return this.buffer = e, this.sourceType = "buffer", this.autoplay && this.play(), this;
  }
  /**
   * Starts the playback of the audio.
   *
   * Can only be used with compatible audio sources that allow playback control.
   *
   * @param {number} [delay=0] - The delay, in seconds, at which the audio should start playing.
   * @return {Audio|undefined} A reference to this instance.
   */
  play(e = 0) {
    if (this.isPlaying === !0) {
      console.warn("THREE.Audio: Audio is already playing.");
      return;
    }
    if (this.hasPlaybackControl === !1) {
      console.warn("THREE.Audio: this Audio has no playback control.");
      return;
    }
    this._startedAt = this.context.currentTime + e;
    const t = this.context.createBufferSource();
    return t.buffer = this.buffer, t.loop = this.loop, t.loopStart = this.loopStart, t.loopEnd = this.loopEnd, t.onended = this.onEnded.bind(this), t.start(this._startedAt, this._progress + this.offset, this.duration), this.isPlaying = !0, this.source = t, this.setDetune(this.detune), this.setPlaybackRate(this.playbackRate), this.connect();
  }
  /**
   * Pauses the playback of the audio.
   *
   * Can only be used with compatible audio sources that allow playback control.
   *
   * @return {Audio|undefined} A reference to this instance.
   */
  pause() {
    if (this.hasPlaybackControl === !1) {
      console.warn("THREE.Audio: this Audio has no playback control.");
      return;
    }
    return this.isPlaying === !0 && (this._progress += Math.max(this.context.currentTime - this._startedAt, 0) * this.playbackRate, this.loop === !0 && (this._progress = this._progress % (this.duration || this.buffer.duration)), this.source.stop(), this.source.onended = null, this.isPlaying = !1), this;
  }
  /**
   * Stops the playback of the audio.
   *
   * Can only be used with compatible audio sources that allow playback control.
   *
   * @param {number} [delay=0] - The delay, in seconds, at which the audio should stop playing.
   * @return {Audio|undefined} A reference to this instance.
   */
  stop(e = 0) {
    if (this.hasPlaybackControl === !1) {
      console.warn("THREE.Audio: this Audio has no playback control.");
      return;
    }
    return this._progress = 0, this.source !== null && (this.source.stop(this.context.currentTime + e), this.source.onended = null), this.isPlaying = !1, this;
  }
  /**
   * Connects to the audio source. This is used internally on
   * initialisation and when setting / removing filters.
   *
   * @return {Audio} A reference to this instance.
   */
  connect() {
    if (this.filters.length > 0) {
      this.source.connect(this.filters[0]);
      for (let e = 1, t = this.filters.length; e < t; e++)
        this.filters[e - 1].connect(this.filters[e]);
      this.filters[this.filters.length - 1].connect(this.getOutput());
    } else
      this.source.connect(this.getOutput());
    return this._connected = !0, this;
  }
  /**
   * Disconnects to the audio source. This is used internally on
   * initialisation and when setting / removing filters.
   *
   * @return {Audio|undefined} A reference to this instance.
   */
  disconnect() {
    if (this._connected !== !1) {
      if (this.filters.length > 0) {
        this.source.disconnect(this.filters[0]);
        for (let e = 1, t = this.filters.length; e < t; e++)
          this.filters[e - 1].disconnect(this.filters[e]);
        this.filters[this.filters.length - 1].disconnect(this.getOutput());
      } else
        this.source.disconnect(this.getOutput());
      return this._connected = !1, this;
    }
  }
  /**
   * Returns the current set filters.
   *
   * @return {Array<AudioNode>} The list of filters.
   */
  getFilters() {
    return this.filters;
  }
  /**
   * Sets an array of filters and connects them with the audio source.
   *
   * @param {Array<AudioNode>} [value] - A list of filters.
   * @return {Audio} A reference to this instance.
   */
  setFilters(e) {
    return e || (e = []), this._connected === !0 ? (this.disconnect(), this.filters = e.slice(), this.connect()) : this.filters = e.slice(), this;
  }
  /**
   * Defines the detuning of oscillation in cents.
   *
   * @param {number} value - The detuning of oscillation in cents.
   * @return {Audio} A reference to this instance.
   */
  setDetune(e) {
    return this.detune = e, this.isPlaying === !0 && this.source.detune !== void 0 && this.source.detune.setTargetAtTime(this.detune, this.context.currentTime, 0.01), this;
  }
  /**
   * Returns the detuning of oscillation in cents.
   *
   * @return {number} The detuning of oscillation in cents.
   */
  getDetune() {
    return this.detune;
  }
  /**
   * Returns the first filter in the list of filters.
   *
   * @return {AudioNode|undefined} The first filter in the list of filters.
   */
  getFilter() {
    return this.getFilters()[0];
  }
  /**
   * Applies a single filter node to the audio.
   *
   * @param {AudioNode} [filter] - The filter to set.
   * @return {Audio} A reference to this instance.
   */
  setFilter(e) {
    return this.setFilters(e ? [e] : []);
  }
  /**
   * Sets the playback rate.
   *
   * Can only be used with compatible audio sources that allow playback control.
   *
   * @param {number} [value] - The playback rate to set.
   * @return {Audio|undefined} A reference to this instance.
   */
  setPlaybackRate(e) {
    if (this.hasPlaybackControl === !1) {
      console.warn("THREE.Audio: this Audio has no playback control.");
      return;
    }
    return this.playbackRate = e, this.isPlaying === !0 && this.source.playbackRate.setTargetAtTime(this.playbackRate, this.context.currentTime, 0.01), this;
  }
  /**
  	 * Returns the current playback rate.
  
  	 * @return {number} The playback rate.
  	 */
  getPlaybackRate() {
    return this.playbackRate;
  }
  /**
   * Automatically called when playback finished.
   */
  onEnded() {
    this.isPlaying = !1, this._progress = 0;
  }
  /**
   * Returns the loop flag.
   *
   * Can only be used with compatible audio sources that allow playback control.
   *
   * @return {boolean} Whether the audio should loop or not.
   */
  getLoop() {
    return this.hasPlaybackControl === !1 ? (console.warn("THREE.Audio: this Audio has no playback control."), !1) : this.loop;
  }
  /**
   * Sets the loop flag.
   *
   * Can only be used with compatible audio sources that allow playback control.
   *
   * @param {boolean} value - Whether the audio should loop or not.
   * @return {Audio|undefined} A reference to this instance.
   */
  setLoop(e) {
    if (this.hasPlaybackControl === !1) {
      console.warn("THREE.Audio: this Audio has no playback control.");
      return;
    }
    return this.loop = e, this.isPlaying === !0 && (this.source.loop = this.loop), this;
  }
  /**
   * Sets the loop start value which defines where in the audio buffer the replay should
   * start, in seconds.
   *
   * @param {number} value - The loop start value.
   * @return {Audio} A reference to this instance.
   */
  setLoopStart(e) {
    return this.loopStart = e, this;
  }
  /**
   * Sets the loop end value which defines where in the audio buffer the replay should
   * stop, in seconds.
   *
   * @param {number} value - The loop end value.
   * @return {Audio} A reference to this instance.
   */
  setLoopEnd(e) {
    return this.loopEnd = e, this;
  }
  /**
   * Returns the volume.
   *
   * @return {number} The volume.
   */
  getVolume() {
    return this.gain.gain.value;
  }
  /**
   * Sets the volume.
   *
   * @param {number} value - The volume to set.
   * @return {Audio} A reference to this instance.
   */
  setVolume(e) {
    return this.gain.gain.setTargetAtTime(e, this.context.currentTime, 0.01), this;
  }
  copy(e, t) {
    return super.copy(e, t), e.sourceType !== "buffer" ? (console.warn("THREE.Audio: Audio source type cannot be copied."), this) : (this.autoplay = e.autoplay, this.buffer = e.buffer, this.detune = e.detune, this.loop = e.loop, this.loopStart = e.loopStart, this.loopEnd = e.loopEnd, this.offset = e.offset, this.duration = e.duration, this.playbackRate = e.playbackRate, this.hasPlaybackControl = e.hasPlaybackControl, this.sourceType = e.sourceType, this.filters = e.filters.slice(), this);
  }
  clone(e) {
    return new this.constructor(this.listener).copy(this, e);
  }
}
const is = /* @__PURE__ */ new b(), Ku = /* @__PURE__ */ new ot(), x0 = /* @__PURE__ */ new b(), ns = /* @__PURE__ */ new b();
class b0 extends eg {
  /**
   * Constructs a positional audio.
   *
   * @param {AudioListener} listener - The global audio listener.
   */
  constructor(e) {
    super(e), this.panner = this.context.createPanner(), this.panner.panningModel = "HRTF", this.panner.connect(this.gain);
  }
  connect() {
    return super.connect(), this.panner.connect(this.gain), this;
  }
  disconnect() {
    return super.disconnect(), this.panner.disconnect(this.gain), this;
  }
  getOutput() {
    return this.panner;
  }
  /**
   * Returns the current reference distance.
   *
   * @return {number} The reference distance.
   */
  getRefDistance() {
    return this.panner.refDistance;
  }
  /**
   * Defines the reference distance for reducing volume as the audio source moves
   * further from the listener – i.e. the distance at which the volume reduction
   * starts taking effect.
   *
   * @param {number} value - The reference distance to set.
   * @return {PositionalAudio} A reference to this instance.
   */
  setRefDistance(e) {
    return this.panner.refDistance = e, this;
  }
  /**
   * Returns the current rolloff factor.
   *
   * @return {number} The rolloff factor.
   */
  getRolloffFactor() {
    return this.panner.rolloffFactor;
  }
  /**
   * Defines how quickly the volume is reduced as the source moves away from the listener.
   *
   * @param {number} value - The rolloff factor.
   * @return {PositionalAudio} A reference to this instance.
   */
  setRolloffFactor(e) {
    return this.panner.rolloffFactor = e, this;
  }
  /**
   * Returns the current distance model.
   *
   * @return {('linear'|'inverse'|'exponential')} The distance model.
   */
  getDistanceModel() {
    return this.panner.distanceModel;
  }
  /**
   * Defines which algorithm to use to reduce the volume of the audio source
   * as it moves away from the listener.
   *
   * Read [the spec]{@link https://www.w3.org/TR/webaudio-1.1/#enumdef-distancemodeltype}
   * for more details.
   *
   * @param {('linear'|'inverse'|'exponential')} value - The distance model to set.
   * @return {PositionalAudio} A reference to this instance.
   */
  setDistanceModel(e) {
    return this.panner.distanceModel = e, this;
  }
  /**
   * Returns the current max distance.
   *
   * @return {number} The max distance.
   */
  getMaxDistance() {
    return this.panner.maxDistance;
  }
  /**
   * Defines the maximum distance between the audio source and the listener,
   * after which the volume is not reduced any further.
   *
   * This value is used only by the `linear` distance model.
   *
   * @param {number} value - The max distance.
   * @return {PositionalAudio} A reference to this instance.
   */
  setMaxDistance(e) {
    return this.panner.maxDistance = e, this;
  }
  /**
   * Sets the directional cone in which the audio can be listened.
   *
   * @param {number} coneInnerAngle - An angle, in degrees, of a cone inside of which there will be no volume reduction.
   * @param {number} coneOuterAngle - An angle, in degrees, of a cone outside of which the volume will be reduced by a constant value, defined by the `coneOuterGain` parameter.
   * @param {number} coneOuterGain - The amount of volume reduction outside the cone defined by the `coneOuterAngle`. When set to `0`, no sound can be heard.
   * @return {PositionalAudio} A reference to this instance.
   */
  setDirectionalCone(e, t, i) {
    return this.panner.coneInnerAngle = e, this.panner.coneOuterAngle = t, this.panner.coneOuterGain = i, this;
  }
  updateMatrixWorld(e) {
    if (super.updateMatrixWorld(e), this.hasPlaybackControl === !0 && this.isPlaying === !1) return;
    this.matrixWorld.decompose(is, Ku, x0), ns.set(0, 0, 1).applyQuaternion(Ku);
    const t = this.panner;
    if (t.positionX) {
      const i = this.context.currentTime + this.listener.timeDelta;
      t.positionX.linearRampToValueAtTime(is.x, i), t.positionY.linearRampToValueAtTime(is.y, i), t.positionZ.linearRampToValueAtTime(is.z, i), t.orientationX.linearRampToValueAtTime(ns.x, i), t.orientationY.linearRampToValueAtTime(ns.y, i), t.orientationZ.linearRampToValueAtTime(ns.z, i);
    } else
      t.setPosition(is.x, is.y, is.z), t.setOrientation(ns.x, ns.y, ns.z);
  }
}
class S0 {
  /**
   * Constructs a new audio analyzer.
   *
   * @param {Audio} audio - The audio to analyze.
   * @param {number} [fftSize=2048] - The window size in samples that is used when performing a Fast Fourier Transform (FFT) to get frequency domain data.
   */
  constructor(e, t = 2048) {
    this.analyser = e.context.createAnalyser(), this.analyser.fftSize = t, this.data = new Uint8Array(this.analyser.frequencyBinCount), e.getOutput().connect(this.analyser);
  }
  /**
   * Returns an array with frequency data of the audio.
   *
   * Each item in the array represents the decibel value for a specific frequency.
   * The frequencies are spread linearly from 0 to 1/2 of the sample rate.
   * For example, for 48000 sample rate, the last item of the array will represent
   * the decibel value for 24000 Hz.
   *
   * @return {Uint8Array} The frequency data.
   */
  getFrequencyData() {
    return this.analyser.getByteFrequencyData(this.data), this.data;
  }
  /**
   * Returns the average of the frequencies returned by {@link AudioAnalyser#getFrequencyData}.
   *
   * @return {number} The average frequency.
   */
  getAverageFrequency() {
    let e = 0;
    const t = this.getFrequencyData();
    for (let i = 0; i < t.length; i++)
      e += t[i];
    return e / t.length;
  }
}
class tg {
  /**
   * Constructs a new property mixer.
   *
   * @param {PropertyBinding} binding - The property binding.
   * @param {string} typeName - The keyframe track type name.
   * @param {number} valueSize - The keyframe track value size.
   */
  constructor(e, t, i) {
    this.binding = e, this.valueSize = i;
    let n, s, a;
    switch (t) {
      case "quaternion":
        n = this._slerp, s = this._slerpAdditive, a = this._setAdditiveIdentityQuaternion, this.buffer = new Float64Array(i * 6), this._workIndex = 5;
        break;
      case "string":
      case "bool":
        n = this._select, s = this._select, a = this._setAdditiveIdentityOther, this.buffer = new Array(i * 5);
        break;
      default:
        n = this._lerp, s = this._lerpAdditive, a = this._setAdditiveIdentityNumeric, this.buffer = new Float64Array(i * 5);
    }
    this._mixBufferRegion = n, this._mixBufferRegionAdditive = s, this._setIdentity = a, this._origIndex = 3, this._addIndex = 4, this.cumulativeWeight = 0, this.cumulativeWeightAdditive = 0, this.useCount = 0, this.referenceCount = 0;
  }
  /**
   * Accumulates data in the `incoming` region into `accu<i>`.
   *
   * @param {number} accuIndex - The accumulation index.
   * @param {number} weight - The weight.
   */
  accumulate(e, t) {
    const i = this.buffer, n = this.valueSize, s = e * n + n;
    let a = this.cumulativeWeight;
    if (a === 0) {
      for (let o = 0; o !== n; ++o)
        i[s + o] = i[o];
      a = t;
    } else {
      a += t;
      const o = t / a;
      this._mixBufferRegion(i, s, 0, o, n);
    }
    this.cumulativeWeight = a;
  }
  /**
   * Accumulates data in the `incoming` region into `add`.
   *
   * @param {number} weight - The weight.
   */
  accumulateAdditive(e) {
    const t = this.buffer, i = this.valueSize, n = i * this._addIndex;
    this.cumulativeWeightAdditive === 0 && this._setIdentity(), this._mixBufferRegionAdditive(t, n, 0, e, i), this.cumulativeWeightAdditive += e;
  }
  /**
   * Applies the state of `accu<i>` to the binding when accus differ.
   *
   * @param {number} accuIndex - The accumulation index.
   */
  apply(e) {
    const t = this.valueSize, i = this.buffer, n = e * t + t, s = this.cumulativeWeight, a = this.cumulativeWeightAdditive, o = this.binding;
    if (this.cumulativeWeight = 0, this.cumulativeWeightAdditive = 0, s < 1) {
      const l = t * this._origIndex;
      this._mixBufferRegion(
        i,
        n,
        l,
        1 - s,
        t
      );
    }
    a > 0 && this._mixBufferRegionAdditive(i, n, this._addIndex * t, 1, t);
    for (let l = t, c = t + t; l !== c; ++l)
      if (i[l] !== i[l + t]) {
        o.setValue(i, n);
        break;
      }
  }
  /**
   * Remembers the state of the bound property and copy it to both accus.
   */
  saveOriginalState() {
    const e = this.binding, t = this.buffer, i = this.valueSize, n = i * this._origIndex;
    e.getValue(t, n);
    for (let s = i, a = n; s !== a; ++s)
      t[s] = t[n + s % i];
    this._setIdentity(), this.cumulativeWeight = 0, this.cumulativeWeightAdditive = 0;
  }
  /**
   * Applies the state previously taken via {@link PropertyMixer#saveOriginalState} to the binding.
   */
  restoreOriginalState() {
    const e = this.valueSize * 3;
    this.binding.setValue(this.buffer, e);
  }
  // internals
  _setAdditiveIdentityNumeric() {
    const e = this._addIndex * this.valueSize, t = e + this.valueSize;
    for (let i = e; i < t; i++)
      this.buffer[i] = 0;
  }
  _setAdditiveIdentityQuaternion() {
    this._setAdditiveIdentityNumeric(), this.buffer[this._addIndex * this.valueSize + 3] = 1;
  }
  _setAdditiveIdentityOther() {
    const e = this._origIndex * this.valueSize, t = this._addIndex * this.valueSize;
    for (let i = 0; i < this.valueSize; i++)
      this.buffer[t + i] = this.buffer[e + i];
  }
  // mix functions
  _select(e, t, i, n, s) {
    if (n >= 0.5)
      for (let a = 0; a !== s; ++a)
        e[t + a] = e[i + a];
  }
  _slerp(e, t, i, n) {
    ot.slerpFlat(e, t, e, t, e, i, n);
  }
  _slerpAdditive(e, t, i, n, s) {
    const a = this._workIndex * s;
    ot.multiplyQuaternionsFlat(e, a, e, t, e, i), ot.slerpFlat(e, t, e, t, e, a, n);
  }
  _lerp(e, t, i, n, s) {
    const a = 1 - n;
    for (let o = 0; o !== s; ++o) {
      const l = t + o;
      e[l] = e[l] * a + e[i + o] * n;
    }
  }
  _lerpAdditive(e, t, i, n, s) {
    for (let a = 0; a !== s; ++a) {
      const o = t + a;
      e[o] = e[o] + e[i + a] * n;
    }
  }
}
const Od = "\\[\\]\\.:\\/", M0 = new RegExp("[" + Od + "]", "g"), Fd = "[^" + Od + "]", w0 = "[^" + Od.replace("\\.", "") + "]", E0 = /* @__PURE__ */ /((?:WC+[\/:])*)/.source.replace("WC", Fd), T0 = /* @__PURE__ */ /(WCOD+)?/.source.replace("WCOD", w0), A0 = /* @__PURE__ */ /(?:\.(WC+)(?:\[(.+)\])?)?/.source.replace("WC", Fd), C0 = /* @__PURE__ */ /\.(WC+)(?:\[(.+)\])?/.source.replace("WC", Fd), R0 = new RegExp(
  "^" + E0 + T0 + A0 + C0 + "$"
), P0 = ["material", "materials", "bones", "map"];
class L0 {
  constructor(e, t, i) {
    const n = i || st.parseTrackName(t);
    this._targetGroup = e, this._bindings = e.subscribe_(t, n);
  }
  getValue(e, t) {
    this.bind();
    const i = this._targetGroup.nCachedObjects_, n = this._bindings[i];
    n !== void 0 && n.getValue(e, t);
  }
  setValue(e, t) {
    const i = this._bindings;
    for (let n = this._targetGroup.nCachedObjects_, s = i.length; n !== s; ++n)
      i[n].setValue(e, t);
  }
  bind() {
    const e = this._bindings;
    for (let t = this._targetGroup.nCachedObjects_, i = e.length; t !== i; ++t)
      e[t].bind();
  }
  unbind() {
    const e = this._bindings;
    for (let t = this._targetGroup.nCachedObjects_, i = e.length; t !== i; ++t)
      e[t].unbind();
  }
}
class st {
  /**
   * Constructs a new property binding.
   *
   * @param {Object} rootNode - The root node.
   * @param {string} path - The path.
   * @param {?Object} [parsedPath] - The parsed path.
   */
  constructor(e, t, i) {
    this.path = t, this.parsedPath = i || st.parseTrackName(t), this.node = st.findNode(e, this.parsedPath.nodeName), this.rootNode = e, this.getValue = this._getValue_unbound, this.setValue = this._setValue_unbound;
  }
  /**
   * Factory method for creating a property binding from the given parameters.
   *
   * @static
   * @param {Object} root - The root node.
   * @param {string} path - The path.
   * @param {?Object} [parsedPath] - The parsed path.
   * @return {PropertyBinding|Composite} The created property binding or composite.
   */
  static create(e, t, i) {
    return e && e.isAnimationObjectGroup ? new st.Composite(e, t, i) : new st(e, t, i);
  }
  /**
   * Replaces spaces with underscores and removes unsupported characters from
   * node names, to ensure compatibility with parseTrackName().
   *
   * @param {string} name - Node name to be sanitized.
   * @return {string} The sanitized node name.
   */
  static sanitizeNodeName(e) {
    return e.replace(/\s/g, "_").replace(M0, "");
  }
  /**
   * Parses the given track name (an object path to an animated property) and
   * returns an object with information about the path. Matches strings in the following forms:
   *
   * - nodeName.property
   * - nodeName.property[accessor]
   * - nodeName.material.property[accessor]
   * - uuid.property[accessor]
   * - uuid.objectName[objectIndex].propertyName[propertyIndex]
   * - parentName/nodeName.property
   * - parentName/parentName/nodeName.property[index]
   * - .bone[Armature.DEF_cog].position
   * - scene:helium_balloon_model:helium_balloon_model.position
   *
   * @static
   * @param {string} trackName - The track name to parse.
   * @return {Object} The parsed track name as an object.
   */
  static parseTrackName(e) {
    const t = R0.exec(e);
    if (t === null)
      throw new Error("PropertyBinding: Cannot parse trackName: " + e);
    const i = {
      // directoryName: matches[ 1 ], // (tschw) currently unused
      nodeName: t[2],
      objectName: t[3],
      objectIndex: t[4],
      propertyName: t[5],
      // required
      propertyIndex: t[6]
    }, n = i.nodeName && i.nodeName.lastIndexOf(".");
    if (n !== void 0 && n !== -1) {
      const s = i.nodeName.substring(n + 1);
      P0.indexOf(s) !== -1 && (i.nodeName = i.nodeName.substring(0, n), i.objectName = s);
    }
    if (i.propertyName === null || i.propertyName.length === 0)
      throw new Error("PropertyBinding: can not parse propertyName from trackName: " + e);
    return i;
  }
  /**
   * Searches for a node in the hierarchy of the given root object by the given
   * node name.
   *
   * @static
   * @param {Object} root - The root object.
   * @param {string|number} nodeName - The name of the node.
   * @return {?Object} The found node. Returns `null` if no object was found.
   */
  static findNode(e, t) {
    if (t === void 0 || t === "" || t === "." || t === -1 || t === e.name || t === e.uuid)
      return e;
    if (e.skeleton) {
      const i = e.skeleton.getBoneByName(t);
      if (i !== void 0)
        return i;
    }
    if (e.children) {
      const i = function(s) {
        for (let a = 0; a < s.length; a++) {
          const o = s[a];
          if (o.name === t || o.uuid === t)
            return o;
          const l = i(o.children);
          if (l) return l;
        }
        return null;
      }, n = i(e.children);
      if (n)
        return n;
    }
    return null;
  }
  // these are used to "bind" a nonexistent property
  _getValue_unavailable() {
  }
  _setValue_unavailable() {
  }
  // Getters
  _getValue_direct(e, t) {
    e[t] = this.targetObject[this.propertyName];
  }
  _getValue_array(e, t) {
    const i = this.resolvedProperty;
    for (let n = 0, s = i.length; n !== s; ++n)
      e[t++] = i[n];
  }
  _getValue_arrayElement(e, t) {
    e[t] = this.resolvedProperty[this.propertyIndex];
  }
  _getValue_toArray(e, t) {
    this.resolvedProperty.toArray(e, t);
  }
  // Direct
  _setValue_direct(e, t) {
    this.targetObject[this.propertyName] = e[t];
  }
  _setValue_direct_setNeedsUpdate(e, t) {
    this.targetObject[this.propertyName] = e[t], this.targetObject.needsUpdate = !0;
  }
  _setValue_direct_setMatrixWorldNeedsUpdate(e, t) {
    this.targetObject[this.propertyName] = e[t], this.targetObject.matrixWorldNeedsUpdate = !0;
  }
  // EntireArray
  _setValue_array(e, t) {
    const i = this.resolvedProperty;
    for (let n = 0, s = i.length; n !== s; ++n)
      i[n] = e[t++];
  }
  _setValue_array_setNeedsUpdate(e, t) {
    const i = this.resolvedProperty;
    for (let n = 0, s = i.length; n !== s; ++n)
      i[n] = e[t++];
    this.targetObject.needsUpdate = !0;
  }
  _setValue_array_setMatrixWorldNeedsUpdate(e, t) {
    const i = this.resolvedProperty;
    for (let n = 0, s = i.length; n !== s; ++n)
      i[n] = e[t++];
    this.targetObject.matrixWorldNeedsUpdate = !0;
  }
  // ArrayElement
  _setValue_arrayElement(e, t) {
    this.resolvedProperty[this.propertyIndex] = e[t];
  }
  _setValue_arrayElement_setNeedsUpdate(e, t) {
    this.resolvedProperty[this.propertyIndex] = e[t], this.targetObject.needsUpdate = !0;
  }
  _setValue_arrayElement_setMatrixWorldNeedsUpdate(e, t) {
    this.resolvedProperty[this.propertyIndex] = e[t], this.targetObject.matrixWorldNeedsUpdate = !0;
  }
  // HasToFromArray
  _setValue_fromArray(e, t) {
    this.resolvedProperty.fromArray(e, t);
  }
  _setValue_fromArray_setNeedsUpdate(e, t) {
    this.resolvedProperty.fromArray(e, t), this.targetObject.needsUpdate = !0;
  }
  _setValue_fromArray_setMatrixWorldNeedsUpdate(e, t) {
    this.resolvedProperty.fromArray(e, t), this.targetObject.matrixWorldNeedsUpdate = !0;
  }
  _getValue_unbound(e, t) {
    this.bind(), this.getValue(e, t);
  }
  _setValue_unbound(e, t) {
    this.bind(), this.setValue(e, t);
  }
  /**
   * Creates a getter / setter pair for the property tracked by this binding.
   */
  bind() {
    let e = this.node;
    const t = this.parsedPath, i = t.objectName, n = t.propertyName;
    let s = t.propertyIndex;
    if (e || (e = st.findNode(this.rootNode, t.nodeName), this.node = e), this.getValue = this._getValue_unavailable, this.setValue = this._setValue_unavailable, !e) {
      console.warn("THREE.PropertyBinding: No target node found for track: " + this.path + ".");
      return;
    }
    if (i) {
      let c = t.objectIndex;
      switch (i) {
        case "materials":
          if (!e.material) {
            console.error("THREE.PropertyBinding: Can not bind to material as node does not have a material.", this);
            return;
          }
          if (!e.material.materials) {
            console.error("THREE.PropertyBinding: Can not bind to material.materials as node.material does not have a materials array.", this);
            return;
          }
          e = e.material.materials;
          break;
        case "bones":
          if (!e.skeleton) {
            console.error("THREE.PropertyBinding: Can not bind to bones as node does not have a skeleton.", this);
            return;
          }
          e = e.skeleton.bones;
          for (let h = 0; h < e.length; h++)
            if (e[h].name === c) {
              c = h;
              break;
            }
          break;
        case "map":
          if ("map" in e) {
            e = e.map;
            break;
          }
          if (!e.material) {
            console.error("THREE.PropertyBinding: Can not bind to material as node does not have a material.", this);
            return;
          }
          if (!e.material.map) {
            console.error("THREE.PropertyBinding: Can not bind to material.map as node.material does not have a map.", this);
            return;
          }
          e = e.material.map;
          break;
        default:
          if (e[i] === void 0) {
            console.error("THREE.PropertyBinding: Can not bind to objectName of node undefined.", this);
            return;
          }
          e = e[i];
      }
      if (c !== void 0) {
        if (e[c] === void 0) {
          console.error("THREE.PropertyBinding: Trying to bind to objectIndex of objectName, but is undefined.", this, e);
          return;
        }
        e = e[c];
      }
    }
    const a = e[n];
    if (a === void 0) {
      const c = t.nodeName;
      console.error("THREE.PropertyBinding: Trying to update property for track: " + c + "." + n + " but it wasn't found.", e);
      return;
    }
    let o = this.Versioning.None;
    this.targetObject = e, e.isMaterial === !0 ? o = this.Versioning.NeedsUpdate : e.isObject3D === !0 && (o = this.Versioning.MatrixWorldNeedsUpdate);
    let l = this.BindingType.Direct;
    if (s !== void 0) {
      if (n === "morphTargetInfluences") {
        if (!e.geometry) {
          console.error("THREE.PropertyBinding: Can not bind to morphTargetInfluences because node does not have a geometry.", this);
          return;
        }
        if (!e.geometry.morphAttributes) {
          console.error("THREE.PropertyBinding: Can not bind to morphTargetInfluences because node does not have a geometry.morphAttributes.", this);
          return;
        }
        e.morphTargetDictionary[s] !== void 0 && (s = e.morphTargetDictionary[s]);
      }
      l = this.BindingType.ArrayElement, this.resolvedProperty = a, this.propertyIndex = s;
    } else a.fromArray !== void 0 && a.toArray !== void 0 ? (l = this.BindingType.HasFromToArray, this.resolvedProperty = a) : Array.isArray(a) ? (l = this.BindingType.EntireArray, this.resolvedProperty = a) : this.propertyName = n;
    this.getValue = this.GetterByBindingType[l], this.setValue = this.SetterByBindingTypeAndVersioning[l][o];
  }
  /**
   * Unbinds the property.
   */
  unbind() {
    this.node = null, this.getValue = this._getValue_unbound, this.setValue = this._setValue_unbound;
  }
}
st.Composite = L0;
st.prototype.BindingType = {
  Direct: 0,
  EntireArray: 1,
  ArrayElement: 2,
  HasFromToArray: 3
};
st.prototype.Versioning = {
  None: 0,
  NeedsUpdate: 1,
  MatrixWorldNeedsUpdate: 2
};
st.prototype.GetterByBindingType = [
  st.prototype._getValue_direct,
  st.prototype._getValue_array,
  st.prototype._getValue_arrayElement,
  st.prototype._getValue_toArray
];
st.prototype.SetterByBindingTypeAndVersioning = [
  [
    // Direct
    st.prototype._setValue_direct,
    st.prototype._setValue_direct_setNeedsUpdate,
    st.prototype._setValue_direct_setMatrixWorldNeedsUpdate
  ],
  [
    // EntireArray
    st.prototype._setValue_array,
    st.prototype._setValue_array_setNeedsUpdate,
    st.prototype._setValue_array_setMatrixWorldNeedsUpdate
  ],
  [
    // ArrayElement
    st.prototype._setValue_arrayElement,
    st.prototype._setValue_arrayElement_setNeedsUpdate,
    st.prototype._setValue_arrayElement_setMatrixWorldNeedsUpdate
  ],
  [
    // HasToFromArray
    st.prototype._setValue_fromArray,
    st.prototype._setValue_fromArray_setNeedsUpdate,
    st.prototype._setValue_fromArray_setMatrixWorldNeedsUpdate
  ]
];
class I0 {
  /**
   * Constructs a new animation group.
   *
   * @param {...Object3D} arguments - An arbitrary number of 3D objects that share the same animation state.
   */
  constructor() {
    this.isAnimationObjectGroup = !0, this.uuid = Ti(), this._objects = Array.prototype.slice.call(arguments), this.nCachedObjects_ = 0;
    const e = {};
    this._indicesByUUID = e;
    for (let i = 0, n = arguments.length; i !== n; ++i)
      e[arguments[i].uuid] = i;
    this._paths = [], this._parsedPaths = [], this._bindings = [], this._bindingsIndicesByPath = {};
    const t = this;
    this.stats = {
      objects: {
        get total() {
          return t._objects.length;
        },
        get inUse() {
          return this.total - t.nCachedObjects_;
        }
      },
      get bindingsPerObject() {
        return t._bindings.length;
      }
    };
  }
  /**
   * Adds an arbitrary number of objects to this animation group.
   *
   * @param {...Object3D} arguments - The 3D objects to add.
   */
  add() {
    const e = this._objects, t = this._indicesByUUID, i = this._paths, n = this._parsedPaths, s = this._bindings, a = s.length;
    let o, l = e.length, c = this.nCachedObjects_;
    for (let h = 0, d = arguments.length; h !== d; ++h) {
      const u = arguments[h], p = u.uuid;
      let m = t[p];
      if (m === void 0) {
        m = l++, t[p] = m, e.push(u);
        for (let _ = 0, g = a; _ !== g; ++_)
          s[_].push(new st(u, i[_], n[_]));
      } else if (m < c) {
        o = e[m];
        const _ = --c, g = e[_];
        t[g.uuid] = m, e[m] = g, t[p] = _, e[_] = u;
        for (let f = 0, v = a; f !== v; ++f) {
          const x = s[f], y = x[_];
          let A = x[m];
          x[m] = y, A === void 0 && (A = new st(u, i[f], n[f])), x[_] = A;
        }
      } else e[m] !== o && console.error("THREE.AnimationObjectGroup: Different objects with the same UUID detected. Clean the caches or recreate your infrastructure when reloading scenes.");
    }
    this.nCachedObjects_ = c;
  }
  /**
   * Removes an arbitrary number of objects to this animation group
   *
   * @param {...Object3D} arguments - The 3D objects to remove.
   */
  remove() {
    const e = this._objects, t = this._indicesByUUID, i = this._bindings, n = i.length;
    let s = this.nCachedObjects_;
    for (let a = 0, o = arguments.length; a !== o; ++a) {
      const l = arguments[a], c = l.uuid, h = t[c];
      if (h !== void 0 && h >= s) {
        const d = s++, u = e[d];
        t[u.uuid] = h, e[h] = u, t[c] = d, e[d] = l;
        for (let p = 0, m = n; p !== m; ++p) {
          const _ = i[p], g = _[d], f = _[h];
          _[h] = g, _[d] = f;
        }
      }
    }
    this.nCachedObjects_ = s;
  }
  /**
   * Deallocates all memory resources for the passed 3D objects of this animation group.
   *
   * @param {...Object3D} arguments - The 3D objects to uncache.
   */
  uncache() {
    const e = this._objects, t = this._indicesByUUID, i = this._bindings, n = i.length;
    let s = this.nCachedObjects_, a = e.length;
    for (let o = 0, l = arguments.length; o !== l; ++o) {
      const c = arguments[o], h = c.uuid, d = t[h];
      if (d !== void 0)
        if (delete t[h], d < s) {
          const u = --s, p = e[u], m = --a, _ = e[m];
          t[p.uuid] = d, e[d] = p, t[_.uuid] = u, e[u] = _, e.pop();
          for (let g = 0, f = n; g !== f; ++g) {
            const v = i[g], x = v[u], y = v[m];
            v[d] = x, v[u] = y, v.pop();
          }
        } else {
          const u = --a, p = e[u];
          u > 0 && (t[p.uuid] = d), e[d] = p, e.pop();
          for (let m = 0, _ = n; m !== _; ++m) {
            const g = i[m];
            g[d] = g[u], g.pop();
          }
        }
    }
    this.nCachedObjects_ = s;
  }
  // Internal interface used by befriended PropertyBinding.Composite:
  subscribe_(e, t) {
    const i = this._bindingsIndicesByPath;
    let n = i[e];
    const s = this._bindings;
    if (n !== void 0) return s[n];
    const a = this._paths, o = this._parsedPaths, l = this._objects, c = l.length, h = this.nCachedObjects_, d = new Array(c);
    n = s.length, i[e] = n, a.push(e), o.push(t), s.push(d);
    for (let u = h, p = l.length; u !== p; ++u) {
      const m = l[u];
      d[u] = new st(m, e, t);
    }
    return d;
  }
  unsubscribe_(e) {
    const t = this._bindingsIndicesByPath, i = t[e];
    if (i !== void 0) {
      const n = this._paths, s = this._parsedPaths, a = this._bindings, o = a.length - 1, l = a[o], c = e[o];
      t[c] = i, a[i] = l, a.pop(), s[i] = s[o], s.pop(), n[i] = n[o], n.pop();
    }
  }
}
class ig {
  /**
   * Constructs a new animation action.
   *
   * @param {AnimationMixer} mixer - The mixer that is controlled by this action.
   * @param {AnimationClip} clip - The animation clip that holds the actual keyframes.
   * @param {?Object3D} [localRoot=null] - The root object on which this action is performed.
   * @param {(NormalAnimationBlendMode|AdditiveAnimationBlendMode)} [blendMode] - The blend mode.
   */
  constructor(e, t, i = null, n = t.blendMode) {
    this._mixer = e, this._clip = t, this._localRoot = i, this.blendMode = n;
    const s = t.tracks, a = s.length, o = new Array(a), l = {
      endingStart: ds,
      endingEnd: ds
    };
    for (let c = 0; c !== a; ++c) {
      const h = s[c].createInterpolant(null);
      o[c] = h, h.settings = l;
    }
    this._interpolantSettings = l, this._interpolants = o, this._propertyBindings = new Array(a), this._cacheIndex = null, this._byClipCacheIndex = null, this._timeScaleInterpolant = null, this._weightInterpolant = null, this.loop = sd, this._loopCount = -1, this._startTime = null, this.time = 0, this.timeScale = 1, this._effectiveTimeScale = 1, this.weight = 1, this._effectiveWeight = 1, this.repetitions = 1 / 0, this.paused = !1, this.enabled = !0, this.clampWhenFinished = !1, this.zeroSlopeAtStart = !0, this.zeroSlopeAtEnd = !0;
  }
  /**
   * Starts the playback of the animation.
   *
   * @return {AnimationAction} A reference to this animation action.
   */
  play() {
    return this._mixer._activateAction(this), this;
  }
  /**
   * Stops the playback of the animation.
   *
   * @return {AnimationAction} A reference to this animation action.
   */
  stop() {
    return this._mixer._deactivateAction(this), this.reset();
  }
  /**
   * Resets the playback of the animation.
   *
   * @return {AnimationAction} A reference to this animation action.
   */
  reset() {
    return this.paused = !1, this.enabled = !0, this.time = 0, this._loopCount = -1, this._startTime = null, this.stopFading().stopWarping();
  }
  /**
   * Returns `true` if the animation is running.
   *
   * @return {boolean} Whether the animation is running or not.
   */
  isRunning() {
    return this.enabled && !this.paused && this.timeScale !== 0 && this._startTime === null && this._mixer._isActiveAction(this);
  }
  /**
   * Returns `true` when {@link AnimationAction#play} has been called.
   *
   * @return {boolean} Whether the animation is scheduled or not.
   */
  isScheduled() {
    return this._mixer._isActiveAction(this);
  }
  /**
   * Defines the time when the animation should start.
   *
   * @param {number} time - The start time in seconds.
   * @return {AnimationAction} A reference to this animation action.
   */
  startAt(e) {
    return this._startTime = e, this;
  }
  /**
   * Configures the loop settings for this action.
   *
   * @param {(LoopRepeat|LoopOnce|LoopPingPong)} mode - The loop mode.
   * @param {number} repetitions - The number of repetitions.
   * @return {AnimationAction} A reference to this animation action.
   */
  setLoop(e, t) {
    return this.loop = e, this.repetitions = t, this;
  }
  /**
   * Sets the effective weight of this action.
   *
   * An action has no effect and thus an effective weight of zero when the
   * action is disabled.
   *
   * @param {number} weight - The weight to set.
   * @return {AnimationAction} A reference to this animation action.
   */
  setEffectiveWeight(e) {
    return this.weight = e, this._effectiveWeight = this.enabled ? e : 0, this.stopFading();
  }
  /**
   * Returns the effective weight of this action.
   *
   * @return {number} The effective weight.
   */
  getEffectiveWeight() {
    return this._effectiveWeight;
  }
  /**
   * Fades the animation in by increasing its weight gradually from `0` to `1`,
   * within the passed time interval.
   *
   * @param {number} duration - The duration of the fade.
   * @return {AnimationAction} A reference to this animation action.
   */
  fadeIn(e) {
    return this._scheduleFading(e, 0, 1);
  }
  /**
   * Fades the animation out by decreasing its weight gradually from `1` to `0`,
   * within the passed time interval.
   *
   * @param {number} duration - The duration of the fade.
   * @return {AnimationAction} A reference to this animation action.
   */
  fadeOut(e) {
    return this._scheduleFading(e, 1, 0);
  }
  /**
   * Causes this action to fade in and the given action to fade out,
   * within the passed time interval.
   *
   * @param {AnimationAction} fadeOutAction - The animation action to fade out.
   * @param {number} duration - The duration of the fade.
   * @param {boolean} [warp=false] - Whether warping should be used or not.
   * @return {AnimationAction} A reference to this animation action.
   */
  crossFadeFrom(e, t, i = !1) {
    if (e.fadeOut(t), this.fadeIn(t), i === !0) {
      const n = this._clip.duration, s = e._clip.duration, a = s / n, o = n / s;
      e.warp(1, a, t), this.warp(o, 1, t);
    }
    return this;
  }
  /**
   * Causes this action to fade out and the given action to fade in,
   * within the passed time interval.
   *
   * @param {AnimationAction} fadeInAction - The animation action to fade in.
   * @param {number} duration - The duration of the fade.
   * @param {boolean} [warp=false] - Whether warping should be used or not.
   * @return {AnimationAction} A reference to this animation action.
   */
  crossFadeTo(e, t, i = !1) {
    return e.crossFadeFrom(this, t, i);
  }
  /**
   * Stops any fading which is applied to this action.
   *
   * @return {AnimationAction} A reference to this animation action.
   */
  stopFading() {
    const e = this._weightInterpolant;
    return e !== null && (this._weightInterpolant = null, this._mixer._takeBackControlInterpolant(e)), this;
  }
  /**
   * Sets the effective time scale of this action.
   *
   * An action has no effect and thus an effective time scale of zero when the
   * action is paused.
   *
   * @param {number} timeScale - The time scale to set.
   * @return {AnimationAction} A reference to this animation action.
   */
  setEffectiveTimeScale(e) {
    return this.timeScale = e, this._effectiveTimeScale = this.paused ? 0 : e, this.stopWarping();
  }
  /**
   * Returns the effective time scale of this action.
   *
   * @return {number} The effective time scale.
   */
  getEffectiveTimeScale() {
    return this._effectiveTimeScale;
  }
  /**
   * Sets the duration for a single loop of this action.
   *
   * @param {number} duration - The duration to set.
   * @return {AnimationAction} A reference to this animation action.
   */
  setDuration(e) {
    return this.timeScale = this._clip.duration / e, this.stopWarping();
  }
  /**
   * Synchronizes this action with the passed other action.
   *
   * @param {AnimationAction} action - The action to sync with.
   * @return {AnimationAction} A reference to this animation action.
   */
  syncWith(e) {
    return this.time = e.time, this.timeScale = e.timeScale, this.stopWarping();
  }
  /**
   * Decelerates this animation's speed to `0` within the passed time interval.
   *
   * @param {number} duration - The duration.
   * @return {AnimationAction} A reference to this animation action.
   */
  halt(e) {
    return this.warp(this._effectiveTimeScale, 0, e);
  }
  /**
   * Changes the playback speed, within the passed time interval, by modifying
   * {@link AnimationAction#timeScale} gradually from `startTimeScale` to
   * `endTimeScale`.
   *
   * @param {number} startTimeScale - The start time scale.
   * @param {number} endTimeScale - The end time scale.
   * @param {number} duration - The duration.
   * @return {AnimationAction} A reference to this animation action.
   */
  warp(e, t, i) {
    const n = this._mixer, s = n.time, a = this.timeScale;
    let o = this._timeScaleInterpolant;
    o === null && (o = n._lendControlInterpolant(), this._timeScaleInterpolant = o);
    const l = o.parameterPositions, c = o.sampleValues;
    return l[0] = s, l[1] = s + i, c[0] = e / a, c[1] = t / a, this;
  }
  /**
   * Stops any scheduled warping which is applied to this action.
   *
   * @return {AnimationAction} A reference to this animation action.
   */
  stopWarping() {
    const e = this._timeScaleInterpolant;
    return e !== null && (this._timeScaleInterpolant = null, this._mixer._takeBackControlInterpolant(e)), this;
  }
  /**
   * Returns the animation mixer of this animation action.
   *
   * @return {AnimationMixer} The animation mixer.
   */
  getMixer() {
    return this._mixer;
  }
  /**
   * Returns the animation clip of this animation action.
   *
   * @return {AnimationClip} The animation clip.
   */
  getClip() {
    return this._clip;
  }
  /**
   * Returns the root object of this animation action.
   *
   * @return {Object3D} The root object.
   */
  getRoot() {
    return this._localRoot || this._mixer._root;
  }
  // Interna
  _update(e, t, i, n) {
    if (!this.enabled) {
      this._updateWeight(e);
      return;
    }
    const s = this._startTime;
    if (s !== null) {
      const l = (e - s) * i;
      l < 0 || i === 0 ? t = 0 : (this._startTime = null, t = i * l);
    }
    t *= this._updateTimeScale(e);
    const a = this._updateTime(t), o = this._updateWeight(e);
    if (o > 0) {
      const l = this._interpolants, c = this._propertyBindings;
      switch (this.blendMode) {
        case ad:
          for (let h = 0, d = l.length; h !== d; ++h)
            l[h].evaluate(a), c[h].accumulateAdditive(o);
          break;
        case Gl:
        default:
          for (let h = 0, d = l.length; h !== d; ++h)
            l[h].evaluate(a), c[h].accumulate(n, o);
      }
    }
  }
  _updateWeight(e) {
    let t = 0;
    if (this.enabled) {
      t = this.weight;
      const i = this._weightInterpolant;
      if (i !== null) {
        const n = i.evaluate(e)[0];
        t *= n, e > i.parameterPositions[1] && (this.stopFading(), n === 0 && (this.enabled = !1));
      }
    }
    return this._effectiveWeight = t, t;
  }
  _updateTimeScale(e) {
    let t = 0;
    if (!this.paused) {
      t = this.timeScale;
      const i = this._timeScaleInterpolant;
      if (i !== null) {
        const n = i.evaluate(e)[0];
        t *= n, e > i.parameterPositions[1] && (this.stopWarping(), t === 0 ? this.paused = !0 : this.timeScale = t);
      }
    }
    return this._effectiveTimeScale = t, t;
  }
  _updateTime(e) {
    const t = this._clip.duration, i = this.loop;
    let n = this.time + e, s = this._loopCount;
    const a = i === rd;
    if (e === 0)
      return s === -1 ? n : a && (s & 1) === 1 ? t - n : n;
    if (i === $f) {
      s === -1 && (this._loopCount = 0, this._setEndings(!0, !0, !1));
      e: {
        if (n >= t)
          n = t;
        else if (n < 0)
          n = 0;
        else {
          this.time = n;
          break e;
        }
        this.clampWhenFinished ? this.paused = !0 : this.enabled = !1, this.time = n, this._mixer.dispatchEvent({
          type: "finished",
          action: this,
          direction: e < 0 ? -1 : 1
        });
      }
    } else {
      if (s === -1 && (e >= 0 ? (s = 0, this._setEndings(!0, this.repetitions === 0, a)) : this._setEndings(this.repetitions === 0, !0, a)), n >= t || n < 0) {
        const o = Math.floor(n / t);
        n -= t * o, s += Math.abs(o);
        const l = this.repetitions - s;
        if (l <= 0)
          this.clampWhenFinished ? this.paused = !0 : this.enabled = !1, n = e > 0 ? t : 0, this.time = n, this._mixer.dispatchEvent({
            type: "finished",
            action: this,
            direction: e > 0 ? 1 : -1
          });
        else {
          if (l === 1) {
            const c = e < 0;
            this._setEndings(c, !c, a);
          } else
            this._setEndings(!1, !1, a);
          this._loopCount = s, this.time = n, this._mixer.dispatchEvent({
            type: "loop",
            action: this,
            loopDelta: o
          });
        }
      } else
        this.time = n;
      if (a && (s & 1) === 1)
        return t - n;
    }
    return n;
  }
  _setEndings(e, t, i) {
    const n = this._interpolantSettings;
    i ? (n.endingStart = us, n.endingEnd = us) : (e ? n.endingStart = this.zeroSlopeAtStart ? us : ds : n.endingStart = oa, t ? n.endingEnd = this.zeroSlopeAtEnd ? us : ds : n.endingEnd = oa);
  }
  _scheduleFading(e, t, i) {
    const n = this._mixer, s = n.time;
    let a = this._weightInterpolant;
    a === null && (a = n._lendControlInterpolant(), this._weightInterpolant = a);
    const o = a.parameterPositions, l = a.sampleValues;
    return o[0] = s, l[0] = t, o[1] = s + e, l[1] = i, this;
  }
}
const D0 = new Float32Array(1);
class ng extends sn {
  /**
   * Constructs a new animation mixer.
   *
   * @param {Object3D} root - The object whose animations shall be played by this mixer.
   */
  constructor(e) {
    super(), this._root = e, this._initMemoryManager(), this._accuIndex = 0, this.time = 0, this.timeScale = 1;
  }
  _bindAction(e, t) {
    const i = e._localRoot || this._root, n = e._clip.tracks, s = n.length, a = e._propertyBindings, o = e._interpolants, l = i.uuid, c = this._bindingsByRootAndName;
    let h = c[l];
    h === void 0 && (h = {}, c[l] = h);
    for (let d = 0; d !== s; ++d) {
      const u = n[d], p = u.name;
      let m = h[p];
      if (m !== void 0)
        ++m.referenceCount, a[d] = m;
      else {
        if (m = a[d], m !== void 0) {
          m._cacheIndex === null && (++m.referenceCount, this._addInactiveBinding(m, l, p));
          continue;
        }
        const _ = t && t._propertyBindings[d].binding.parsedPath;
        m = new tg(
          st.create(i, p, _),
          u.ValueTypeName,
          u.getValueSize()
        ), ++m.referenceCount, this._addInactiveBinding(m, l, p), a[d] = m;
      }
      o[d].resultBuffer = m.buffer;
    }
  }
  _activateAction(e) {
    if (!this._isActiveAction(e)) {
      if (e._cacheIndex === null) {
        const i = (e._localRoot || this._root).uuid, n = e._clip.uuid, s = this._actionsByClip[n];
        this._bindAction(
          e,
          s && s.knownActions[0]
        ), this._addInactiveAction(e, n, i);
      }
      const t = e._propertyBindings;
      for (let i = 0, n = t.length; i !== n; ++i) {
        const s = t[i];
        s.useCount++ === 0 && (this._lendBinding(s), s.saveOriginalState());
      }
      this._lendAction(e);
    }
  }
  _deactivateAction(e) {
    if (this._isActiveAction(e)) {
      const t = e._propertyBindings;
      for (let i = 0, n = t.length; i !== n; ++i) {
        const s = t[i];
        --s.useCount === 0 && (s.restoreOriginalState(), this._takeBackBinding(s));
      }
      this._takeBackAction(e);
    }
  }
  // Memory manager
  _initMemoryManager() {
    this._actions = [], this._nActiveActions = 0, this._actionsByClip = {}, this._bindings = [], this._nActiveBindings = 0, this._bindingsByRootAndName = {}, this._controlInterpolants = [], this._nActiveControlInterpolants = 0;
    const e = this;
    this.stats = {
      actions: {
        get total() {
          return e._actions.length;
        },
        get inUse() {
          return e._nActiveActions;
        }
      },
      bindings: {
        get total() {
          return e._bindings.length;
        },
        get inUse() {
          return e._nActiveBindings;
        }
      },
      controlInterpolants: {
        get total() {
          return e._controlInterpolants.length;
        },
        get inUse() {
          return e._nActiveControlInterpolants;
        }
      }
    };
  }
  // Memory management for AnimationAction objects
  _isActiveAction(e) {
    const t = e._cacheIndex;
    return t !== null && t < this._nActiveActions;
  }
  _addInactiveAction(e, t, i) {
    const n = this._actions, s = this._actionsByClip;
    let a = s[t];
    if (a === void 0)
      a = {
        knownActions: [e],
        actionByRoot: {}
      }, e._byClipCacheIndex = 0, s[t] = a;
    else {
      const o = a.knownActions;
      e._byClipCacheIndex = o.length, o.push(e);
    }
    e._cacheIndex = n.length, n.push(e), a.actionByRoot[i] = e;
  }
  _removeInactiveAction(e) {
    const t = this._actions, i = t[t.length - 1], n = e._cacheIndex;
    i._cacheIndex = n, t[n] = i, t.pop(), e._cacheIndex = null;
    const s = e._clip.uuid, a = this._actionsByClip, o = a[s], l = o.knownActions, c = l[l.length - 1], h = e._byClipCacheIndex;
    c._byClipCacheIndex = h, l[h] = c, l.pop(), e._byClipCacheIndex = null;
    const d = o.actionByRoot, u = (e._localRoot || this._root).uuid;
    delete d[u], l.length === 0 && delete a[s], this._removeInactiveBindingsForAction(e);
  }
  _removeInactiveBindingsForAction(e) {
    const t = e._propertyBindings;
    for (let i = 0, n = t.length; i !== n; ++i) {
      const s = t[i];
      --s.referenceCount === 0 && this._removeInactiveBinding(s);
    }
  }
  _lendAction(e) {
    const t = this._actions, i = e._cacheIndex, n = this._nActiveActions++, s = t[n];
    e._cacheIndex = n, t[n] = e, s._cacheIndex = i, t[i] = s;
  }
  _takeBackAction(e) {
    const t = this._actions, i = e._cacheIndex, n = --this._nActiveActions, s = t[n];
    e._cacheIndex = n, t[n] = e, s._cacheIndex = i, t[i] = s;
  }
  // Memory management for PropertyMixer objects
  _addInactiveBinding(e, t, i) {
    const n = this._bindingsByRootAndName, s = this._bindings;
    let a = n[t];
    a === void 0 && (a = {}, n[t] = a), a[i] = e, e._cacheIndex = s.length, s.push(e);
  }
  _removeInactiveBinding(e) {
    const t = this._bindings, i = e.binding, n = i.rootNode.uuid, s = i.path, a = this._bindingsByRootAndName, o = a[n], l = t[t.length - 1], c = e._cacheIndex;
    l._cacheIndex = c, t[c] = l, t.pop(), delete o[s], Object.keys(o).length === 0 && delete a[n];
  }
  _lendBinding(e) {
    const t = this._bindings, i = e._cacheIndex, n = this._nActiveBindings++, s = t[n];
    e._cacheIndex = n, t[n] = e, s._cacheIndex = i, t[i] = s;
  }
  _takeBackBinding(e) {
    const t = this._bindings, i = e._cacheIndex, n = --this._nActiveBindings, s = t[n];
    e._cacheIndex = n, t[n] = e, s._cacheIndex = i, t[i] = s;
  }
  // Memory management of Interpolants for weight and time scale
  _lendControlInterpolant() {
    const e = this._controlInterpolants, t = this._nActiveControlInterpolants++;
    let i = e[t];
    return i === void 0 && (i = new Cd(
      new Float32Array(2),
      new Float32Array(2),
      1,
      D0
    ), i.__cacheIndex = t, e[t] = i), i;
  }
  _takeBackControlInterpolant(e) {
    const t = this._controlInterpolants, i = e.__cacheIndex, n = --this._nActiveControlInterpolants, s = t[n];
    e.__cacheIndex = n, t[n] = e, s.__cacheIndex = i, t[i] = s;
  }
  /**
   * Returns an instance of {@link AnimationAction} for the passed clip.
   *
   * If an action fitting the clip and root parameters doesn't yet exist, it
   * will be created by this method. Calling this method several times with the
   * same clip and root parameters always returns the same action.
   *
   * @param {AnimationClip|string} clip - An animation clip or alternatively the name of the animation clip.
   * @param {Object3D} [optionalRoot] - An alternative root object.
   * @param {(NormalAnimationBlendMode|AdditiveAnimationBlendMode)} [blendMode] - The blend mode.
   * @return {?AnimationAction} The animation action.
   */
  clipAction(e, t, i) {
    const n = t || this._root, s = n.uuid;
    let a = typeof e == "string" ? yr.findByName(n, e) : e;
    const o = a !== null ? a.uuid : e, l = this._actionsByClip[o];
    let c = null;
    if (i === void 0 && (a !== null ? i = a.blendMode : i = Gl), l !== void 0) {
      const d = l.actionByRoot[s];
      if (d !== void 0 && d.blendMode === i)
        return d;
      c = l.knownActions[0], a === null && (a = c._clip);
    }
    if (a === null) return null;
    const h = new ig(this, a, t, i);
    return this._bindAction(h, c), this._addInactiveAction(h, o, s), h;
  }
  /**
   * Returns an existing animation action for the passed clip.
   *
   * @param {AnimationClip|string} clip - An animation clip or alternatively the name of the animation clip.
   * @param {Object3D} [optionalRoot] - An alternative root object.
   * @return {?AnimationAction} The animation action. Returns `null` if no action was found.
   */
  existingAction(e, t) {
    const i = t || this._root, n = i.uuid, s = typeof e == "string" ? yr.findByName(i, e) : e, a = s ? s.uuid : e, o = this._actionsByClip[a];
    return o !== void 0 && o.actionByRoot[n] || null;
  }
  /**
   * Deactivates all previously scheduled actions on this mixer.
   *
   * @return {AnimationMixer} A reference to thi animation mixer.
   */
  stopAllAction() {
    const e = this._actions, t = this._nActiveActions;
    for (let i = t - 1; i >= 0; --i)
      e[i].stop();
    return this;
  }
  /**
   * Advances the global mixer time and updates the animation.
   *
   * This is usually done in the render loop by passing the delta
   * time from {@link Clock} or {@link Timer}.
   *
   * @param {number} deltaTime - The delta time in seconds.
   * @return {AnimationMixer} A reference to thi animation mixer.
   */
  update(e) {
    e *= this.timeScale;
    const t = this._actions, i = this._nActiveActions, n = this.time += e, s = Math.sign(e), a = this._accuIndex ^= 1;
    for (let c = 0; c !== i; ++c)
      t[c]._update(n, e, s, a);
    const o = this._bindings, l = this._nActiveBindings;
    for (let c = 0; c !== l; ++c)
      o[c].apply(a);
    return this;
  }
  /**
   * Sets the global mixer to a specific time and updates the animation accordingly.
   *
   * This is useful when you need to jump to an exact time in an animation. The
   * input parameter will be scaled by {@link AnimationMixer#timeScale}
   *
   * @param {number} time - The time to set in seconds.
   * @return {AnimationMixer} A reference to thi animation mixer.
   */
  setTime(e) {
    this.time = 0;
    for (let t = 0; t < this._actions.length; t++)
      this._actions[t].time = 0;
    return this.update(e);
  }
  /**
   * Returns this mixer's root object.
   *
   * @return {Object3D} The mixer's root object.
   */
  getRoot() {
    return this._root;
  }
  /**
   * Deallocates all memory resources for a clip. Before using this method make
   * sure to call {@link AnimationAction#stop} for all related actions.
   *
   * @param {AnimationClip} clip - The clip to uncache.
   */
  uncacheClip(e) {
    const t = this._actions, i = e.uuid, n = this._actionsByClip, s = n[i];
    if (s !== void 0) {
      const a = s.knownActions;
      for (let o = 0, l = a.length; o !== l; ++o) {
        const c = a[o];
        this._deactivateAction(c);
        const h = c._cacheIndex, d = t[t.length - 1];
        c._cacheIndex = null, c._byClipCacheIndex = null, d._cacheIndex = h, t[h] = d, t.pop(), this._removeInactiveBindingsForAction(c);
      }
      delete n[i];
    }
  }
  /**
   * Deallocates all memory resources for a root object. Before using this
   * method make sure to call {@link AnimationAction#stop} for all related
   * actions or alternatively {@link AnimationMixer#stopAllAction} when the
   * mixer operates on a single root.
   *
   * @param {Object3D} root - The root object to uncache.
   */
  uncacheRoot(e) {
    const t = e.uuid, i = this._actionsByClip;
    for (const a in i) {
      const o = i[a].actionByRoot, l = o[t];
      l !== void 0 && (this._deactivateAction(l), this._removeInactiveAction(l));
    }
    const n = this._bindingsByRootAndName, s = n[t];
    if (s !== void 0)
      for (const a in s) {
        const o = s[a];
        o.restoreOriginalState(), this._removeInactiveBinding(o);
      }
  }
  /**
   * Deallocates all memory resources for an action. The action is identified by the
   * given clip and an optional root object. Before using this method make
   * sure to call {@link AnimationAction#stop} to deactivate the action.
   *
   * @param {AnimationClip|string} clip - An animation clip or alternatively the name of the animation clip.
   * @param {Object3D} [optionalRoot] - An alternative root object.
   */
  uncacheAction(e, t) {
    const i = this.existingAction(e, t);
    i !== null && (this._deactivateAction(i), this._removeInactiveAction(i));
  }
}
class N0 extends cd {
  /**
   * Constructs a new 3D render target.
   *
   * @param {number} [width=1] - The width of the render target.
   * @param {number} [height=1] - The height of the render target.
   * @param {number} [depth=1] - The height of the render target.
   * @param {RenderTarget~Options} [options] - The configuration object.
   */
  constructor(e = 1, t = 1, i = 1, n = {}) {
    super(e, t, n), this.isRenderTarget3D = !0, this.depth = i, this.texture = new Xl(null, e, t, i), this._setTextureOptions(n), this.texture.isRenderTargetTexture = !0;
  }
}
class Bd {
  /**
   * Constructs a new uniform.
   *
   * @param {any} value - The uniform value.
   */
  constructor(e) {
    this.value = e;
  }
  /**
   * Returns a new uniform with copied values from this instance.
   * If the value has a `clone()` method, the value is cloned as well.
   *
   * @return {Uniform} A clone of this instance.
   */
  clone() {
    return new Bd(this.value.clone === void 0 ? this.value : this.value.clone());
  }
}
let U0 = 0;
class O0 extends sn {
  /**
   * Constructs a new uniforms group.
   */
  constructor() {
    super(), this.isUniformsGroup = !0, Object.defineProperty(this, "id", { value: U0++ }), this.name = "", this.usage = ha, this.uniforms = [];
  }
  /**
   * Adds the given uniform to this uniforms group.
   *
   * @param {Uniform} uniform - The uniform to add.
   * @return {UniformsGroup} A reference to this uniforms group.
   */
  add(e) {
    return this.uniforms.push(e), this;
  }
  /**
   * Removes the given uniform from this uniforms group.
   *
   * @param {Uniform} uniform - The uniform to remove.
   * @return {UniformsGroup} A reference to this uniforms group.
   */
  remove(e) {
    const t = this.uniforms.indexOf(e);
    return t !== -1 && this.uniforms.splice(t, 1), this;
  }
  /**
   * Sets the name of this uniforms group.
   *
   * @param {string} name - The name to set.
   * @return {UniformsGroup} A reference to this uniforms group.
   */
  setName(e) {
    return this.name = e, this;
  }
  /**
   * Sets the usage of this uniforms group.
   *
   * @param {(StaticDrawUsage|DynamicDrawUsage|StreamDrawUsage|StaticReadUsage|DynamicReadUsage|StreamReadUsage|StaticCopyUsage|DynamicCopyUsage|StreamCopyUsage)} value - The usage to set.
   * @return {UniformsGroup} A reference to this uniforms group.
   */
  setUsage(e) {
    return this.usage = e, this;
  }
  /**
   * Frees the GPU-related resources allocated by this instance. Call this
   * method whenever this instance is no longer used in your app.
   *
   * @fires Texture#dispose
   */
  dispose() {
    this.dispatchEvent({ type: "dispose" });
  }
  /**
   * Copies the values of the given uniforms group to this instance.
   *
   * @param {UniformsGroup} source - The uniforms group to copy.
   * @return {UniformsGroup} A reference to this uniforms group.
   */
  copy(e) {
    this.name = e.name, this.usage = e.usage;
    const t = e.uniforms;
    this.uniforms.length = 0;
    for (let i = 0, n = t.length; i < n; i++) {
      const s = Array.isArray(t[i]) ? t[i] : [t[i]];
      for (let a = 0; a < s.length; a++)
        this.uniforms.push(s[a].clone());
    }
    return this;
  }
  /**
   * Returns a new uniforms group with copied values from this instance.
   *
   * @return {UniformsGroup} A clone of this instance.
   */
  clone() {
    return new this.constructor().copy(this);
  }
}
class Nl extends Kl {
  /**
   * Constructs a new instanced interleaved buffer.
   *
   * @param {TypedArray} array - A typed array with a shared buffer storing attribute data.
   * @param {number} stride - The number of typed-array elements per vertex.
   * @param {number} [meshPerAttribute=1] - Defines how often a value of this interleaved buffer should be repeated.
   */
  constructor(e, t, i = 1) {
    super(e, t), this.isInstancedInterleavedBuffer = !0, this.meshPerAttribute = i;
  }
  copy(e) {
    return super.copy(e), this.meshPerAttribute = e.meshPerAttribute, this;
  }
  clone(e) {
    const t = super.clone(e);
    return t.meshPerAttribute = this.meshPerAttribute, t;
  }
  toJSON(e) {
    const t = super.toJSON(e);
    return t.isInstancedInterleavedBuffer = !0, t.meshPerAttribute = this.meshPerAttribute, t;
  }
}
class F0 {
  /**
   * Constructs a new GL buffer attribute.
   *
   * @param {WebGLBuffer} buffer - The native WebGL buffer.
   * @param {number} type - The native data type (e.g. `gl.FLOAT`).
   * @param {number} itemSize - The item size.
   * @param {number} elementSize - The corresponding size (in bytes) for the given `type` parameter.
   * @param {number} count - The expected number of vertices in VBO.
   * @param {boolean} [normalized=false] - Whether the data are normalized or not.
   */
  constructor(e, t, i, n, s, a = !1) {
    this.isGLBufferAttribute = !0, this.name = "", this.buffer = e, this.type = t, this.itemSize = i, this.elementSize = n, this.count = s, this.normalized = a, this.version = 0;
  }
  /**
   * Flag to indicate that this attribute has changed and should be re-sent to
   * the GPU. Set this to `true` when you modify the value of the array.
   *
   * @type {number}
   * @default false
   * @param {boolean} value
   */
  set needsUpdate(e) {
    e === !0 && this.version++;
  }
  /**
   * Sets the given native WebGL buffer.
   *
   * @param {WebGLBuffer} buffer - The buffer to set.
   * @return {BufferAttribute} A reference to this instance.
   */
  setBuffer(e) {
    return this.buffer = e, this;
  }
  /**
   * Sets the given native data type and element size.
   *
   * @param {number} type - The native data type (e.g. `gl.FLOAT`).
   * @param {number} elementSize - The corresponding size (in bytes) for the given `type` parameter.
   * @return {BufferAttribute} A reference to this instance.
   */
  setType(e, t) {
    return this.type = e, this.elementSize = t, this;
  }
  /**
   * Sets the item size.
   *
   * @param {number} itemSize - The item size.
   * @return {BufferAttribute} A reference to this instance.
   */
  setItemSize(e) {
    return this.itemSize = e, this;
  }
  /**
   * Sets the count (the expected number of vertices in VBO).
   *
   * @param {number} count - The count.
   * @return {BufferAttribute} A reference to this instance.
   */
  setCount(e) {
    return this.count = e, this;
  }
}
const Ju = /* @__PURE__ */ new Ne();
let sg = class {
  /**
   * Constructs a new raycaster.
   *
   * @param {Vector3} origin - The origin vector where the ray casts from.
   * @param {Vector3} direction - The (normalized) direction vector that gives direction to the ray.
   * @param {number} [near=0] - All results returned are further away than near. Near can't be negative.
   * @param {number} [far=Infinity] - All results returned are closer than far. Far can't be lower than near.
   */
  constructor(e, t, i = 0, n = 1 / 0) {
    this.ray = new ws(e, t), this.near = i, this.far = n, this.camera = null, this.layers = new ql(), this.params = {
      Mesh: {},
      Line: { threshold: 1 },
      LOD: {},
      Points: { threshold: 1 },
      Sprite: {}
    };
  }
  /**
   * Updates the ray with a new origin and direction by copying the values from the arguments.
   *
   * @param {Vector3} origin - The origin vector where the ray casts from.
   * @param {Vector3} direction - The (normalized) direction vector that gives direction to the ray.
   */
  set(e, t) {
    this.ray.set(e, t);
  }
  /**
   * Uses the given coordinates and camera to compute a new origin and direction for the internal ray.
   *
   * @param {Vector2} coords - 2D coordinates of the mouse, in normalized device coordinates (NDC).
   * X and Y components should be between `-1` and `1`.
   * @param {Camera} camera - The camera from which the ray should originate.
   */
  setFromCamera(e, t) {
    t.isPerspectiveCamera ? (this.ray.origin.setFromMatrixPosition(t.matrixWorld), this.ray.direction.set(e.x, e.y, 0.5).unproject(t).sub(this.ray.origin).normalize(), this.camera = t) : t.isOrthographicCamera ? (this.ray.origin.set(e.x, e.y, (t.near + t.far) / (t.near - t.far)).unproject(t), this.ray.direction.set(0, 0, -1).transformDirection(t.matrixWorld), this.camera = t) : console.error("THREE.Raycaster: Unsupported camera type: " + t.type);
  }
  /**
   * Uses the given WebXR controller to compute a new origin and direction for the internal ray.
   *
   * @param {WebXRController} controller - The controller to copy the position and direction from.
   * @return {Raycaster} A reference to this raycaster.
   */
  setFromXRController(e) {
    return Ju.identity().extractRotation(e.matrixWorld), this.ray.origin.setFromMatrixPosition(e.matrixWorld), this.ray.direction.set(0, 0, -1).applyMatrix4(Ju), this;
  }
  /**
   * The intersection point of a raycaster intersection test.
   * @typedef {Object} Raycaster~Intersection
   * @property {number} distance - The distance from the ray's origin to the intersection point.
   * @property {number} distanceToRay -  Some 3D objects e.g. {@link Points} provide the distance of the
   * intersection to the nearest point on the ray. For other objects it will be `undefined`.
   * @property {Vector3} point - The intersection point, in world coordinates.
   * @property {Object} face - The face that has been intersected.
   * @property {number} faceIndex - The face index.
   * @property {Object3D} object - The 3D object that has been intersected.
   * @property {Vector2} uv - U,V coordinates at point of intersection.
   * @property {Vector2} uv1 - Second set of U,V coordinates at point of intersection.
   * @property {Vector3} uv1 - Interpolated normal vector at point of intersection.
   * @property {number} instanceId - The index number of the instance where the ray
   * intersects the {@link InstancedMesh}.
   */
  /**
   * Checks all intersection between the ray and the object with or without the
   * descendants. Intersections are returned sorted by distance, closest first.
   *
   * `Raycaster` delegates to the `raycast()` method of the passed 3D object, when
   * evaluating whether the ray intersects the object or not. This allows meshes to respond
   * differently to ray casting than lines or points.
   *
   * Note that for meshes, faces must be pointed towards the origin of the ray in order
   * to be detected; intersections of the ray passing through the back of a face will not
   * be detected. To raycast against both faces of an object, you'll want to set  {@link Material#side}
   * to `THREE.DoubleSide`.
   *
   * @param {Object3D} object - The 3D object to check for intersection with the ray.
   * @param {boolean} [recursive=true] - If set to `true`, it also checks all descendants.
   * Otherwise it only checks intersection with the object.
   * @param {Array<Raycaster~Intersection>} [intersects=[]] The target array that holds the result of the method.
   * @return {Array<Raycaster~Intersection>} An array holding the intersection points.
   */
  intersectObject(e, t = !0, i = []) {
    return Hh(e, this, i, t), i.sort(Qu), i;
  }
  /**
   * Checks all intersection between the ray and the objects with or without
   * the descendants. Intersections are returned sorted by distance, closest first.
   *
   * @param {Array<Object3D>} objects - The 3D objects to check for intersection with the ray.
   * @param {boolean} [recursive=true] - If set to `true`, it also checks all descendants.
   * Otherwise it only checks intersection with the object.
   * @param {Array<Raycaster~Intersection>} [intersects=[]] The target array that holds the result of the method.
   * @return {Array<Raycaster~Intersection>} An array holding the intersection points.
   */
  intersectObjects(e, t = !0, i = []) {
    for (let n = 0, s = e.length; n < s; n++)
      Hh(e[n], this, i, t);
    return i.sort(Qu), i;
  }
};
function Qu(r, e) {
  return r.distance - e.distance;
}
function Hh(r, e, t, i) {
  let n = !0;
  if (r.layers.test(e.layers) && r.raycast(e, t) === !1 && (n = !1), n === !0 && i === !0) {
    const s = r.children;
    for (let a = 0, o = s.length; a < o; a++)
      Hh(s[a], e, t, !0);
  }
}
let B0 = class {
  /**
   * Constructs a new timer.
   */
  constructor() {
    this._previousTime = 0, this._currentTime = 0, this._startTime = performance.now(), this._delta = 0, this._elapsed = 0, this._timescale = 1, this._document = null, this._pageVisibilityHandler = null;
  }
  /**
   * Connect the timer to the given document.Calling this method is not mandatory to
   * use the timer but enables the usage of the Page Visibility API to avoid large time
   * delta values.
   *
   * @param {Document} document - The document.
   */
  connect(e) {
    this._document = e, e.hidden !== void 0 && (this._pageVisibilityHandler = k0.bind(this), e.addEventListener("visibilitychange", this._pageVisibilityHandler, !1));
  }
  /**
   * Disconnects the timer from the DOM and also disables the usage of the Page Visibility API.
   */
  disconnect() {
    this._pageVisibilityHandler !== null && (this._document.removeEventListener("visibilitychange", this._pageVisibilityHandler), this._pageVisibilityHandler = null), this._document = null;
  }
  /**
   * Returns the time delta in seconds.
   *
   * @return {number} The time delta in second.
   */
  getDelta() {
    return this._delta / 1e3;
  }
  /**
   * Returns the elapsed time in seconds.
   *
   * @return {number} The elapsed time in second.
   */
  getElapsed() {
    return this._elapsed / 1e3;
  }
  /**
   * Returns the timescale.
   *
   * @return {number} The timescale.
   */
  getTimescale() {
    return this._timescale;
  }
  /**
   * Sets the given timescale which scale the time delta computation
   * in `update()`.
   *
   * @param {number} timescale - The timescale to set.
   * @return {Timer} A reference to this timer.
   */
  setTimescale(e) {
    return this._timescale = e, this;
  }
  /**
   * Resets the time computation for the current simulation step.
   *
   * @return {Timer} A reference to this timer.
   */
  reset() {
    return this._currentTime = performance.now() - this._startTime, this;
  }
  /**
   * Can be used to free all internal resources. Usually called when
   * the timer instance isn't required anymore.
   */
  dispose() {
    this.disconnect();
  }
  /**
   * Updates the internal state of the timer. This method should be called
   * once per simulation step and before you perform queries against the timer
   * (e.g. via `getDelta()`).
   *
   * @param {number} timestamp - The current time in milliseconds. Can be obtained
   * from the `requestAnimationFrame` callback argument. If not provided, the current
   * time will be determined with `performance.now`.
   * @return {Timer} A reference to this timer.
   */
  update(e) {
    return this._pageVisibilityHandler !== null && this._document.hidden === !0 ? this._delta = 0 : (this._previousTime = this._currentTime, this._currentTime = (e !== void 0 ? e : performance.now()) - this._startTime, this._delta = (this._currentTime - this._previousTime) * this._timescale, this._elapsed += this._delta), this;
  }
};
function k0() {
  this._document.hidden === !1 && this.reset();
}
class Vh {
  /**
   * Constructs a new spherical.
   *
   * @param {number} [radius=1] - The radius, or the Euclidean distance (straight-line distance) from the point to the origin.
   * @param {number} [phi=0] - The polar angle in radians from the y (up) axis.
   * @param {number} [theta=0] - The equator/azimuthal angle in radians around the y (up) axis.
   */
  constructor(e = 1, t = 0, i = 0) {
    this.radius = e, this.phi = t, this.theta = i;
  }
  /**
   * Sets the spherical components by copying the given values.
   *
   * @param {number} radius - The radius.
   * @param {number} phi - The polar angle.
   * @param {number} theta - The azimuthal angle.
   * @return {Spherical} A reference to this spherical.
   */
  set(e, t, i) {
    return this.radius = e, this.phi = t, this.theta = i, this;
  }
  /**
   * Copies the values of the given spherical to this instance.
   *
   * @param {Spherical} other - The spherical to copy.
   * @return {Spherical} A reference to this spherical.
   */
  copy(e) {
    return this.radius = e.radius, this.phi = e.phi, this.theta = e.theta, this;
  }
  /**
   * Restricts the polar angle [page:.phi phi] to be between `0.000001` and pi -
   * `0.000001`.
   *
   * @return {Spherical} A reference to this spherical.
   */
  makeSafe() {
    return this.phi = Fe(this.phi, 1e-6, Math.PI - 1e-6), this;
  }
  /**
   * Sets the spherical components from the given vector which is assumed to hold
   * Cartesian coordinates.
   *
   * @param {Vector3} v - The vector to set.
   * @return {Spherical} A reference to this spherical.
   */
  setFromVector3(e) {
    return this.setFromCartesianCoords(e.x, e.y, e.z);
  }
  /**
   * Sets the spherical components from the given Cartesian coordinates.
   *
   * @param {number} x - The x value.
   * @param {number} y - The y value.
   * @param {number} z - The z value.
   * @return {Spherical} A reference to this spherical.
   */
  setFromCartesianCoords(e, t, i) {
    return this.radius = Math.sqrt(e * e + t * t + i * i), this.radius === 0 ? (this.theta = 0, this.phi = 0) : (this.theta = Math.atan2(e, i), this.phi = Math.acos(Fe(t / this.radius, -1, 1))), this;
  }
  /**
   * Returns a new spherical with copied values from this instance.
   *
   * @return {Spherical} A clone of this instance.
   */
  clone() {
    return new this.constructor().copy(this);
  }
}
class z0 {
  /**
   * Constructs a new cylindrical.
   *
   * @param {number} [radius=1] - The distance from the origin to a point in the x-z plane.
   * @param {number} [theta=0] - A counterclockwise angle in the x-z plane measured in radians from the positive z-axis.
   * @param {number} [y=0] - The height above the x-z plane.
   */
  constructor(e = 1, t = 0, i = 0) {
    this.radius = e, this.theta = t, this.y = i;
  }
  /**
   * Sets the cylindrical components by copying the given values.
   *
   * @param {number} radius - The radius.
   * @param {number} theta - The theta angle.
   * @param {number} y - The height value.
   * @return {Cylindrical} A reference to this cylindrical.
   */
  set(e, t, i) {
    return this.radius = e, this.theta = t, this.y = i, this;
  }
  /**
   * Copies the values of the given cylindrical to this instance.
   *
   * @param {Cylindrical} other - The cylindrical to copy.
   * @return {Cylindrical} A reference to this cylindrical.
   */
  copy(e) {
    return this.radius = e.radius, this.theta = e.theta, this.y = e.y, this;
  }
  /**
   * Sets the cylindrical components from the given vector which is assumed to hold
   * Cartesian coordinates.
   *
   * @param {Vector3} v - The vector to set.
   * @return {Cylindrical} A reference to this cylindrical.
   */
  setFromVector3(e) {
    return this.setFromCartesianCoords(e.x, e.y, e.z);
  }
  /**
   * Sets the cylindrical components from the given Cartesian coordinates.
   *
   * @param {number} x - The x value.
   * @param {number} y - The x value.
   * @param {number} z - The x value.
   * @return {Cylindrical} A reference to this cylindrical.
   */
  setFromCartesianCoords(e, t, i) {
    return this.radius = Math.sqrt(e * e + i * i), this.theta = Math.atan2(e, i), this.y = t, this;
  }
  /**
   * Returns a new cylindrical with copied values from this instance.
   *
   * @return {Cylindrical} A clone of this instance.
   */
  clone() {
    return new this.constructor().copy(this);
  }
}
class kd {
  /**
   * Constructs a new 2x2 matrix. The arguments are supposed to be
   * in row-major order. If no arguments are provided, the constructor
   * initializes the matrix as an identity matrix.
   *
   * @param {number} [n11] - 1-1 matrix element.
   * @param {number} [n12] - 1-2 matrix element.
   * @param {number} [n21] - 2-1 matrix element.
   * @param {number} [n22] - 2-2 matrix element.
   */
  constructor(e, t, i, n) {
    kd.prototype.isMatrix2 = !0, this.elements = [
      1,
      0,
      0,
      1
    ], e !== void 0 && this.set(e, t, i, n);
  }
  /**
   * Sets this matrix to the 2x2 identity matrix.
   *
   * @return {Matrix2} A reference to this matrix.
   */
  identity() {
    return this.set(
      1,
      0,
      0,
      1
    ), this;
  }
  /**
   * Sets the elements of the matrix from the given array.
   *
   * @param {Array<number>} array - The matrix elements in column-major order.
   * @param {number} [offset=0] - Index of the first element in the array.
   * @return {Matrix2} A reference to this matrix.
   */
  fromArray(e, t = 0) {
    for (let i = 0; i < 4; i++)
      this.elements[i] = e[i + t];
    return this;
  }
  /**
   * Sets the elements of the matrix.The arguments are supposed to be
   * in row-major order.
   *
   * @param {number} n11 - 1-1 matrix element.
   * @param {number} n12 - 1-2 matrix element.
   * @param {number} n21 - 2-1 matrix element.
   * @param {number} n22 - 2-2 matrix element.
   * @return {Matrix2} A reference to this matrix.
   */
  set(e, t, i, n) {
    const s = this.elements;
    return s[0] = e, s[2] = t, s[1] = i, s[3] = n, this;
  }
}
const ep = /* @__PURE__ */ new H();
class H0 {
  /**
   * Constructs a new bounding box.
   *
   * @param {Vector2} [min=(Infinity,Infinity)] - A vector representing the lower boundary of the box.
   * @param {Vector2} [max=(-Infinity,-Infinity)] - A vector representing the upper boundary of the box.
   */
  constructor(e = new H(1 / 0, 1 / 0), t = new H(-1 / 0, -1 / 0)) {
    this.isBox2 = !0, this.min = e, this.max = t;
  }
  /**
   * Sets the lower and upper boundaries of this box.
   * Please note that this method only copies the values from the given objects.
   *
   * @param {Vector2} min - The lower boundary of the box.
   * @param {Vector2} max - The upper boundary of the box.
   * @return {Box2} A reference to this bounding box.
   */
  set(e, t) {
    return this.min.copy(e), this.max.copy(t), this;
  }
  /**
   * Sets the upper and lower bounds of this box so it encloses the position data
   * in the given array.
   *
   * @param {Array<Vector2>} points - An array holding 2D position data as instances of {@link Vector2}.
   * @return {Box2} A reference to this bounding box.
   */
  setFromPoints(e) {
    this.makeEmpty();
    for (let t = 0, i = e.length; t < i; t++)
      this.expandByPoint(e[t]);
    return this;
  }
  /**
   * Centers this box on the given center vector and sets this box's width, height and
   * depth to the given size values.
   *
   * @param {Vector2} center - The center of the box.
   * @param {Vector2} size - The x and y dimensions of the box.
   * @return {Box2} A reference to this bounding box.
   */
  setFromCenterAndSize(e, t) {
    const i = ep.copy(t).multiplyScalar(0.5);
    return this.min.copy(e).sub(i), this.max.copy(e).add(i), this;
  }
  /**
   * Returns a new box with copied values from this instance.
   *
   * @return {Box2} A clone of this instance.
   */
  clone() {
    return new this.constructor().copy(this);
  }
  /**
   * Copies the values of the given box to this instance.
   *
   * @param {Box2} box - The box to copy.
   * @return {Box2} A reference to this bounding box.
   */
  copy(e) {
    return this.min.copy(e.min), this.max.copy(e.max), this;
  }
  /**
   * Makes this box empty which means in encloses a zero space in 2D.
   *
   * @return {Box2} A reference to this bounding box.
   */
  makeEmpty() {
    return this.min.x = this.min.y = 1 / 0, this.max.x = this.max.y = -1 / 0, this;
  }
  /**
   * Returns true if this box includes zero points within its bounds.
   * Note that a box with equal lower and upper bounds still includes one
   * point, the one both bounds share.
   *
   * @return {boolean} Whether this box is empty or not.
   */
  isEmpty() {
    return this.max.x < this.min.x || this.max.y < this.min.y;
  }
  /**
   * Returns the center point of this box.
   *
   * @param {Vector2} target - The target vector that is used to store the method's result.
   * @return {Vector2} The center point.
   */
  getCenter(e) {
    return this.isEmpty() ? e.set(0, 0) : e.addVectors(this.min, this.max).multiplyScalar(0.5);
  }
  /**
   * Returns the dimensions of this box.
   *
   * @param {Vector2} target - The target vector that is used to store the method's result.
   * @return {Vector2} The size.
   */
  getSize(e) {
    return this.isEmpty() ? e.set(0, 0) : e.subVectors(this.max, this.min);
  }
  /**
   * Expands the boundaries of this box to include the given point.
   *
   * @param {Vector2} point - The point that should be included by the bounding box.
   * @return {Box2} A reference to this bounding box.
   */
  expandByPoint(e) {
    return this.min.min(e), this.max.max(e), this;
  }
  /**
   * Expands this box equilaterally by the given vector. The width of this
   * box will be expanded by the x component of the vector in both
   * directions. The height of this box will be expanded by the y component of
   * the vector in both directions.
   *
   * @param {Vector2} vector - The vector that should expand the bounding box.
   * @return {Box2} A reference to this bounding box.
   */
  expandByVector(e) {
    return this.min.sub(e), this.max.add(e), this;
  }
  /**
   * Expands each dimension of the box by the given scalar. If negative, the
   * dimensions of the box will be contracted.
   *
   * @param {number} scalar - The scalar value that should expand the bounding box.
   * @return {Box2} A reference to this bounding box.
   */
  expandByScalar(e) {
    return this.min.addScalar(-e), this.max.addScalar(e), this;
  }
  /**
   * Returns `true` if the given point lies within or on the boundaries of this box.
   *
   * @param {Vector2} point - The point to test.
   * @return {boolean} Whether the bounding box contains the given point or not.
   */
  containsPoint(e) {
    return e.x >= this.min.x && e.x <= this.max.x && e.y >= this.min.y && e.y <= this.max.y;
  }
  /**
   * Returns `true` if this bounding box includes the entirety of the given bounding box.
   * If this box and the given one are identical, this function also returns `true`.
   *
   * @param {Box2} box - The bounding box to test.
   * @return {boolean} Whether the bounding box contains the given bounding box or not.
   */
  containsBox(e) {
    return this.min.x <= e.min.x && e.max.x <= this.max.x && this.min.y <= e.min.y && e.max.y <= this.max.y;
  }
  /**
   * Returns a point as a proportion of this box's width and height.
   *
   * @param {Vector2} point - A point in 2D space.
   * @param {Vector2} target - The target vector that is used to store the method's result.
   * @return {Vector2} A point as a proportion of this box's width and height.
   */
  getParameter(e, t) {
    return t.set(
      (e.x - this.min.x) / (this.max.x - this.min.x),
      (e.y - this.min.y) / (this.max.y - this.min.y)
    );
  }
  /**
   * Returns `true` if the given bounding box intersects with this bounding box.
   *
   * @param {Box2} box - The bounding box to test.
   * @return {boolean} Whether the given bounding box intersects with this bounding box.
   */
  intersectsBox(e) {
    return e.max.x >= this.min.x && e.min.x <= this.max.x && e.max.y >= this.min.y && e.min.y <= this.max.y;
  }
  /**
   * Clamps the given point within the bounds of this box.
   *
   * @param {Vector2} point - The point to clamp.
   * @param {Vector2} target - The target vector that is used to store the method's result.
   * @return {Vector2} The clamped point.
   */
  clampPoint(e, t) {
    return t.copy(e).clamp(this.min, this.max);
  }
  /**
   * Returns the euclidean distance from any edge of this box to the specified point. If
   * the given point lies inside of this box, the distance will be `0`.
   *
   * @param {Vector2} point - The point to compute the distance to.
   * @return {number} The euclidean distance.
   */
  distanceToPoint(e) {
    return this.clampPoint(e, ep).distanceTo(e);
  }
  /**
   * Computes the intersection of this bounding box and the given one, setting the upper
   * bound of this box to the lesser of the two boxes' upper bounds and the
   * lower bound of this box to the greater of the two boxes' lower bounds. If
   * there's no overlap, makes this box empty.
   *
   * @param {Box2} box - The bounding box to intersect with.
   * @return {Box2} A reference to this bounding box.
   */
  intersect(e) {
    return this.min.max(e.min), this.max.min(e.max), this.isEmpty() && this.makeEmpty(), this;
  }
  /**
   * Computes the union of this box and another and the given one, setting the upper
   * bound of this box to the greater of the two boxes' upper bounds and the
   * lower bound of this box to the lesser of the two boxes' lower bounds.
   *
   * @param {Box2} box - The bounding box that will be unioned with this instance.
   * @return {Box2} A reference to this bounding box.
   */
  union(e) {
    return this.min.min(e.min), this.max.max(e.max), this;
  }
  /**
   * Adds the given offset to both the upper and lower bounds of this bounding box,
   * effectively moving it in 2D space.
   *
   * @param {Vector2} offset - The offset that should be used to translate the bounding box.
   * @return {Box2} A reference to this bounding box.
   */
  translate(e) {
    return this.min.add(e), this.max.add(e), this;
  }
  /**
   * Returns `true` if this bounding box is equal with the given one.
   *
   * @param {Box2} box - The box to test for equality.
   * @return {boolean} Whether this bounding box is equal with the given one.
   */
  equals(e) {
    return e.min.equals(this.min) && e.max.equals(this.max);
  }
}
const tp = /* @__PURE__ */ new b(), po = /* @__PURE__ */ new b(), Ys = /* @__PURE__ */ new b(), js = /* @__PURE__ */ new b(), th = /* @__PURE__ */ new b(), V0 = /* @__PURE__ */ new b(), G0 = /* @__PURE__ */ new b();
class rg {
  /**
   * Constructs a new line segment.
   *
   * @param {Vector3} [start=(0,0,0)] - Start of the line segment.
   * @param {Vector3} [end=(0,0,0)] - End of the line segment.
   */
  constructor(e = new b(), t = new b()) {
    this.start = e, this.end = t;
  }
  /**
   * Sets the start and end values by copying the given vectors.
   *
   * @param {Vector3} start - The start point.
   * @param {Vector3} end - The end point.
   * @return {Line3} A reference to this line segment.
   */
  set(e, t) {
    return this.start.copy(e), this.end.copy(t), this;
  }
  /**
   * Copies the values of the given line segment to this instance.
   *
   * @param {Line3} line - The line segment to copy.
   * @return {Line3} A reference to this line segment.
   */
  copy(e) {
    return this.start.copy(e.start), this.end.copy(e.end), this;
  }
  /**
   * Returns the center of the line segment.
   *
   * @param {Vector3} target - The target vector that is used to store the method's result.
   * @return {Vector3} The center point.
   */
  getCenter(e) {
    return e.addVectors(this.start, this.end).multiplyScalar(0.5);
  }
  /**
   * Returns the delta vector of the line segment's start and end point.
   *
   * @param {Vector3} target - The target vector that is used to store the method's result.
   * @return {Vector3} The delta vector.
   */
  delta(e) {
    return e.subVectors(this.end, this.start);
  }
  /**
   * Returns the squared Euclidean distance between the line' start and end point.
   *
   * @return {number} The squared Euclidean distance.
   */
  distanceSq() {
    return this.start.distanceToSquared(this.end);
  }
  /**
   * Returns the Euclidean distance between the line' start and end point.
   *
   * @return {number} The Euclidean distance.
   */
  distance() {
    return this.start.distanceTo(this.end);
  }
  /**
   * Returns a vector at a certain position along the line segment.
   *
   * @param {number} t - A value between `[0,1]` to represent a position along the line segment.
   * @param {Vector3} target - The target vector that is used to store the method's result.
   * @return {Vector3} The delta vector.
   */
  at(e, t) {
    return this.delta(t).multiplyScalar(e).add(this.start);
  }
  /**
   * Returns a point parameter based on the closest point as projected on the line segment.
   *
   * @param {Vector3} point - The point for which to return a point parameter.
   * @param {boolean} clampToLine - Whether to clamp the result to the range `[0,1]` or not.
   * @return {number} The point parameter.
   */
  closestPointToPointParameter(e, t) {
    tp.subVectors(e, this.start), po.subVectors(this.end, this.start);
    const i = po.dot(po);
    let s = po.dot(tp) / i;
    return t && (s = Fe(s, 0, 1)), s;
  }
  /**
   * Returns the closest point on the line for a given point.
   *
   * @param {Vector3} point - The point to compute the closest point on the line for.
   * @param {boolean} clampToLine - Whether to clamp the result to the range `[0,1]` or not.
   * @param {Vector3} target - The target vector that is used to store the method's result.
   * @return {Vector3} The closest point on the line.
   */
  closestPointToPoint(e, t, i) {
    const n = this.closestPointToPointParameter(e, t);
    return this.delta(i).multiplyScalar(n).add(this.start);
  }
  /**
   * Returns the closest squared distance between this line segment and the given one.
   *
   * @param {Line3} line - The line segment to compute the closest squared distance to.
   * @param {Vector3} [c1] - The closest point on this line segment.
   * @param {Vector3} [c2] - The closest point on the given line segment.
   * @return {number} The squared distance between this line segment and the given one.
   */
  distanceSqToLine3(e, t = V0, i = G0) {
    const n = 10000000000000001e-32;
    let s, a;
    const o = this.start, l = e.start, c = this.end, h = e.end;
    Ys.subVectors(c, o), js.subVectors(h, l), th.subVectors(o, l);
    const d = Ys.dot(Ys), u = js.dot(js), p = js.dot(th);
    if (d <= n && u <= n)
      return t.copy(o), i.copy(l), t.sub(i), t.dot(t);
    if (d <= n)
      s = 0, a = p / u, a = Fe(a, 0, 1);
    else {
      const m = Ys.dot(th);
      if (u <= n)
        a = 0, s = Fe(-m / d, 0, 1);
      else {
        const _ = Ys.dot(js), g = d * u - _ * _;
        g !== 0 ? s = Fe((_ * p - m * u) / g, 0, 1) : s = 0, a = (_ * s + p) / u, a < 0 ? (a = 0, s = Fe(-m / d, 0, 1)) : a > 1 && (a = 1, s = Fe((_ - m) / d, 0, 1));
      }
    }
    return t.copy(o).add(Ys.multiplyScalar(s)), i.copy(l).add(js.multiplyScalar(a)), t.sub(i), t.dot(t);
  }
  /**
   * Applies a 4x4 transformation matrix to this line segment.
   *
   * @param {Matrix4} matrix - The transformation matrix.
   * @return {Line3} A reference to this line segment.
   */
  applyMatrix4(e) {
    return this.start.applyMatrix4(e), this.end.applyMatrix4(e), this;
  }
  /**
   * Returns `true` if this line segment is equal with the given one.
   *
   * @param {Line3} line - The line segment to test for equality.
   * @return {boolean} Whether this line segment is equal with the given one.
   */
  equals(e) {
    return e.start.equals(this.start) && e.end.equals(this.end);
  }
  /**
   * Returns a new line segment with copied values from this instance.
   *
   * @return {Line3} A clone of this instance.
   */
  clone() {
    return new this.constructor().copy(this);
  }
}
const ip = /* @__PURE__ */ new b();
class W0 extends tt {
  /**
   * Constructs a new spot light helper.
   *
   * @param {HemisphereLight} light - The light to be visualized.
   * @param {number|Color|string} [color] - The helper's color. If not set, the helper will take
   * the color of the light.
   */
  constructor(e, t) {
    super(), this.light = e, this.matrixAutoUpdate = !1, this.color = t, this.type = "SpotLightHelper";
    const i = new Ue(), n = [
      0,
      0,
      0,
      0,
      0,
      1,
      0,
      0,
      0,
      1,
      0,
      1,
      0,
      0,
      0,
      -1,
      0,
      1,
      0,
      0,
      0,
      0,
      1,
      1,
      0,
      0,
      0,
      0,
      -1,
      1
    ];
    for (let a = 0, o = 1, l = 32; a < l; a++, o++) {
      const c = a / l * Math.PI * 2, h = o / l * Math.PI * 2;
      n.push(
        Math.cos(c),
        Math.sin(c),
        1,
        Math.cos(h),
        Math.sin(h),
        1
      );
    }
    i.setAttribute("position", new ve(n, 3));
    const s = new It({ fog: !1, toneMapped: !1 });
    this.cone = new ei(i, s), this.add(this.cone), this.update();
  }
  /**
   * Frees the GPU-related resources allocated by this instance. Call this
   * method whenever this instance is no longer used in your app.
   */
  dispose() {
    this.cone.geometry.dispose(), this.cone.material.dispose();
  }
  /**
   * Updates the helper to match the position and direction of the
   * light being visualized.
   */
  update() {
    this.light.updateWorldMatrix(!0, !1), this.light.target.updateWorldMatrix(!0, !1), this.parent ? (this.parent.updateWorldMatrix(!0), this.matrix.copy(this.parent.matrixWorld).invert().multiply(this.light.matrixWorld)) : this.matrix.copy(this.light.matrixWorld), this.matrixWorld.copy(this.light.matrixWorld);
    const e = this.light.distance ? this.light.distance : 1e3, t = e * Math.tan(this.light.angle);
    this.cone.scale.set(t, t, e), ip.setFromMatrixPosition(this.light.target.matrixWorld), this.cone.lookAt(ip), this.color !== void 0 ? this.cone.material.color.set(this.color) : this.cone.material.color.copy(this.light.color);
  }
}
const Tn = /* @__PURE__ */ new b(), fo = /* @__PURE__ */ new Ne(), ih = /* @__PURE__ */ new Ne();
class X0 extends ei {
  /**
   * Constructs a new skeleton helper.
   *
   * @param {Object3D} object -  Usually an instance of {@link SkinnedMesh}. However, any 3D object
   * can be used if it represents a hierarchy of bones (see {@link Bone}).
   */
  constructor(e) {
    const t = ag(e), i = new Ue(), n = [], s = [];
    for (let c = 0; c < t.length; c++) {
      const h = t[c];
      h.parent && h.parent.isBone && (n.push(0, 0, 0), n.push(0, 0, 0), s.push(0, 0, 0), s.push(0, 0, 0));
    }
    i.setAttribute("position", new ve(n, 3)), i.setAttribute("color", new ve(s, 3));
    const a = new It({ vertexColors: !0, depthTest: !1, depthWrite: !1, toneMapped: !1, transparent: !0 });
    super(i, a), this.isSkeletonHelper = !0, this.type = "SkeletonHelper", this.root = e, this.bones = t, this.matrix = e.matrixWorld, this.matrixAutoUpdate = !1;
    const o = new oe(255), l = new oe(65280);
    this.setColors(o, l);
  }
  updateMatrixWorld(e) {
    const t = this.bones, i = this.geometry, n = i.getAttribute("position");
    ih.copy(this.root.matrixWorld).invert();
    for (let s = 0, a = 0; s < t.length; s++) {
      const o = t[s];
      o.parent && o.parent.isBone && (fo.multiplyMatrices(ih, o.matrixWorld), Tn.setFromMatrixPosition(fo), n.setXYZ(a, Tn.x, Tn.y, Tn.z), fo.multiplyMatrices(ih, o.parent.matrixWorld), Tn.setFromMatrixPosition(fo), n.setXYZ(a + 1, Tn.x, Tn.y, Tn.z), a += 2);
    }
    i.getAttribute("position").needsUpdate = !0, super.updateMatrixWorld(e);
  }
  /**
   * Defines the colors of the helper.
   *
   * @param {Color} color1 - The first line color for each bone.
   * @param {Color} color2 - The second line color for each bone.
   * @return {SkeletonHelper} A reference to this helper.
   */
  setColors(e, t) {
    const n = this.geometry.getAttribute("color");
    for (let s = 0; s < n.count; s += 2)
      n.setXYZ(s, e.r, e.g, e.b), n.setXYZ(s + 1, t.r, t.g, t.b);
    return n.needsUpdate = !0, this;
  }
  /**
   * Frees the GPU-related resources allocated by this instance. Call this
   * method whenever this instance is no longer used in your app.
   */
  dispose() {
    this.geometry.dispose(), this.material.dispose();
  }
}
function ag(r) {
  const e = [];
  r.isBone === !0 && e.push(r);
  for (let t = 0; t < r.children.length; t++)
    e.push(...ag(r.children[t]));
  return e;
}
class q0 extends Je {
  /**
   * Constructs a new point light helper.
   *
   * @param {PointLight} light - The light to be visualized.
   * @param {number} [sphereSize=1] - The size of the sphere helper.
   * @param {number|Color|string} [color] - The helper's color. If not set, the helper will take
   * the color of the light.
   */
  constructor(e, t, i) {
    const n = new Ts(t, 4, 2), s = new Ht({ wireframe: !0, fog: !1, toneMapped: !1 });
    super(n, s), this.light = e, this.color = i, this.type = "PointLightHelper", this.matrix = this.light.matrixWorld, this.matrixAutoUpdate = !1, this.update();
  }
  /**
   * Frees the GPU-related resources allocated by this instance. Call this
   * method whenever this instance is no longer used in your app.
   */
  dispose() {
    this.geometry.dispose(), this.material.dispose();
  }
  /**
   * Updates the helper to match the position of the
   * light being visualized.
   */
  update() {
    this.light.updateWorldMatrix(!0, !1), this.color !== void 0 ? this.material.color.set(this.color) : this.material.color.copy(this.light.color);
  }
}
const Z0 = /* @__PURE__ */ new b(), np = /* @__PURE__ */ new oe(), sp = /* @__PURE__ */ new oe();
class Y0 extends tt {
  /**
   * Constructs a new hemisphere light helper.
   *
   * @param {HemisphereLight} light - The light to be visualized.
   * @param {number} [size=1] - The size of the mesh used to visualize the light.
   * @param {number|Color|string} [color] - The helper's color. If not set, the helper will take
   * the color of the light.
   */
  constructor(e, t, i) {
    super(), this.light = e, this.matrix = e.matrixWorld, this.matrixAutoUpdate = !1, this.color = i, this.type = "HemisphereLightHelper";
    const n = new Ea(t);
    n.rotateY(Math.PI * 0.5), this.material = new Ht({ wireframe: !0, fog: !1, toneMapped: !1 }), this.color === void 0 && (this.material.vertexColors = !0);
    const s = n.getAttribute("position"), a = new Float32Array(s.count * 3);
    n.setAttribute("color", new it(a, 3)), this.add(new Je(n, this.material)), this.update();
  }
  /**
   * Frees the GPU-related resources allocated by this instance. Call this
   * method whenever this instance is no longer used in your app.
   */
  dispose() {
    this.children[0].geometry.dispose(), this.children[0].material.dispose();
  }
  /**
   * Updates the helper to match the position and direction of the
   * light being visualized.
   */
  update() {
    const e = this.children[0];
    if (this.color !== void 0)
      this.material.color.set(this.color);
    else {
      const t = e.geometry.getAttribute("color");
      np.copy(this.light.color), sp.copy(this.light.groundColor);
      for (let i = 0, n = t.count; i < n; i++) {
        const s = i < n / 2 ? np : sp;
        t.setXYZ(i, s.r, s.g, s.b);
      }
      t.needsUpdate = !0;
    }
    this.light.updateWorldMatrix(!0, !1), e.lookAt(Z0.setFromMatrixPosition(this.light.matrixWorld).negate());
  }
}
let j0 = class extends ei {
  /**
   * Constructs a new grid helper.
   *
   * @param {number} [size=10] - The size of the grid.
   * @param {number} [divisions=10] - The number of divisions across the grid.
   * @param {number|Color|string} [color1=0x444444] - The color of the center line.
   * @param {number|Color|string} [color2=0x888888] - The color of the lines of the grid.
   */
  constructor(e = 10, t = 10, i = 4473924, n = 8947848) {
    i = new oe(i), n = new oe(n);
    const s = t / 2, a = e / t, o = e / 2, l = [], c = [];
    for (let u = 0, p = 0, m = -o; u <= t; u++, m += a) {
      l.push(-o, 0, m, o, 0, m), l.push(m, 0, -o, m, 0, o);
      const _ = u === s ? i : n;
      _.toArray(c, p), p += 3, _.toArray(c, p), p += 3, _.toArray(c, p), p += 3, _.toArray(c, p), p += 3;
    }
    const h = new Ue();
    h.setAttribute("position", new ve(l, 3)), h.setAttribute("color", new ve(c, 3));
    const d = new It({ vertexColors: !0, toneMapped: !1 });
    super(h, d), this.type = "GridHelper";
  }
  /**
   * Frees the GPU-related resources allocated by this instance. Call this
   * method whenever this instance is no longer used in your app.
   */
  dispose() {
    this.geometry.dispose(), this.material.dispose();
  }
};
class $0 extends ei {
  /**
   * Constructs a new polar grid helper.
   *
   * @param {number} [radius=10] - The radius of the polar grid. This can be any positive number.
   * @param {number} [sectors=16] - The number of sectors the grid will be divided into. This can be any positive integer.
   * @param {number} [rings=16] - The number of rings. This can be any positive integer.
   * @param {number} [divisions=64] - The number of line segments used for each circle. This can be any positive integer.
   * @param {number|Color|string} [color1=0x444444] - The first color used for grid elements.
   * @param {number|Color|string} [color2=0x888888] -  The second color used for grid elements.
   */
  constructor(e = 10, t = 16, i = 8, n = 64, s = 4473924, a = 8947848) {
    s = new oe(s), a = new oe(a);
    const o = [], l = [];
    if (t > 1)
      for (let d = 0; d < t; d++) {
        const u = d / t * (Math.PI * 2), p = Math.sin(u) * e, m = Math.cos(u) * e;
        o.push(0, 0, 0), o.push(p, 0, m);
        const _ = d & 1 ? s : a;
        l.push(_.r, _.g, _.b), l.push(_.r, _.g, _.b);
      }
    for (let d = 0; d < i; d++) {
      const u = d & 1 ? s : a, p = e - e / i * d;
      for (let m = 0; m < n; m++) {
        let _ = m / n * (Math.PI * 2), g = Math.sin(_) * p, f = Math.cos(_) * p;
        o.push(g, 0, f), l.push(u.r, u.g, u.b), _ = (m + 1) / n * (Math.PI * 2), g = Math.sin(_) * p, f = Math.cos(_) * p, o.push(g, 0, f), l.push(u.r, u.g, u.b);
      }
    }
    const c = new Ue();
    c.setAttribute("position", new ve(o, 3)), c.setAttribute("color", new ve(l, 3));
    const h = new It({ vertexColors: !0, toneMapped: !1 });
    super(c, h), this.type = "PolarGridHelper";
  }
  /**
   * Frees the GPU-related resources allocated by this instance. Call this
   * method whenever this instance is no longer used in your app.
   */
  dispose() {
    this.geometry.dispose(), this.material.dispose();
  }
}
const rp = /* @__PURE__ */ new b(), mo = /* @__PURE__ */ new b(), ap = /* @__PURE__ */ new b();
class K0 extends tt {
  /**
   * Constructs a new directional light helper.
   *
   * @param {DirectionalLight} light - The light to be visualized.
   * @param {number} [size=1] - The dimensions of the plane.
   * @param {number|Color|string} [color] - The helper's color. If not set, the helper will take
   * the color of the light.
   */
  constructor(e, t, i) {
    super(), this.light = e, this.matrix = e.matrixWorld, this.matrixAutoUpdate = !1, this.color = i, this.type = "DirectionalLightHelper", t === void 0 && (t = 1);
    let n = new Ue();
    n.setAttribute("position", new ve([
      -t,
      t,
      0,
      t,
      t,
      0,
      t,
      -t,
      0,
      -t,
      -t,
      0,
      -t,
      t,
      0
    ], 3));
    const s = new It({ fog: !1, toneMapped: !1 });
    this.lightPlane = new Fn(n, s), this.add(this.lightPlane), n = new Ue(), n.setAttribute("position", new ve([0, 0, 0, 0, 0, 1], 3)), this.targetLine = new Fn(n, s), this.add(this.targetLine), this.update();
  }
  /**
   * Frees the GPU-related resources allocated by this instance. Call this
   * method whenever this instance is no longer used in your app.
   */
  dispose() {
    this.lightPlane.geometry.dispose(), this.lightPlane.material.dispose(), this.targetLine.geometry.dispose(), this.targetLine.material.dispose();
  }
  /**
   * Updates the helper to match the position and direction of the
   * light being visualized.
   */
  update() {
    this.light.updateWorldMatrix(!0, !1), this.light.target.updateWorldMatrix(!0, !1), rp.setFromMatrixPosition(this.light.matrixWorld), mo.setFromMatrixPosition(this.light.target.matrixWorld), ap.subVectors(mo, rp), this.lightPlane.lookAt(mo), this.color !== void 0 ? (this.lightPlane.material.color.set(this.color), this.targetLine.material.color.set(this.color)) : (this.lightPlane.material.color.copy(this.light.color), this.targetLine.material.color.copy(this.light.color)), this.targetLine.lookAt(mo), this.targetLine.scale.z = ap.length();
  }
}
const go = /* @__PURE__ */ new b(), Ct = /* @__PURE__ */ new Yl();
class J0 extends ei {
  /**
   * Constructs a new arrow helper.
   *
   * @param {Camera} camera - The camera to visualize.
   */
  constructor(e) {
    const t = new Ue(), i = new It({ color: 16777215, vertexColors: !0, toneMapped: !1 }), n = [], s = [], a = {};
    o("n1", "n2"), o("n2", "n4"), o("n4", "n3"), o("n3", "n1"), o("f1", "f2"), o("f2", "f4"), o("f4", "f3"), o("f3", "f1"), o("n1", "f1"), o("n2", "f2"), o("n3", "f3"), o("n4", "f4"), o("p", "n1"), o("p", "n2"), o("p", "n3"), o("p", "n4"), o("u1", "u2"), o("u2", "u3"), o("u3", "u1"), o("c", "t"), o("p", "c"), o("cn1", "cn2"), o("cn3", "cn4"), o("cf1", "cf2"), o("cf3", "cf4");
    function o(m, _) {
      l(m), l(_);
    }
    function l(m) {
      n.push(0, 0, 0), s.push(0, 0, 0), a[m] === void 0 && (a[m] = []), a[m].push(n.length / 3 - 1);
    }
    t.setAttribute("position", new ve(n, 3)), t.setAttribute("color", new ve(s, 3)), super(t, i), this.type = "CameraHelper", this.camera = e, this.camera.updateProjectionMatrix && this.camera.updateProjectionMatrix(), this.matrix = e.matrixWorld, this.matrixAutoUpdate = !1, this.pointMap = a, this.update();
    const c = new oe(16755200), h = new oe(16711680), d = new oe(43775), u = new oe(16777215), p = new oe(3355443);
    this.setColors(c, h, d, u, p);
  }
  /**
   * Defines the colors of the helper.
   *
   * @param {Color} frustum - The frustum line color.
   * @param {Color} cone - The cone line color.
   * @param {Color} up - The up line color.
   * @param {Color} target - The target line color.
   * @param {Color} cross - The cross line color.
   * @return {CameraHelper} A reference to this helper.
   */
  setColors(e, t, i, n, s) {
    const o = this.geometry.getAttribute("color");
    return o.setXYZ(0, e.r, e.g, e.b), o.setXYZ(1, e.r, e.g, e.b), o.setXYZ(2, e.r, e.g, e.b), o.setXYZ(3, e.r, e.g, e.b), o.setXYZ(4, e.r, e.g, e.b), o.setXYZ(5, e.r, e.g, e.b), o.setXYZ(6, e.r, e.g, e.b), o.setXYZ(7, e.r, e.g, e.b), o.setXYZ(8, e.r, e.g, e.b), o.setXYZ(9, e.r, e.g, e.b), o.setXYZ(10, e.r, e.g, e.b), o.setXYZ(11, e.r, e.g, e.b), o.setXYZ(12, e.r, e.g, e.b), o.setXYZ(13, e.r, e.g, e.b), o.setXYZ(14, e.r, e.g, e.b), o.setXYZ(15, e.r, e.g, e.b), o.setXYZ(16, e.r, e.g, e.b), o.setXYZ(17, e.r, e.g, e.b), o.setXYZ(18, e.r, e.g, e.b), o.setXYZ(19, e.r, e.g, e.b), o.setXYZ(20, e.r, e.g, e.b), o.setXYZ(21, e.r, e.g, e.b), o.setXYZ(22, e.r, e.g, e.b), o.setXYZ(23, e.r, e.g, e.b), o.setXYZ(24, t.r, t.g, t.b), o.setXYZ(25, t.r, t.g, t.b), o.setXYZ(26, t.r, t.g, t.b), o.setXYZ(27, t.r, t.g, t.b), o.setXYZ(28, t.r, t.g, t.b), o.setXYZ(29, t.r, t.g, t.b), o.setXYZ(30, t.r, t.g, t.b), o.setXYZ(31, t.r, t.g, t.b), o.setXYZ(32, i.r, i.g, i.b), o.setXYZ(33, i.r, i.g, i.b), o.setXYZ(34, i.r, i.g, i.b), o.setXYZ(35, i.r, i.g, i.b), o.setXYZ(36, i.r, i.g, i.b), o.setXYZ(37, i.r, i.g, i.b), o.setXYZ(38, n.r, n.g, n.b), o.setXYZ(39, n.r, n.g, n.b), o.setXYZ(40, s.r, s.g, s.b), o.setXYZ(41, s.r, s.g, s.b), o.setXYZ(42, s.r, s.g, s.b), o.setXYZ(43, s.r, s.g, s.b), o.setXYZ(44, s.r, s.g, s.b), o.setXYZ(45, s.r, s.g, s.b), o.setXYZ(46, s.r, s.g, s.b), o.setXYZ(47, s.r, s.g, s.b), o.setXYZ(48, s.r, s.g, s.b), o.setXYZ(49, s.r, s.g, s.b), o.needsUpdate = !0, this;
  }
  /**
   * Updates the helper based on the projection matrix of the camera.
   */
  update() {
    const e = this.geometry, t = this.pointMap, i = 1, n = 1;
    let s, a;
    if (Ct.projectionMatrixInverse.copy(this.camera.projectionMatrixInverse), this.camera.reversedDepth === !0)
      s = 1, a = 0;
    else if (this.camera.coordinateSystem === wi)
      s = -1, a = 1;
    else if (this.camera.coordinateSystem === pr)
      s = 0, a = 1;
    else
      throw new Error("THREE.CameraHelper.update(): Invalid coordinate system: " + this.camera.coordinateSystem);
    Rt("c", t, e, Ct, 0, 0, s), Rt("t", t, e, Ct, 0, 0, a), Rt("n1", t, e, Ct, -i, -n, s), Rt("n2", t, e, Ct, i, -n, s), Rt("n3", t, e, Ct, -i, n, s), Rt("n4", t, e, Ct, i, n, s), Rt("f1", t, e, Ct, -i, -n, a), Rt("f2", t, e, Ct, i, -n, a), Rt("f3", t, e, Ct, -i, n, a), Rt("f4", t, e, Ct, i, n, a), Rt("u1", t, e, Ct, i * 0.7, n * 1.1, s), Rt("u2", t, e, Ct, -i * 0.7, n * 1.1, s), Rt("u3", t, e, Ct, 0, n * 2, s), Rt("cf1", t, e, Ct, -i, 0, a), Rt("cf2", t, e, Ct, i, 0, a), Rt("cf3", t, e, Ct, 0, -n, a), Rt("cf4", t, e, Ct, 0, n, a), Rt("cn1", t, e, Ct, -i, 0, s), Rt("cn2", t, e, Ct, i, 0, s), Rt("cn3", t, e, Ct, 0, -n, s), Rt("cn4", t, e, Ct, 0, n, s), e.getAttribute("position").needsUpdate = !0;
  }
  /**
   * Frees the GPU-related resources allocated by this instance. Call this
   * method whenever this instance is no longer used in your app.
   */
  dispose() {
    this.geometry.dispose(), this.material.dispose();
  }
}
function Rt(r, e, t, i, n, s, a) {
  go.set(n, s, a).unproject(i);
  const o = e[r];
  if (o !== void 0) {
    const l = t.getAttribute("position");
    for (let c = 0, h = o.length; c < h; c++)
      l.setXYZ(o[c], go.x, go.y, go.z);
  }
}
const _o = /* @__PURE__ */ new Tt();
let Q0 = class extends ei {
  /**
   * Constructs a new box helper.
   *
   * @param {Object3D} [object] - The 3D object to show the world-axis-aligned bounding box.
   * @param {number|Color|string} [color=0xffff00] - The box's color.
   */
  constructor(e, t = 16776960) {
    const i = new Uint16Array([0, 1, 1, 2, 2, 3, 3, 0, 4, 5, 5, 6, 6, 7, 7, 4, 0, 4, 1, 5, 2, 6, 3, 7]), n = new Float32Array(8 * 3), s = new Ue();
    s.setIndex(new it(i, 1)), s.setAttribute("position", new it(n, 3)), super(s, new It({ color: t, toneMapped: !1 })), this.object = e, this.type = "BoxHelper", this.matrixAutoUpdate = !1, this.update();
  }
  /**
   * Updates the helper's geometry to match the dimensions of the object,
   * including any children.
   */
  update() {
    if (this.object !== void 0 && _o.setFromObject(this.object), _o.isEmpty()) return;
    const e = _o.min, t = _o.max, i = this.geometry.attributes.position, n = i.array;
    n[0] = t.x, n[1] = t.y, n[2] = t.z, n[3] = e.x, n[4] = t.y, n[5] = t.z, n[6] = e.x, n[7] = e.y, n[8] = t.z, n[9] = t.x, n[10] = e.y, n[11] = t.z, n[12] = t.x, n[13] = t.y, n[14] = e.z, n[15] = e.x, n[16] = t.y, n[17] = e.z, n[18] = e.x, n[19] = e.y, n[20] = e.z, n[21] = t.x, n[22] = e.y, n[23] = e.z, i.needsUpdate = !0, this.geometry.computeBoundingSphere();
  }
  /**
   * Updates the wireframe box for the passed object.
   *
   * @param {Object3D} object - The 3D object to create the helper for.
   * @return {BoxHelper} A reference to this instance.
   */
  setFromObject(e) {
    return this.object = e, this.update(), this;
  }
  copy(e, t) {
    return super.copy(e, t), this.object = e.object, this;
  }
  /**
   * Frees the GPU-related resources allocated by this instance. Call this
   * method whenever this instance is no longer used in your app.
   */
  dispose() {
    this.geometry.dispose(), this.material.dispose();
  }
};
class ev extends ei {
  /**
   * Constructs a new box3 helper.
   *
   * @param {Box3} box - The box to visualize.
   * @param {number|Color|string} [color=0xffff00] - The box's color.
   */
  constructor(e, t = 16776960) {
    const i = new Uint16Array([0, 1, 1, 2, 2, 3, 3, 0, 4, 5, 5, 6, 6, 7, 7, 4, 0, 4, 1, 5, 2, 6, 3, 7]), n = [1, 1, 1, -1, 1, 1, -1, -1, 1, 1, -1, 1, 1, 1, -1, -1, 1, -1, -1, -1, -1, 1, -1, -1], s = new Ue();
    s.setIndex(new it(i, 1)), s.setAttribute("position", new ve(n, 3)), super(s, new It({ color: t, toneMapped: !1 })), this.box = e, this.type = "Box3Helper", this.geometry.computeBoundingSphere();
  }
  updateMatrixWorld(e) {
    const t = this.box;
    t.isEmpty() || (t.getCenter(this.position), t.getSize(this.scale), this.scale.multiplyScalar(0.5), super.updateMatrixWorld(e));
  }
  /**
   * Frees the GPU-related resources allocated by this instance. Call this
   * method whenever this instance is no longer used in your app.
   */
  dispose() {
    this.geometry.dispose(), this.material.dispose();
  }
}
class tv extends Fn {
  /**
   * Constructs a new plane helper.
   *
   * @param {Plane} plane - The plane to be visualized.
   * @param {number} [size=1] - The side length of plane helper.
   * @param {number|Color|string} [hex=0xffff00] - The helper's color.
   */
  constructor(e, t = 1, i = 16776960) {
    const n = i, s = [1, -1, 0, -1, 1, 0, -1, -1, 0, 1, 1, 0, -1, 1, 0, -1, -1, 0, 1, -1, 0, 1, 1, 0], a = new Ue();
    a.setAttribute("position", new ve(s, 3)), a.computeBoundingSphere(), super(a, new It({ color: n, toneMapped: !1 })), this.type = "PlaneHelper", this.plane = e, this.size = t;
    const o = [1, 1, 0, -1, 1, 0, -1, -1, 0, 1, 1, 0, -1, -1, 0, 1, -1, 0], l = new Ue();
    l.setAttribute("position", new ve(o, 3)), l.computeBoundingSphere(), this.add(new Je(l, new Ht({ color: n, opacity: 0.2, transparent: !0, depthWrite: !1, toneMapped: !1 })));
  }
  updateMatrixWorld(e) {
    this.position.set(0, 0, 0), this.scale.set(0.5 * this.size, 0.5 * this.size, 1), this.lookAt(this.plane.normal), this.translateZ(-this.plane.constant), super.updateMatrixWorld(e);
  }
  /**
   * Updates the helper to match the position and direction of the
   * light being visualized.
   */
  dispose() {
    this.geometry.dispose(), this.material.dispose(), this.children[0].geometry.dispose(), this.children[0].material.dispose();
  }
}
const op = /* @__PURE__ */ new b();
let yo, nh;
class iv extends tt {
  /**
   * Constructs a new arrow helper.
   *
   * @param {Vector3} [dir=(0, 0, 1)] - The (normalized) direction vector.
   * @param {Vector3} [origin=(0, 0, 0)] - Point at which the arrow starts.
   * @param {number} [length=1] - Length of the arrow in world units.
   * @param {(number|Color|string)} [color=0xffff00] - Color of the arrow.
   * @param {number} [headLength=length*0.2] - The length of the head of the arrow.
   * @param {number} [headWidth=headLength*0.2] - The width of the head of the arrow.
   */
  constructor(e = new b(0, 0, 1), t = new b(0, 0, 0), i = 1, n = 16776960, s = i * 0.2, a = s * 0.2) {
    super(), this.type = "ArrowHelper", yo === void 0 && (yo = new Ue(), yo.setAttribute("position", new ve([0, 0, 0, 0, 1, 0], 3)), nh = new wr(0.5, 1, 5, 1), nh.translate(0, -0.5, 0)), this.position.copy(t), this.line = new Fn(yo, new It({ color: n, toneMapped: !1 })), this.line.matrixAutoUpdate = !1, this.add(this.line), this.cone = new Je(nh, new Ht({ color: n, toneMapped: !1 })), this.cone.matrixAutoUpdate = !1, this.add(this.cone), this.setDirection(e), this.setLength(i, s, a);
  }
  /**
   * Sets the direction of the helper.
   *
   * @param {Vector3} dir - The normalized direction vector.
   */
  setDirection(e) {
    if (e.y > 0.99999)
      this.quaternion.set(0, 0, 0, 1);
    else if (e.y < -0.99999)
      this.quaternion.set(1, 0, 0, 0);
    else {
      op.set(e.z, 0, -e.x).normalize();
      const t = Math.acos(e.y);
      this.quaternion.setFromAxisAngle(op, t);
    }
  }
  /**
   * Sets the length of the helper.
   *
   * @param {number} length - Length of the arrow in world units.
   * @param {number} [headLength=length*0.2] - The length of the head of the arrow.
   * @param {number} [headWidth=headLength*0.2] - The width of the head of the arrow.
   */
  setLength(e, t = e * 0.2, i = t * 0.2) {
    this.line.scale.set(1, Math.max(1e-4, e - t), 1), this.line.updateMatrix(), this.cone.scale.set(i, t, i), this.cone.position.y = e, this.cone.updateMatrix();
  }
  /**
   * Sets the color of the helper.
   *
   * @param {number|Color|string} color - The color to set.
   */
  setColor(e) {
    this.line.material.color.set(e), this.cone.material.color.set(e);
  }
  copy(e) {
    return super.copy(e, !1), this.line.copy(e.line), this.cone.copy(e.cone), this;
  }
  /**
   * Frees the GPU-related resources allocated by this instance. Call this
   * method whenever this instance is no longer used in your app.
   */
  dispose() {
    this.line.geometry.dispose(), this.line.material.dispose(), this.cone.geometry.dispose(), this.cone.material.dispose();
  }
}
let nv = class extends ei {
  /**
   * Constructs a new axes helper.
   *
   * @param {number} [size=1] - Size of the lines representing the axes.
   */
  constructor(e = 1) {
    const t = [
      0,
      0,
      0,
      e,
      0,
      0,
      0,
      0,
      0,
      0,
      e,
      0,
      0,
      0,
      0,
      0,
      0,
      e
    ], i = [
      1,
      0,
      0,
      1,
      0.6,
      0,
      0,
      1,
      0,
      0.6,
      1,
      0,
      0,
      0,
      1,
      0,
      0.6,
      1
    ], n = new Ue();
    n.setAttribute("position", new ve(t, 3)), n.setAttribute("color", new ve(i, 3));
    const s = new It({ vertexColors: !0, toneMapped: !1 });
    super(n, s), this.type = "AxesHelper";
  }
  /**
   * Defines the colors of the axes helper.
   *
   * @param {number|Color|string} xAxisColor - The color for the x axis.
   * @param {number|Color|string} yAxisColor - The color for the y axis.
   * @param {number|Color|string} zAxisColor - The color for the z axis.
   * @return {AxesHelper} A reference to this axes helper.
   */
  setColors(e, t, i) {
    const n = new oe(), s = this.geometry.attributes.color.array;
    return n.set(e), n.toArray(s, 0), n.toArray(s, 3), n.set(t), n.toArray(s, 6), n.toArray(s, 9), n.set(i), n.toArray(s, 12), n.toArray(s, 15), this.geometry.attributes.color.needsUpdate = !0, this;
  }
  /**
   * Frees the GPU-related resources allocated by this instance. Call this
   * method whenever this instance is no longer used in your app.
   */
  dispose() {
    this.geometry.dispose(), this.material.dispose();
  }
};
class og {
  /**
   * Constructs a new shape path.
   */
  constructor() {
    this.type = "ShapePath", this.color = new oe(), this.subPaths = [], this.currentPath = null;
  }
  /**
   * Creates a new path and moves it current point to the given one.
   *
   * @param {number} x - The x coordinate.
   * @param {number} y - The y coordinate.
   * @return {ShapePath} A reference to this shape path.
   */
  moveTo(e, t) {
    return this.currentPath = new Dl(), this.subPaths.push(this.currentPath), this.currentPath.moveTo(e, t), this;
  }
  /**
   * Adds an instance of {@link LineCurve} to the path by connecting
   * the current point with the given one.
   *
   * @param {number} x - The x coordinate of the end point.
   * @param {number} y - The y coordinate of the end point.
   * @return {ShapePath} A reference to this shape path.
   */
  lineTo(e, t) {
    return this.currentPath.lineTo(e, t), this;
  }
  /**
   * Adds an instance of {@link QuadraticBezierCurve} to the path by connecting
   * the current point with the given one.
   *
   * @param {number} aCPx - The x coordinate of the control point.
   * @param {number} aCPy - The y coordinate of the control point.
   * @param {number} aX - The x coordinate of the end point.
   * @param {number} aY - The y coordinate of the end point.
   * @return {ShapePath} A reference to this shape path.
   */
  quadraticCurveTo(e, t, i, n) {
    return this.currentPath.quadraticCurveTo(e, t, i, n), this;
  }
  /**
   * Adds an instance of {@link CubicBezierCurve} to the path by connecting
   * the current point with the given one.
   *
   * @param {number} aCP1x - The x coordinate of the first control point.
   * @param {number} aCP1y - The y coordinate of the first control point.
   * @param {number} aCP2x - The x coordinate of the second control point.
   * @param {number} aCP2y - The y coordinate of the second control point.
   * @param {number} aX - The x coordinate of the end point.
   * @param {number} aY - The y coordinate of the end point.
   * @return {ShapePath} A reference to this shape path.
   */
  bezierCurveTo(e, t, i, n, s, a) {
    return this.currentPath.bezierCurveTo(e, t, i, n, s, a), this;
  }
  /**
   * Adds an instance of {@link SplineCurve} to the path by connecting
   * the current point with the given list of points.
   *
   * @param {Array<Vector2>} pts - An array of points in 2D space.
   * @return {ShapePath} A reference to this shape path.
   */
  splineThru(e) {
    return this.currentPath.splineThru(e), this;
  }
  /**
   * Converts the paths into an array of shapes.
   *
   * @param {boolean} isCCW - By default solid shapes are  defined clockwise (CW) and holes are defined counterclockwise (CCW).
   * If this flag is set to `true`, then those are flipped.
   * @return {Array<Shape>} An array of shapes.
   */
  toShapes(e) {
    function t(f) {
      const v = [];
      for (let x = 0, y = f.length; x < y; x++) {
        const A = f[x], S = new Nn();
        S.curves = A.curves, v.push(S);
      }
      return v;
    }
    function i(f, v) {
      const x = v.length;
      let y = !1;
      for (let A = x - 1, S = 0; S < x; A = S++) {
        let C = v[A], P = v[S], E = P.x - C.x, w = P.y - C.y;
        if (Math.abs(w) > Number.EPSILON) {
          if (w < 0 && (C = v[S], E = -E, P = v[A], w = -w), f.y < C.y || f.y > P.y) continue;
          if (f.y === C.y) {
            if (f.x === C.x) return !0;
          } else {
            const L = w * (f.x - C.x) - E * (f.y - C.y);
            if (L === 0) return !0;
            if (L < 0) continue;
            y = !y;
          }
        } else {
          if (f.y !== C.y) continue;
          if (P.x <= f.x && f.x <= C.x || C.x <= f.x && f.x <= P.x) return !0;
        }
      }
      return y;
    }
    const n = zi.isClockWise, s = this.subPaths;
    if (s.length === 0) return [];
    let a, o, l;
    const c = [];
    if (s.length === 1)
      return o = s[0], l = new Nn(), l.curves = o.curves, c.push(l), c;
    let h = !n(s[0].getPoints());
    h = e ? !h : h;
    const d = [], u = [];
    let p = [], m = 0, _;
    u[m] = void 0, p[m] = [];
    for (let f = 0, v = s.length; f < v; f++)
      o = s[f], _ = o.getPoints(), a = n(_), a = e ? !a : a, a ? (!h && u[m] && m++, u[m] = { s: new Nn(), p: _ }, u[m].s.curves = o.curves, h && m++, p[m] = []) : p[m].push({ h: o, p: _[0] });
    if (!u[0]) return t(s);
    if (u.length > 1) {
      let f = !1, v = 0;
      for (let x = 0, y = u.length; x < y; x++)
        d[x] = [];
      for (let x = 0, y = u.length; x < y; x++) {
        const A = p[x];
        for (let S = 0; S < A.length; S++) {
          const C = A[S];
          let P = !0;
          for (let E = 0; E < u.length; E++)
            i(C.p, u[E].p) && (x !== E && v++, P ? (P = !1, d[E].push(C)) : f = !0);
          P && d[x].push(C);
        }
      }
      v > 0 && f === !1 && (p = d);
    }
    let g;
    for (let f = 0, v = u.length; f < v; f++) {
      l = u[f].s, c.push(l), g = p[f];
      for (let x = 0, y = g.length; x < y; x++)
        l.holes.push(g[x].h);
    }
    return c;
  }
}
let zd = class extends sn {
  /**
   * Constructs a new controls instance.
   *
   * @param {Object3D} object - The object that is managed by the controls.
   * @param {?HTMLDOMElement} domElement - The HTML element used for event listeners.
   */
  constructor(e, t = null) {
    super(), this.object = e, this.domElement = t, this.enabled = !0, this.state = -1, this.keys = {}, this.mouseButtons = { LEFT: null, MIDDLE: null, RIGHT: null }, this.touches = { ONE: null, TWO: null };
  }
  /**
   * Connects the controls to the DOM. This method has so called "side effects" since
   * it adds the module's event listeners to the DOM.
   *
   * @param {HTMLDOMElement} element - The DOM element to connect to.
   */
  connect(e) {
    if (e === void 0) {
      console.warn("THREE.Controls: connect() now requires an element.");
      return;
    }
    this.domElement !== null && this.disconnect(), this.domElement = e;
  }
  /**
   * Disconnects the controls from the DOM.
   */
  disconnect() {
  }
  /**
   * Call this method if you no longer want use to the controls. It frees all internal
   * resources and removes all event listeners.
   */
  dispose() {
  }
  /**
   * Controls should implement this method if they have to update their internal state
   * per simulation step.
   *
   * @param {number} [delta] - The time delta in seconds.
   */
  update() {
  }
};
function sv(r, e) {
  const t = r.image && r.image.width ? r.image.width / r.image.height : 1;
  return t > e ? (r.repeat.x = 1, r.repeat.y = t / e, r.offset.x = 0, r.offset.y = (1 - r.repeat.y) / 2) : (r.repeat.x = e / t, r.repeat.y = 1, r.offset.x = (1 - r.repeat.x) / 2, r.offset.y = 0), r;
}
function rv(r, e) {
  const t = r.image && r.image.width ? r.image.width / r.image.height : 1;
  return t > e ? (r.repeat.x = e / t, r.repeat.y = 1, r.offset.x = (1 - r.repeat.x) / 2, r.offset.y = 0) : (r.repeat.x = 1, r.repeat.y = t / e, r.offset.x = 0, r.offset.y = (1 - r.repeat.y) / 2), r;
}
function av(r) {
  return r.repeat.x = 1, r.repeat.y = 1, r.offset.x = 0, r.offset.y = 0, r;
}
function Gh(r, e, t, i) {
  const n = ov(i);
  switch (t) {
    case td:
      return r * e;
    case zl:
      return r * e / n.components * n.byteLength;
    case ba:
      return r * e / n.components * n.byteLength;
    case nd:
      return r * e * 2 / n.components * n.byteLength;
    case Hl:
      return r * e * 2 / n.components * n.byteLength;
    case id:
      return r * e * 3 / n.components * n.byteLength;
    case oi:
      return r * e * 4 / n.components * n.byteLength;
    case Vl:
      return r * e * 4 / n.components * n.byteLength;
    case Yr:
    case jr:
      return Math.floor((r + 3) / 4) * Math.floor((e + 3) / 4) * 8;
    case $r:
    case Kr:
      return Math.floor((r + 3) / 4) * Math.floor((e + 3) / 4) * 16;
    case il:
    case sl:
      return Math.max(r, 16) * Math.max(e, 8) / 4;
    case tl:
    case nl:
      return Math.max(r, 8) * Math.max(e, 8) / 2;
    case rl:
    case al:
      return Math.floor((r + 3) / 4) * Math.floor((e + 3) / 4) * 8;
    case ol:
      return Math.floor((r + 3) / 4) * Math.floor((e + 3) / 4) * 16;
    case ll:
      return Math.floor((r + 3) / 4) * Math.floor((e + 3) / 4) * 16;
    case cl:
      return Math.floor((r + 4) / 5) * Math.floor((e + 3) / 4) * 16;
    case hl:
      return Math.floor((r + 4) / 5) * Math.floor((e + 4) / 5) * 16;
    case dl:
      return Math.floor((r + 5) / 6) * Math.floor((e + 4) / 5) * 16;
    case ul:
      return Math.floor((r + 5) / 6) * Math.floor((e + 5) / 6) * 16;
    case pl:
      return Math.floor((r + 7) / 8) * Math.floor((e + 4) / 5) * 16;
    case fl:
      return Math.floor((r + 7) / 8) * Math.floor((e + 5) / 6) * 16;
    case ml:
      return Math.floor((r + 7) / 8) * Math.floor((e + 7) / 8) * 16;
    case gl:
      return Math.floor((r + 9) / 10) * Math.floor((e + 4) / 5) * 16;
    case _l:
      return Math.floor((r + 9) / 10) * Math.floor((e + 5) / 6) * 16;
    case yl:
      return Math.floor((r + 9) / 10) * Math.floor((e + 7) / 8) * 16;
    case vl:
      return Math.floor((r + 9) / 10) * Math.floor((e + 9) / 10) * 16;
    case xl:
      return Math.floor((r + 11) / 12) * Math.floor((e + 9) / 10) * 16;
    case bl:
      return Math.floor((r + 11) / 12) * Math.floor((e + 11) / 12) * 16;
    case Sl:
    case Ml:
    case wl:
      return Math.ceil(r / 4) * Math.ceil(e / 4) * 16;
    case El:
    case Tl:
      return Math.ceil(r / 4) * Math.ceil(e / 4) * 8;
    case Al:
    case Cl:
      return Math.ceil(r / 4) * Math.ceil(e / 4) * 16;
  }
  throw new Error(
    `Unable to determine texture byte length for ${t} format.`
  );
}
function ov(r) {
  switch (r) {
    case Hi:
    case Kh:
      return { byteLength: 1, components: 1 };
    case cr:
    case Jh:
    case br:
      return { byteLength: 2, components: 1 };
    case Bl:
    case kl:
      return { byteLength: 2, components: 4 };
    case yn:
    case Fl:
    case mi:
      return { byteLength: 4, components: 1 };
    case Qh:
    case ed:
      return { byteLength: 4, components: 3 };
  }
  throw new Error(`Unknown texture type ${r}.`);
}
class lv {
  /**
   * Scales the texture as large as possible within its surface without cropping
   * or stretching the texture. The method preserves the original aspect ratio of
   * the texture. Akin to CSS `object-fit: contain`
   *
   * @param {Texture} texture - The texture.
   * @param {number} aspect - The texture's aspect ratio.
   * @return {Texture} The updated texture.
   */
  static contain(e, t) {
    return sv(e, t);
  }
  /**
   * Scales the texture to the smallest possible size to fill the surface, leaving
   * no empty space. The method preserves the original aspect ratio of the texture.
   * Akin to CSS `object-fit: cover`.
   *
   * @param {Texture} texture - The texture.
   * @param {number} aspect - The texture's aspect ratio.
   * @return {Texture} The updated texture.
   */
  static cover(e, t) {
    return rv(e, t);
  }
  /**
   * Configures the texture to the default transformation. Akin to CSS `object-fit: fill`.
   *
   * @param {Texture} texture - The texture.
   * @return {Texture} The updated texture.
   */
  static fill(e) {
    return av(e);
  }
  /**
   * Determines how many bytes must be used to represent the texture.
   *
   * @param {number} width - The width of the texture.
   * @param {number} height - The height of the texture.
   * @param {number} format - The texture's format.
   * @param {number} type - The texture's type.
   * @return {number} The byte length.
   */
  static getByteLength(e, t, i, n) {
    return Gh(e, t, i, n);
  }
}
typeof __THREE_DEVTOOLS__ < "u" && __THREE_DEVTOOLS__.dispatchEvent(new CustomEvent("register", { detail: {
  revision: Ul
} }));
typeof window < "u" && (window.__THREE__ ? console.warn("WARNING: Multiple instances of Three.js being imported.") : window.__THREE__ = Ul);
/**
 * @license
 * Copyright 2010-2025 Three.js Authors
 * SPDX-License-Identifier: MIT
 */
function lg() {
  let r = null, e = !1, t = null, i = null;
  function n(s, a) {
    t(s, a), i = r.requestAnimationFrame(n);
  }
  return {
    start: function() {
      e !== !0 && t !== null && (i = r.requestAnimationFrame(n), e = !0);
    },
    stop: function() {
      r.cancelAnimationFrame(i), e = !1;
    },
    setAnimationLoop: function(s) {
      t = s;
    },
    setContext: function(s) {
      r = s;
    }
  };
}
function cv(r) {
  const e = /* @__PURE__ */ new WeakMap();
  function t(o, l) {
    const c = o.array, h = o.usage, d = c.byteLength, u = r.createBuffer();
    r.bindBuffer(l, u), r.bufferData(l, c, h), o.onUploadCallback();
    let p;
    if (c instanceof Float32Array)
      p = r.FLOAT;
    else if (typeof Float16Array < "u" && c instanceof Float16Array)
      p = r.HALF_FLOAT;
    else if (c instanceof Uint16Array)
      o.isFloat16BufferAttribute ? p = r.HALF_FLOAT : p = r.UNSIGNED_SHORT;
    else if (c instanceof Int16Array)
      p = r.SHORT;
    else if (c instanceof Uint32Array)
      p = r.UNSIGNED_INT;
    else if (c instanceof Int32Array)
      p = r.INT;
    else if (c instanceof Int8Array)
      p = r.BYTE;
    else if (c instanceof Uint8Array)
      p = r.UNSIGNED_BYTE;
    else if (c instanceof Uint8ClampedArray)
      p = r.UNSIGNED_BYTE;
    else
      throw new Error("THREE.WebGLAttributes: Unsupported buffer data format: " + c);
    return {
      buffer: u,
      type: p,
      bytesPerElement: c.BYTES_PER_ELEMENT,
      version: o.version,
      size: d
    };
  }
  function i(o, l, c) {
    const h = l.array, d = l.updateRanges;
    if (r.bindBuffer(c, o), d.length === 0)
      r.bufferSubData(c, 0, h);
    else {
      d.sort((p, m) => p.start - m.start);
      let u = 0;
      for (let p = 1; p < d.length; p++) {
        const m = d[u], _ = d[p];
        _.start <= m.start + m.count + 1 ? m.count = Math.max(
          m.count,
          _.start + _.count - m.start
        ) : (++u, d[u] = _);
      }
      d.length = u + 1;
      for (let p = 0, m = d.length; p < m; p++) {
        const _ = d[p];
        r.bufferSubData(
          c,
          _.start * h.BYTES_PER_ELEMENT,
          h,
          _.start,
          _.count
        );
      }
      l.clearUpdateRanges();
    }
    l.onUploadCallback();
  }
  function n(o) {
    return o.isInterleavedBufferAttribute && (o = o.data), e.get(o);
  }
  function s(o) {
    o.isInterleavedBufferAttribute && (o = o.data);
    const l = e.get(o);
    l && (r.deleteBuffer(l.buffer), e.delete(o));
  }
  function a(o, l) {
    if (o.isInterleavedBufferAttribute && (o = o.data), o.isGLBufferAttribute) {
      const h = e.get(o);
      (!h || h.version < o.version) && e.set(o, {
        buffer: o.buffer,
        type: o.type,
        bytesPerElement: o.elementSize,
        version: o.version
      });
      return;
    }
    const c = e.get(o);
    if (c === void 0)
      e.set(o, t(o, l));
    else if (c.version < o.version) {
      if (c.size !== o.array.byteLength)
        throw new Error("THREE.WebGLAttributes: The size of the buffer attribute's array buffer does not match the original size. Resizing buffer attributes is not supported.");
      i(c.buffer, o, l), c.version = o.version;
    }
  }
  return {
    get: n,
    remove: s,
    update: a
  };
}
var hv = `#ifdef USE_ALPHAHASH
	if ( diffuseColor.a < getAlphaHashThreshold( vPosition ) ) discard;
#endif`, dv = `#ifdef USE_ALPHAHASH
	const float ALPHA_HASH_SCALE = 0.05;
	float hash2D( vec2 value ) {
		return fract( 1.0e4 * sin( 17.0 * value.x + 0.1 * value.y ) * ( 0.1 + abs( sin( 13.0 * value.y + value.x ) ) ) );
	}
	float hash3D( vec3 value ) {
		return hash2D( vec2( hash2D( value.xy ), value.z ) );
	}
	float getAlphaHashThreshold( vec3 position ) {
		float maxDeriv = max(
			length( dFdx( position.xyz ) ),
			length( dFdy( position.xyz ) )
		);
		float pixScale = 1.0 / ( ALPHA_HASH_SCALE * maxDeriv );
		vec2 pixScales = vec2(
			exp2( floor( log2( pixScale ) ) ),
			exp2( ceil( log2( pixScale ) ) )
		);
		vec2 alpha = vec2(
			hash3D( floor( pixScales.x * position.xyz ) ),
			hash3D( floor( pixScales.y * position.xyz ) )
		);
		float lerpFactor = fract( log2( pixScale ) );
		float x = ( 1.0 - lerpFactor ) * alpha.x + lerpFactor * alpha.y;
		float a = min( lerpFactor, 1.0 - lerpFactor );
		vec3 cases = vec3(
			x * x / ( 2.0 * a * ( 1.0 - a ) ),
			( x - 0.5 * a ) / ( 1.0 - a ),
			1.0 - ( ( 1.0 - x ) * ( 1.0 - x ) / ( 2.0 * a * ( 1.0 - a ) ) )
		);
		float threshold = ( x < ( 1.0 - a ) )
			? ( ( x < a ) ? cases.x : cases.y )
			: cases.z;
		return clamp( threshold , 1.0e-6, 1.0 );
	}
#endif`, uv = `#ifdef USE_ALPHAMAP
	diffuseColor.a *= texture2D( alphaMap, vAlphaMapUv ).g;
#endif`, pv = `#ifdef USE_ALPHAMAP
	uniform sampler2D alphaMap;
#endif`, fv = `#ifdef USE_ALPHATEST
	#ifdef ALPHA_TO_COVERAGE
	diffuseColor.a = smoothstep( alphaTest, alphaTest + fwidth( diffuseColor.a ), diffuseColor.a );
	if ( diffuseColor.a == 0.0 ) discard;
	#else
	if ( diffuseColor.a < alphaTest ) discard;
	#endif
#endif`, mv = `#ifdef USE_ALPHATEST
	uniform float alphaTest;
#endif`, gv = `#ifdef USE_AOMAP
	float ambientOcclusion = ( texture2D( aoMap, vAoMapUv ).r - 1.0 ) * aoMapIntensity + 1.0;
	reflectedLight.indirectDiffuse *= ambientOcclusion;
	#if defined( USE_CLEARCOAT ) 
		clearcoatSpecularIndirect *= ambientOcclusion;
	#endif
	#if defined( USE_SHEEN ) 
		sheenSpecularIndirect *= ambientOcclusion;
	#endif
	#if defined( USE_ENVMAP ) && defined( STANDARD )
		float dotNV = saturate( dot( geometryNormal, geometryViewDir ) );
		reflectedLight.indirectSpecular *= computeSpecularOcclusion( dotNV, ambientOcclusion, material.roughness );
	#endif
#endif`, _v = `#ifdef USE_AOMAP
	uniform sampler2D aoMap;
	uniform float aoMapIntensity;
#endif`, yv = `#ifdef USE_BATCHING
	#if ! defined( GL_ANGLE_multi_draw )
	#define gl_DrawID _gl_DrawID
	uniform int _gl_DrawID;
	#endif
	uniform highp sampler2D batchingTexture;
	uniform highp usampler2D batchingIdTexture;
	mat4 getBatchingMatrix( const in float i ) {
		int size = textureSize( batchingTexture, 0 ).x;
		int j = int( i ) * 4;
		int x = j % size;
		int y = j / size;
		vec4 v1 = texelFetch( batchingTexture, ivec2( x, y ), 0 );
		vec4 v2 = texelFetch( batchingTexture, ivec2( x + 1, y ), 0 );
		vec4 v3 = texelFetch( batchingTexture, ivec2( x + 2, y ), 0 );
		vec4 v4 = texelFetch( batchingTexture, ivec2( x + 3, y ), 0 );
		return mat4( v1, v2, v3, v4 );
	}
	float getIndirectIndex( const in int i ) {
		int size = textureSize( batchingIdTexture, 0 ).x;
		int x = i % size;
		int y = i / size;
		return float( texelFetch( batchingIdTexture, ivec2( x, y ), 0 ).r );
	}
#endif
#ifdef USE_BATCHING_COLOR
	uniform sampler2D batchingColorTexture;
	vec3 getBatchingColor( const in float i ) {
		int size = textureSize( batchingColorTexture, 0 ).x;
		int j = int( i );
		int x = j % size;
		int y = j / size;
		return texelFetch( batchingColorTexture, ivec2( x, y ), 0 ).rgb;
	}
#endif`, vv = `#ifdef USE_BATCHING
	mat4 batchingMatrix = getBatchingMatrix( getIndirectIndex( gl_DrawID ) );
#endif`, xv = `vec3 transformed = vec3( position );
#ifdef USE_ALPHAHASH
	vPosition = vec3( position );
#endif`, bv = `vec3 objectNormal = vec3( normal );
#ifdef USE_TANGENT
	vec3 objectTangent = vec3( tangent.xyz );
#endif`, Sv = `float G_BlinnPhong_Implicit( ) {
	return 0.25;
}
float D_BlinnPhong( const in float shininess, const in float dotNH ) {
	return RECIPROCAL_PI * ( shininess * 0.5 + 1.0 ) * pow( dotNH, shininess );
}
vec3 BRDF_BlinnPhong( const in vec3 lightDir, const in vec3 viewDir, const in vec3 normal, const in vec3 specularColor, const in float shininess ) {
	vec3 halfDir = normalize( lightDir + viewDir );
	float dotNH = saturate( dot( normal, halfDir ) );
	float dotVH = saturate( dot( viewDir, halfDir ) );
	vec3 F = F_Schlick( specularColor, 1.0, dotVH );
	float G = G_BlinnPhong_Implicit( );
	float D = D_BlinnPhong( shininess, dotNH );
	return F * ( G * D );
} // validated`, Mv = `#ifdef USE_IRIDESCENCE
	const mat3 XYZ_TO_REC709 = mat3(
		 3.2404542, -0.9692660,  0.0556434,
		-1.5371385,  1.8760108, -0.2040259,
		-0.4985314,  0.0415560,  1.0572252
	);
	vec3 Fresnel0ToIor( vec3 fresnel0 ) {
		vec3 sqrtF0 = sqrt( fresnel0 );
		return ( vec3( 1.0 ) + sqrtF0 ) / ( vec3( 1.0 ) - sqrtF0 );
	}
	vec3 IorToFresnel0( vec3 transmittedIor, float incidentIor ) {
		return pow2( ( transmittedIor - vec3( incidentIor ) ) / ( transmittedIor + vec3( incidentIor ) ) );
	}
	float IorToFresnel0( float transmittedIor, float incidentIor ) {
		return pow2( ( transmittedIor - incidentIor ) / ( transmittedIor + incidentIor ));
	}
	vec3 evalSensitivity( float OPD, vec3 shift ) {
		float phase = 2.0 * PI * OPD * 1.0e-9;
		vec3 val = vec3( 5.4856e-13, 4.4201e-13, 5.2481e-13 );
		vec3 pos = vec3( 1.6810e+06, 1.7953e+06, 2.2084e+06 );
		vec3 var = vec3( 4.3278e+09, 9.3046e+09, 6.6121e+09 );
		vec3 xyz = val * sqrt( 2.0 * PI * var ) * cos( pos * phase + shift ) * exp( - pow2( phase ) * var );
		xyz.x += 9.7470e-14 * sqrt( 2.0 * PI * 4.5282e+09 ) * cos( 2.2399e+06 * phase + shift[ 0 ] ) * exp( - 4.5282e+09 * pow2( phase ) );
		xyz /= 1.0685e-7;
		vec3 rgb = XYZ_TO_REC709 * xyz;
		return rgb;
	}
	vec3 evalIridescence( float outsideIOR, float eta2, float cosTheta1, float thinFilmThickness, vec3 baseF0 ) {
		vec3 I;
		float iridescenceIOR = mix( outsideIOR, eta2, smoothstep( 0.0, 0.03, thinFilmThickness ) );
		float sinTheta2Sq = pow2( outsideIOR / iridescenceIOR ) * ( 1.0 - pow2( cosTheta1 ) );
		float cosTheta2Sq = 1.0 - sinTheta2Sq;
		if ( cosTheta2Sq < 0.0 ) {
			return vec3( 1.0 );
		}
		float cosTheta2 = sqrt( cosTheta2Sq );
		float R0 = IorToFresnel0( iridescenceIOR, outsideIOR );
		float R12 = F_Schlick( R0, 1.0, cosTheta1 );
		float T121 = 1.0 - R12;
		float phi12 = 0.0;
		if ( iridescenceIOR < outsideIOR ) phi12 = PI;
		float phi21 = PI - phi12;
		vec3 baseIOR = Fresnel0ToIor( clamp( baseF0, 0.0, 0.9999 ) );		vec3 R1 = IorToFresnel0( baseIOR, iridescenceIOR );
		vec3 R23 = F_Schlick( R1, 1.0, cosTheta2 );
		vec3 phi23 = vec3( 0.0 );
		if ( baseIOR[ 0 ] < iridescenceIOR ) phi23[ 0 ] = PI;
		if ( baseIOR[ 1 ] < iridescenceIOR ) phi23[ 1 ] = PI;
		if ( baseIOR[ 2 ] < iridescenceIOR ) phi23[ 2 ] = PI;
		float OPD = 2.0 * iridescenceIOR * thinFilmThickness * cosTheta2;
		vec3 phi = vec3( phi21 ) + phi23;
		vec3 R123 = clamp( R12 * R23, 1e-5, 0.9999 );
		vec3 r123 = sqrt( R123 );
		vec3 Rs = pow2( T121 ) * R23 / ( vec3( 1.0 ) - R123 );
		vec3 C0 = R12 + Rs;
		I = C0;
		vec3 Cm = Rs - T121;
		for ( int m = 1; m <= 2; ++ m ) {
			Cm *= r123;
			vec3 Sm = 2.0 * evalSensitivity( float( m ) * OPD, float( m ) * phi );
			I += Cm * Sm;
		}
		return max( I, vec3( 0.0 ) );
	}
#endif`, wv = `#ifdef USE_BUMPMAP
	uniform sampler2D bumpMap;
	uniform float bumpScale;
	vec2 dHdxy_fwd() {
		vec2 dSTdx = dFdx( vBumpMapUv );
		vec2 dSTdy = dFdy( vBumpMapUv );
		float Hll = bumpScale * texture2D( bumpMap, vBumpMapUv ).x;
		float dBx = bumpScale * texture2D( bumpMap, vBumpMapUv + dSTdx ).x - Hll;
		float dBy = bumpScale * texture2D( bumpMap, vBumpMapUv + dSTdy ).x - Hll;
		return vec2( dBx, dBy );
	}
	vec3 perturbNormalArb( vec3 surf_pos, vec3 surf_norm, vec2 dHdxy, float faceDirection ) {
		vec3 vSigmaX = normalize( dFdx( surf_pos.xyz ) );
		vec3 vSigmaY = normalize( dFdy( surf_pos.xyz ) );
		vec3 vN = surf_norm;
		vec3 R1 = cross( vSigmaY, vN );
		vec3 R2 = cross( vN, vSigmaX );
		float fDet = dot( vSigmaX, R1 ) * faceDirection;
		vec3 vGrad = sign( fDet ) * ( dHdxy.x * R1 + dHdxy.y * R2 );
		return normalize( abs( fDet ) * surf_norm - vGrad );
	}
#endif`, Ev = `#if NUM_CLIPPING_PLANES > 0
	vec4 plane;
	#ifdef ALPHA_TO_COVERAGE
		float distanceToPlane, distanceGradient;
		float clipOpacity = 1.0;
		#pragma unroll_loop_start
		for ( int i = 0; i < UNION_CLIPPING_PLANES; i ++ ) {
			plane = clippingPlanes[ i ];
			distanceToPlane = - dot( vClipPosition, plane.xyz ) + plane.w;
			distanceGradient = fwidth( distanceToPlane ) / 2.0;
			clipOpacity *= smoothstep( - distanceGradient, distanceGradient, distanceToPlane );
			if ( clipOpacity == 0.0 ) discard;
		}
		#pragma unroll_loop_end
		#if UNION_CLIPPING_PLANES < NUM_CLIPPING_PLANES
			float unionClipOpacity = 1.0;
			#pragma unroll_loop_start
			for ( int i = UNION_CLIPPING_PLANES; i < NUM_CLIPPING_PLANES; i ++ ) {
				plane = clippingPlanes[ i ];
				distanceToPlane = - dot( vClipPosition, plane.xyz ) + plane.w;
				distanceGradient = fwidth( distanceToPlane ) / 2.0;
				unionClipOpacity *= 1.0 - smoothstep( - distanceGradient, distanceGradient, distanceToPlane );
			}
			#pragma unroll_loop_end
			clipOpacity *= 1.0 - unionClipOpacity;
		#endif
		diffuseColor.a *= clipOpacity;
		if ( diffuseColor.a == 0.0 ) discard;
	#else
		#pragma unroll_loop_start
		for ( int i = 0; i < UNION_CLIPPING_PLANES; i ++ ) {
			plane = clippingPlanes[ i ];
			if ( dot( vClipPosition, plane.xyz ) > plane.w ) discard;
		}
		#pragma unroll_loop_end
		#if UNION_CLIPPING_PLANES < NUM_CLIPPING_PLANES
			bool clipped = true;
			#pragma unroll_loop_start
			for ( int i = UNION_CLIPPING_PLANES; i < NUM_CLIPPING_PLANES; i ++ ) {
				plane = clippingPlanes[ i ];
				clipped = ( dot( vClipPosition, plane.xyz ) > plane.w ) && clipped;
			}
			#pragma unroll_loop_end
			if ( clipped ) discard;
		#endif
	#endif
#endif`, Tv = `#if NUM_CLIPPING_PLANES > 0
	varying vec3 vClipPosition;
	uniform vec4 clippingPlanes[ NUM_CLIPPING_PLANES ];
#endif`, Av = `#if NUM_CLIPPING_PLANES > 0
	varying vec3 vClipPosition;
#endif`, Cv = `#if NUM_CLIPPING_PLANES > 0
	vClipPosition = - mvPosition.xyz;
#endif`, Rv = `#if defined( USE_COLOR_ALPHA )
	diffuseColor *= vColor;
#elif defined( USE_COLOR )
	diffuseColor.rgb *= vColor;
#endif`, Pv = `#if defined( USE_COLOR_ALPHA )
	varying vec4 vColor;
#elif defined( USE_COLOR )
	varying vec3 vColor;
#endif`, Lv = `#if defined( USE_COLOR_ALPHA )
	varying vec4 vColor;
#elif defined( USE_COLOR ) || defined( USE_INSTANCING_COLOR ) || defined( USE_BATCHING_COLOR )
	varying vec3 vColor;
#endif`, Iv = `#if defined( USE_COLOR_ALPHA )
	vColor = vec4( 1.0 );
#elif defined( USE_COLOR ) || defined( USE_INSTANCING_COLOR ) || defined( USE_BATCHING_COLOR )
	vColor = vec3( 1.0 );
#endif
#ifdef USE_COLOR
	vColor *= color;
#endif
#ifdef USE_INSTANCING_COLOR
	vColor.xyz *= instanceColor.xyz;
#endif
#ifdef USE_BATCHING_COLOR
	vec3 batchingColor = getBatchingColor( getIndirectIndex( gl_DrawID ) );
	vColor.xyz *= batchingColor.xyz;
#endif`, Dv = `#define PI 3.141592653589793
#define PI2 6.283185307179586
#define PI_HALF 1.5707963267948966
#define RECIPROCAL_PI 0.3183098861837907
#define RECIPROCAL_PI2 0.15915494309189535
#define EPSILON 1e-6
#ifndef saturate
#define saturate( a ) clamp( a, 0.0, 1.0 )
#endif
#define whiteComplement( a ) ( 1.0 - saturate( a ) )
float pow2( const in float x ) { return x*x; }
vec3 pow2( const in vec3 x ) { return x*x; }
float pow3( const in float x ) { return x*x*x; }
float pow4( const in float x ) { float x2 = x*x; return x2*x2; }
float max3( const in vec3 v ) { return max( max( v.x, v.y ), v.z ); }
float average( const in vec3 v ) { return dot( v, vec3( 0.3333333 ) ); }
highp float rand( const in vec2 uv ) {
	const highp float a = 12.9898, b = 78.233, c = 43758.5453;
	highp float dt = dot( uv.xy, vec2( a,b ) ), sn = mod( dt, PI );
	return fract( sin( sn ) * c );
}
#ifdef HIGH_PRECISION
	float precisionSafeLength( vec3 v ) { return length( v ); }
#else
	float precisionSafeLength( vec3 v ) {
		float maxComponent = max3( abs( v ) );
		return length( v / maxComponent ) * maxComponent;
	}
#endif
struct IncidentLight {
	vec3 color;
	vec3 direction;
	bool visible;
};
struct ReflectedLight {
	vec3 directDiffuse;
	vec3 directSpecular;
	vec3 indirectDiffuse;
	vec3 indirectSpecular;
};
#ifdef USE_ALPHAHASH
	varying vec3 vPosition;
#endif
vec3 transformDirection( in vec3 dir, in mat4 matrix ) {
	return normalize( ( matrix * vec4( dir, 0.0 ) ).xyz );
}
vec3 inverseTransformDirection( in vec3 dir, in mat4 matrix ) {
	return normalize( ( vec4( dir, 0.0 ) * matrix ).xyz );
}
mat3 transposeMat3( const in mat3 m ) {
	mat3 tmp;
	tmp[ 0 ] = vec3( m[ 0 ].x, m[ 1 ].x, m[ 2 ].x );
	tmp[ 1 ] = vec3( m[ 0 ].y, m[ 1 ].y, m[ 2 ].y );
	tmp[ 2 ] = vec3( m[ 0 ].z, m[ 1 ].z, m[ 2 ].z );
	return tmp;
}
bool isPerspectiveMatrix( mat4 m ) {
	return m[ 2 ][ 3 ] == - 1.0;
}
vec2 equirectUv( in vec3 dir ) {
	float u = atan( dir.z, dir.x ) * RECIPROCAL_PI2 + 0.5;
	float v = asin( clamp( dir.y, - 1.0, 1.0 ) ) * RECIPROCAL_PI + 0.5;
	return vec2( u, v );
}
vec3 BRDF_Lambert( const in vec3 diffuseColor ) {
	return RECIPROCAL_PI * diffuseColor;
}
vec3 F_Schlick( const in vec3 f0, const in float f90, const in float dotVH ) {
	float fresnel = exp2( ( - 5.55473 * dotVH - 6.98316 ) * dotVH );
	return f0 * ( 1.0 - fresnel ) + ( f90 * fresnel );
}
float F_Schlick( const in float f0, const in float f90, const in float dotVH ) {
	float fresnel = exp2( ( - 5.55473 * dotVH - 6.98316 ) * dotVH );
	return f0 * ( 1.0 - fresnel ) + ( f90 * fresnel );
} // validated`, Nv = `#ifdef ENVMAP_TYPE_CUBE_UV
	#define cubeUV_minMipLevel 4.0
	#define cubeUV_minTileSize 16.0
	float getFace( vec3 direction ) {
		vec3 absDirection = abs( direction );
		float face = - 1.0;
		if ( absDirection.x > absDirection.z ) {
			if ( absDirection.x > absDirection.y )
				face = direction.x > 0.0 ? 0.0 : 3.0;
			else
				face = direction.y > 0.0 ? 1.0 : 4.0;
		} else {
			if ( absDirection.z > absDirection.y )
				face = direction.z > 0.0 ? 2.0 : 5.0;
			else
				face = direction.y > 0.0 ? 1.0 : 4.0;
		}
		return face;
	}
	vec2 getUV( vec3 direction, float face ) {
		vec2 uv;
		if ( face == 0.0 ) {
			uv = vec2( direction.z, direction.y ) / abs( direction.x );
		} else if ( face == 1.0 ) {
			uv = vec2( - direction.x, - direction.z ) / abs( direction.y );
		} else if ( face == 2.0 ) {
			uv = vec2( - direction.x, direction.y ) / abs( direction.z );
		} else if ( face == 3.0 ) {
			uv = vec2( - direction.z, direction.y ) / abs( direction.x );
		} else if ( face == 4.0 ) {
			uv = vec2( - direction.x, direction.z ) / abs( direction.y );
		} else {
			uv = vec2( direction.x, direction.y ) / abs( direction.z );
		}
		return 0.5 * ( uv + 1.0 );
	}
	vec3 bilinearCubeUV( sampler2D envMap, vec3 direction, float mipInt ) {
		float face = getFace( direction );
		float filterInt = max( cubeUV_minMipLevel - mipInt, 0.0 );
		mipInt = max( mipInt, cubeUV_minMipLevel );
		float faceSize = exp2( mipInt );
		highp vec2 uv = getUV( direction, face ) * ( faceSize - 2.0 ) + 1.0;
		if ( face > 2.0 ) {
			uv.y += faceSize;
			face -= 3.0;
		}
		uv.x += face * faceSize;
		uv.x += filterInt * 3.0 * cubeUV_minTileSize;
		uv.y += 4.0 * ( exp2( CUBEUV_MAX_MIP ) - faceSize );
		uv.x *= CUBEUV_TEXEL_WIDTH;
		uv.y *= CUBEUV_TEXEL_HEIGHT;
		#ifdef texture2DGradEXT
			return texture2DGradEXT( envMap, uv, vec2( 0.0 ), vec2( 0.0 ) ).rgb;
		#else
			return texture2D( envMap, uv ).rgb;
		#endif
	}
	#define cubeUV_r0 1.0
	#define cubeUV_m0 - 2.0
	#define cubeUV_r1 0.8
	#define cubeUV_m1 - 1.0
	#define cubeUV_r4 0.4
	#define cubeUV_m4 2.0
	#define cubeUV_r5 0.305
	#define cubeUV_m5 3.0
	#define cubeUV_r6 0.21
	#define cubeUV_m6 4.0
	float roughnessToMip( float roughness ) {
		float mip = 0.0;
		if ( roughness >= cubeUV_r1 ) {
			mip = ( cubeUV_r0 - roughness ) * ( cubeUV_m1 - cubeUV_m0 ) / ( cubeUV_r0 - cubeUV_r1 ) + cubeUV_m0;
		} else if ( roughness >= cubeUV_r4 ) {
			mip = ( cubeUV_r1 - roughness ) * ( cubeUV_m4 - cubeUV_m1 ) / ( cubeUV_r1 - cubeUV_r4 ) + cubeUV_m1;
		} else if ( roughness >= cubeUV_r5 ) {
			mip = ( cubeUV_r4 - roughness ) * ( cubeUV_m5 - cubeUV_m4 ) / ( cubeUV_r4 - cubeUV_r5 ) + cubeUV_m4;
		} else if ( roughness >= cubeUV_r6 ) {
			mip = ( cubeUV_r5 - roughness ) * ( cubeUV_m6 - cubeUV_m5 ) / ( cubeUV_r5 - cubeUV_r6 ) + cubeUV_m5;
		} else {
			mip = - 2.0 * log2( 1.16 * roughness );		}
		return mip;
	}
	vec4 textureCubeUV( sampler2D envMap, vec3 sampleDir, float roughness ) {
		float mip = clamp( roughnessToMip( roughness ), cubeUV_m0, CUBEUV_MAX_MIP );
		float mipF = fract( mip );
		float mipInt = floor( mip );
		vec3 color0 = bilinearCubeUV( envMap, sampleDir, mipInt );
		if ( mipF == 0.0 ) {
			return vec4( color0, 1.0 );
		} else {
			vec3 color1 = bilinearCubeUV( envMap, sampleDir, mipInt + 1.0 );
			return vec4( mix( color0, color1, mipF ), 1.0 );
		}
	}
#endif`, Uv = `vec3 transformedNormal = objectNormal;
#ifdef USE_TANGENT
	vec3 transformedTangent = objectTangent;
#endif
#ifdef USE_BATCHING
	mat3 bm = mat3( batchingMatrix );
	transformedNormal /= vec3( dot( bm[ 0 ], bm[ 0 ] ), dot( bm[ 1 ], bm[ 1 ] ), dot( bm[ 2 ], bm[ 2 ] ) );
	transformedNormal = bm * transformedNormal;
	#ifdef USE_TANGENT
		transformedTangent = bm * transformedTangent;
	#endif
#endif
#ifdef USE_INSTANCING
	mat3 im = mat3( instanceMatrix );
	transformedNormal /= vec3( dot( im[ 0 ], im[ 0 ] ), dot( im[ 1 ], im[ 1 ] ), dot( im[ 2 ], im[ 2 ] ) );
	transformedNormal = im * transformedNormal;
	#ifdef USE_TANGENT
		transformedTangent = im * transformedTangent;
	#endif
#endif
transformedNormal = normalMatrix * transformedNormal;
#ifdef FLIP_SIDED
	transformedNormal = - transformedNormal;
#endif
#ifdef USE_TANGENT
	transformedTangent = ( modelViewMatrix * vec4( transformedTangent, 0.0 ) ).xyz;
	#ifdef FLIP_SIDED
		transformedTangent = - transformedTangent;
	#endif
#endif`, Ov = `#ifdef USE_DISPLACEMENTMAP
	uniform sampler2D displacementMap;
	uniform float displacementScale;
	uniform float displacementBias;
#endif`, Fv = `#ifdef USE_DISPLACEMENTMAP
	transformed += normalize( objectNormal ) * ( texture2D( displacementMap, vDisplacementMapUv ).x * displacementScale + displacementBias );
#endif`, Bv = `#ifdef USE_EMISSIVEMAP
	vec4 emissiveColor = texture2D( emissiveMap, vEmissiveMapUv );
	#ifdef DECODE_VIDEO_TEXTURE_EMISSIVE
		emissiveColor = sRGBTransferEOTF( emissiveColor );
	#endif
	totalEmissiveRadiance *= emissiveColor.rgb;
#endif`, kv = `#ifdef USE_EMISSIVEMAP
	uniform sampler2D emissiveMap;
#endif`, zv = "gl_FragColor = linearToOutputTexel( gl_FragColor );", Hv = `vec4 LinearTransferOETF( in vec4 value ) {
	return value;
}
vec4 sRGBTransferEOTF( in vec4 value ) {
	return vec4( mix( pow( value.rgb * 0.9478672986 + vec3( 0.0521327014 ), vec3( 2.4 ) ), value.rgb * 0.0773993808, vec3( lessThanEqual( value.rgb, vec3( 0.04045 ) ) ) ), value.a );
}
vec4 sRGBTransferOETF( in vec4 value ) {
	return vec4( mix( pow( value.rgb, vec3( 0.41666 ) ) * 1.055 - vec3( 0.055 ), value.rgb * 12.92, vec3( lessThanEqual( value.rgb, vec3( 0.0031308 ) ) ) ), value.a );
}`, Vv = `#ifdef USE_ENVMAP
	#ifdef ENV_WORLDPOS
		vec3 cameraToFrag;
		if ( isOrthographic ) {
			cameraToFrag = normalize( vec3( - viewMatrix[ 0 ][ 2 ], - viewMatrix[ 1 ][ 2 ], - viewMatrix[ 2 ][ 2 ] ) );
		} else {
			cameraToFrag = normalize( vWorldPosition - cameraPosition );
		}
		vec3 worldNormal = inverseTransformDirection( normal, viewMatrix );
		#ifdef ENVMAP_MODE_REFLECTION
			vec3 reflectVec = reflect( cameraToFrag, worldNormal );
		#else
			vec3 reflectVec = refract( cameraToFrag, worldNormal, refractionRatio );
		#endif
	#else
		vec3 reflectVec = vReflect;
	#endif
	#ifdef ENVMAP_TYPE_CUBE
		vec4 envColor = textureCube( envMap, envMapRotation * vec3( flipEnvMap * reflectVec.x, reflectVec.yz ) );
	#else
		vec4 envColor = vec4( 0.0 );
	#endif
	#ifdef ENVMAP_BLENDING_MULTIPLY
		outgoingLight = mix( outgoingLight, outgoingLight * envColor.xyz, specularStrength * reflectivity );
	#elif defined( ENVMAP_BLENDING_MIX )
		outgoingLight = mix( outgoingLight, envColor.xyz, specularStrength * reflectivity );
	#elif defined( ENVMAP_BLENDING_ADD )
		outgoingLight += envColor.xyz * specularStrength * reflectivity;
	#endif
#endif`, Gv = `#ifdef USE_ENVMAP
	uniform float envMapIntensity;
	uniform float flipEnvMap;
	uniform mat3 envMapRotation;
	#ifdef ENVMAP_TYPE_CUBE
		uniform samplerCube envMap;
	#else
		uniform sampler2D envMap;
	#endif
	
#endif`, Wv = `#ifdef USE_ENVMAP
	uniform float reflectivity;
	#if defined( USE_BUMPMAP ) || defined( USE_NORMALMAP ) || defined( PHONG ) || defined( LAMBERT )
		#define ENV_WORLDPOS
	#endif
	#ifdef ENV_WORLDPOS
		varying vec3 vWorldPosition;
		uniform float refractionRatio;
	#else
		varying vec3 vReflect;
	#endif
#endif`, Xv = `#ifdef USE_ENVMAP
	#if defined( USE_BUMPMAP ) || defined( USE_NORMALMAP ) || defined( PHONG ) || defined( LAMBERT )
		#define ENV_WORLDPOS
	#endif
	#ifdef ENV_WORLDPOS
		
		varying vec3 vWorldPosition;
	#else
		varying vec3 vReflect;
		uniform float refractionRatio;
	#endif
#endif`, qv = `#ifdef USE_ENVMAP
	#ifdef ENV_WORLDPOS
		vWorldPosition = worldPosition.xyz;
	#else
		vec3 cameraToVertex;
		if ( isOrthographic ) {
			cameraToVertex = normalize( vec3( - viewMatrix[ 0 ][ 2 ], - viewMatrix[ 1 ][ 2 ], - viewMatrix[ 2 ][ 2 ] ) );
		} else {
			cameraToVertex = normalize( worldPosition.xyz - cameraPosition );
		}
		vec3 worldNormal = inverseTransformDirection( transformedNormal, viewMatrix );
		#ifdef ENVMAP_MODE_REFLECTION
			vReflect = reflect( cameraToVertex, worldNormal );
		#else
			vReflect = refract( cameraToVertex, worldNormal, refractionRatio );
		#endif
	#endif
#endif`, Zv = `#ifdef USE_FOG
	vFogDepth = - mvPosition.z;
#endif`, Yv = `#ifdef USE_FOG
	varying float vFogDepth;
#endif`, jv = `#ifdef USE_FOG
	#ifdef FOG_EXP2
		float fogFactor = 1.0 - exp( - fogDensity * fogDensity * vFogDepth * vFogDepth );
	#else
		float fogFactor = smoothstep( fogNear, fogFar, vFogDepth );
	#endif
	gl_FragColor.rgb = mix( gl_FragColor.rgb, fogColor, fogFactor );
#endif`, $v = `#ifdef USE_FOG
	uniform vec3 fogColor;
	varying float vFogDepth;
	#ifdef FOG_EXP2
		uniform float fogDensity;
	#else
		uniform float fogNear;
		uniform float fogFar;
	#endif
#endif`, Kv = `#ifdef USE_GRADIENTMAP
	uniform sampler2D gradientMap;
#endif
vec3 getGradientIrradiance( vec3 normal, vec3 lightDirection ) {
	float dotNL = dot( normal, lightDirection );
	vec2 coord = vec2( dotNL * 0.5 + 0.5, 0.0 );
	#ifdef USE_GRADIENTMAP
		return vec3( texture2D( gradientMap, coord ).r );
	#else
		vec2 fw = fwidth( coord ) * 0.5;
		return mix( vec3( 0.7 ), vec3( 1.0 ), smoothstep( 0.7 - fw.x, 0.7 + fw.x, coord.x ) );
	#endif
}`, Jv = `#ifdef USE_LIGHTMAP
	uniform sampler2D lightMap;
	uniform float lightMapIntensity;
#endif`, Qv = `LambertMaterial material;
material.diffuseColor = diffuseColor.rgb;
material.specularStrength = specularStrength;`, ex = `varying vec3 vViewPosition;
struct LambertMaterial {
	vec3 diffuseColor;
	float specularStrength;
};
void RE_Direct_Lambert( const in IncidentLight directLight, const in vec3 geometryPosition, const in vec3 geometryNormal, const in vec3 geometryViewDir, const in vec3 geometryClearcoatNormal, const in LambertMaterial material, inout ReflectedLight reflectedLight ) {
	float dotNL = saturate( dot( geometryNormal, directLight.direction ) );
	vec3 irradiance = dotNL * directLight.color;
	reflectedLight.directDiffuse += irradiance * BRDF_Lambert( material.diffuseColor );
}
void RE_IndirectDiffuse_Lambert( const in vec3 irradiance, const in vec3 geometryPosition, const in vec3 geometryNormal, const in vec3 geometryViewDir, const in vec3 geometryClearcoatNormal, const in LambertMaterial material, inout ReflectedLight reflectedLight ) {
	reflectedLight.indirectDiffuse += irradiance * BRDF_Lambert( material.diffuseColor );
}
#define RE_Direct				RE_Direct_Lambert
#define RE_IndirectDiffuse		RE_IndirectDiffuse_Lambert`, tx = `uniform bool receiveShadow;
uniform vec3 ambientLightColor;
#if defined( USE_LIGHT_PROBES )
	uniform vec3 lightProbe[ 9 ];
#endif
vec3 shGetIrradianceAt( in vec3 normal, in vec3 shCoefficients[ 9 ] ) {
	float x = normal.x, y = normal.y, z = normal.z;
	vec3 result = shCoefficients[ 0 ] * 0.886227;
	result += shCoefficients[ 1 ] * 2.0 * 0.511664 * y;
	result += shCoefficients[ 2 ] * 2.0 * 0.511664 * z;
	result += shCoefficients[ 3 ] * 2.0 * 0.511664 * x;
	result += shCoefficients[ 4 ] * 2.0 * 0.429043 * x * y;
	result += shCoefficients[ 5 ] * 2.0 * 0.429043 * y * z;
	result += shCoefficients[ 6 ] * ( 0.743125 * z * z - 0.247708 );
	result += shCoefficients[ 7 ] * 2.0 * 0.429043 * x * z;
	result += shCoefficients[ 8 ] * 0.429043 * ( x * x - y * y );
	return result;
}
vec3 getLightProbeIrradiance( const in vec3 lightProbe[ 9 ], const in vec3 normal ) {
	vec3 worldNormal = inverseTransformDirection( normal, viewMatrix );
	vec3 irradiance = shGetIrradianceAt( worldNormal, lightProbe );
	return irradiance;
}
vec3 getAmbientLightIrradiance( const in vec3 ambientLightColor ) {
	vec3 irradiance = ambientLightColor;
	return irradiance;
}
float getDistanceAttenuation( const in float lightDistance, const in float cutoffDistance, const in float decayExponent ) {
	float distanceFalloff = 1.0 / max( pow( lightDistance, decayExponent ), 0.01 );
	if ( cutoffDistance > 0.0 ) {
		distanceFalloff *= pow2( saturate( 1.0 - pow4( lightDistance / cutoffDistance ) ) );
	}
	return distanceFalloff;
}
float getSpotAttenuation( const in float coneCosine, const in float penumbraCosine, const in float angleCosine ) {
	return smoothstep( coneCosine, penumbraCosine, angleCosine );
}
#if NUM_DIR_LIGHTS > 0
	struct DirectionalLight {
		vec3 direction;
		vec3 color;
	};
	uniform DirectionalLight directionalLights[ NUM_DIR_LIGHTS ];
	void getDirectionalLightInfo( const in DirectionalLight directionalLight, out IncidentLight light ) {
		light.color = directionalLight.color;
		light.direction = directionalLight.direction;
		light.visible = true;
	}
#endif
#if NUM_POINT_LIGHTS > 0
	struct PointLight {
		vec3 position;
		vec3 color;
		float distance;
		float decay;
	};
	uniform PointLight pointLights[ NUM_POINT_LIGHTS ];
	void getPointLightInfo( const in PointLight pointLight, const in vec3 geometryPosition, out IncidentLight light ) {
		vec3 lVector = pointLight.position - geometryPosition;
		light.direction = normalize( lVector );
		float lightDistance = length( lVector );
		light.color = pointLight.color;
		light.color *= getDistanceAttenuation( lightDistance, pointLight.distance, pointLight.decay );
		light.visible = ( light.color != vec3( 0.0 ) );
	}
#endif
#if NUM_SPOT_LIGHTS > 0
	struct SpotLight {
		vec3 position;
		vec3 direction;
		vec3 color;
		float distance;
		float decay;
		float coneCos;
		float penumbraCos;
	};
	uniform SpotLight spotLights[ NUM_SPOT_LIGHTS ];
	void getSpotLightInfo( const in SpotLight spotLight, const in vec3 geometryPosition, out IncidentLight light ) {
		vec3 lVector = spotLight.position - geometryPosition;
		light.direction = normalize( lVector );
		float angleCos = dot( light.direction, spotLight.direction );
		float spotAttenuation = getSpotAttenuation( spotLight.coneCos, spotLight.penumbraCos, angleCos );
		if ( spotAttenuation > 0.0 ) {
			float lightDistance = length( lVector );
			light.color = spotLight.color * spotAttenuation;
			light.color *= getDistanceAttenuation( lightDistance, spotLight.distance, spotLight.decay );
			light.visible = ( light.color != vec3( 0.0 ) );
		} else {
			light.color = vec3( 0.0 );
			light.visible = false;
		}
	}
#endif
#if NUM_RECT_AREA_LIGHTS > 0
	struct RectAreaLight {
		vec3 color;
		vec3 position;
		vec3 halfWidth;
		vec3 halfHeight;
	};
	uniform sampler2D ltc_1;	uniform sampler2D ltc_2;
	uniform RectAreaLight rectAreaLights[ NUM_RECT_AREA_LIGHTS ];
#endif
#if NUM_HEMI_LIGHTS > 0
	struct HemisphereLight {
		vec3 direction;
		vec3 skyColor;
		vec3 groundColor;
	};
	uniform HemisphereLight hemisphereLights[ NUM_HEMI_LIGHTS ];
	vec3 getHemisphereLightIrradiance( const in HemisphereLight hemiLight, const in vec3 normal ) {
		float dotNL = dot( normal, hemiLight.direction );
		float hemiDiffuseWeight = 0.5 * dotNL + 0.5;
		vec3 irradiance = mix( hemiLight.groundColor, hemiLight.skyColor, hemiDiffuseWeight );
		return irradiance;
	}
#endif`, ix = `#ifdef USE_ENVMAP
	vec3 getIBLIrradiance( const in vec3 normal ) {
		#ifdef ENVMAP_TYPE_CUBE_UV
			vec3 worldNormal = inverseTransformDirection( normal, viewMatrix );
			vec4 envMapColor = textureCubeUV( envMap, envMapRotation * worldNormal, 1.0 );
			return PI * envMapColor.rgb * envMapIntensity;
		#else
			return vec3( 0.0 );
		#endif
	}
	vec3 getIBLRadiance( const in vec3 viewDir, const in vec3 normal, const in float roughness ) {
		#ifdef ENVMAP_TYPE_CUBE_UV
			vec3 reflectVec = reflect( - viewDir, normal );
			reflectVec = normalize( mix( reflectVec, normal, roughness * roughness) );
			reflectVec = inverseTransformDirection( reflectVec, viewMatrix );
			vec4 envMapColor = textureCubeUV( envMap, envMapRotation * reflectVec, roughness );
			return envMapColor.rgb * envMapIntensity;
		#else
			return vec3( 0.0 );
		#endif
	}
	#ifdef USE_ANISOTROPY
		vec3 getIBLAnisotropyRadiance( const in vec3 viewDir, const in vec3 normal, const in float roughness, const in vec3 bitangent, const in float anisotropy ) {
			#ifdef ENVMAP_TYPE_CUBE_UV
				vec3 bentNormal = cross( bitangent, viewDir );
				bentNormal = normalize( cross( bentNormal, bitangent ) );
				bentNormal = normalize( mix( bentNormal, normal, pow2( pow2( 1.0 - anisotropy * ( 1.0 - roughness ) ) ) ) );
				return getIBLRadiance( viewDir, bentNormal, roughness );
			#else
				return vec3( 0.0 );
			#endif
		}
	#endif
#endif`, nx = `ToonMaterial material;
material.diffuseColor = diffuseColor.rgb;`, sx = `varying vec3 vViewPosition;
struct ToonMaterial {
	vec3 diffuseColor;
};
void RE_Direct_Toon( const in IncidentLight directLight, const in vec3 geometryPosition, const in vec3 geometryNormal, const in vec3 geometryViewDir, const in vec3 geometryClearcoatNormal, const in ToonMaterial material, inout ReflectedLight reflectedLight ) {
	vec3 irradiance = getGradientIrradiance( geometryNormal, directLight.direction ) * directLight.color;
	reflectedLight.directDiffuse += irradiance * BRDF_Lambert( material.diffuseColor );
}
void RE_IndirectDiffuse_Toon( const in vec3 irradiance, const in vec3 geometryPosition, const in vec3 geometryNormal, const in vec3 geometryViewDir, const in vec3 geometryClearcoatNormal, const in ToonMaterial material, inout ReflectedLight reflectedLight ) {
	reflectedLight.indirectDiffuse += irradiance * BRDF_Lambert( material.diffuseColor );
}
#define RE_Direct				RE_Direct_Toon
#define RE_IndirectDiffuse		RE_IndirectDiffuse_Toon`, rx = `BlinnPhongMaterial material;
material.diffuseColor = diffuseColor.rgb;
material.specularColor = specular;
material.specularShininess = shininess;
material.specularStrength = specularStrength;`, ax = `varying vec3 vViewPosition;
struct BlinnPhongMaterial {
	vec3 diffuseColor;
	vec3 specularColor;
	float specularShininess;
	float specularStrength;
};
void RE_Direct_BlinnPhong( const in IncidentLight directLight, const in vec3 geometryPosition, const in vec3 geometryNormal, const in vec3 geometryViewDir, const in vec3 geometryClearcoatNormal, const in BlinnPhongMaterial material, inout ReflectedLight reflectedLight ) {
	float dotNL = saturate( dot( geometryNormal, directLight.direction ) );
	vec3 irradiance = dotNL * directLight.color;
	reflectedLight.directDiffuse += irradiance * BRDF_Lambert( material.diffuseColor );
	reflectedLight.directSpecular += irradiance * BRDF_BlinnPhong( directLight.direction, geometryViewDir, geometryNormal, material.specularColor, material.specularShininess ) * material.specularStrength;
}
void RE_IndirectDiffuse_BlinnPhong( const in vec3 irradiance, const in vec3 geometryPosition, const in vec3 geometryNormal, const in vec3 geometryViewDir, const in vec3 geometryClearcoatNormal, const in BlinnPhongMaterial material, inout ReflectedLight reflectedLight ) {
	reflectedLight.indirectDiffuse += irradiance * BRDF_Lambert( material.diffuseColor );
}
#define RE_Direct				RE_Direct_BlinnPhong
#define RE_IndirectDiffuse		RE_IndirectDiffuse_BlinnPhong`, ox = `PhysicalMaterial material;
material.diffuseColor = diffuseColor.rgb * ( 1.0 - metalnessFactor );
vec3 dxy = max( abs( dFdx( nonPerturbedNormal ) ), abs( dFdy( nonPerturbedNormal ) ) );
float geometryRoughness = max( max( dxy.x, dxy.y ), dxy.z );
material.roughness = max( roughnessFactor, 0.0525 );material.roughness += geometryRoughness;
material.roughness = min( material.roughness, 1.0 );
#ifdef IOR
	material.ior = ior;
	#ifdef USE_SPECULAR
		float specularIntensityFactor = specularIntensity;
		vec3 specularColorFactor = specularColor;
		#ifdef USE_SPECULAR_COLORMAP
			specularColorFactor *= texture2D( specularColorMap, vSpecularColorMapUv ).rgb;
		#endif
		#ifdef USE_SPECULAR_INTENSITYMAP
			specularIntensityFactor *= texture2D( specularIntensityMap, vSpecularIntensityMapUv ).a;
		#endif
		material.specularF90 = mix( specularIntensityFactor, 1.0, metalnessFactor );
	#else
		float specularIntensityFactor = 1.0;
		vec3 specularColorFactor = vec3( 1.0 );
		material.specularF90 = 1.0;
	#endif
	material.specularColor = mix( min( pow2( ( material.ior - 1.0 ) / ( material.ior + 1.0 ) ) * specularColorFactor, vec3( 1.0 ) ) * specularIntensityFactor, diffuseColor.rgb, metalnessFactor );
#else
	material.specularColor = mix( vec3( 0.04 ), diffuseColor.rgb, metalnessFactor );
	material.specularF90 = 1.0;
#endif
#ifdef USE_CLEARCOAT
	material.clearcoat = clearcoat;
	material.clearcoatRoughness = clearcoatRoughness;
	material.clearcoatF0 = vec3( 0.04 );
	material.clearcoatF90 = 1.0;
	#ifdef USE_CLEARCOATMAP
		material.clearcoat *= texture2D( clearcoatMap, vClearcoatMapUv ).x;
	#endif
	#ifdef USE_CLEARCOAT_ROUGHNESSMAP
		material.clearcoatRoughness *= texture2D( clearcoatRoughnessMap, vClearcoatRoughnessMapUv ).y;
	#endif
	material.clearcoat = saturate( material.clearcoat );	material.clearcoatRoughness = max( material.clearcoatRoughness, 0.0525 );
	material.clearcoatRoughness += geometryRoughness;
	material.clearcoatRoughness = min( material.clearcoatRoughness, 1.0 );
#endif
#ifdef USE_DISPERSION
	material.dispersion = dispersion;
#endif
#ifdef USE_IRIDESCENCE
	material.iridescence = iridescence;
	material.iridescenceIOR = iridescenceIOR;
	#ifdef USE_IRIDESCENCEMAP
		material.iridescence *= texture2D( iridescenceMap, vIridescenceMapUv ).r;
	#endif
	#ifdef USE_IRIDESCENCE_THICKNESSMAP
		material.iridescenceThickness = (iridescenceThicknessMaximum - iridescenceThicknessMinimum) * texture2D( iridescenceThicknessMap, vIridescenceThicknessMapUv ).g + iridescenceThicknessMinimum;
	#else
		material.iridescenceThickness = iridescenceThicknessMaximum;
	#endif
#endif
#ifdef USE_SHEEN
	material.sheenColor = sheenColor;
	#ifdef USE_SHEEN_COLORMAP
		material.sheenColor *= texture2D( sheenColorMap, vSheenColorMapUv ).rgb;
	#endif
	material.sheenRoughness = clamp( sheenRoughness, 0.07, 1.0 );
	#ifdef USE_SHEEN_ROUGHNESSMAP
		material.sheenRoughness *= texture2D( sheenRoughnessMap, vSheenRoughnessMapUv ).a;
	#endif
#endif
#ifdef USE_ANISOTROPY
	#ifdef USE_ANISOTROPYMAP
		mat2 anisotropyMat = mat2( anisotropyVector.x, anisotropyVector.y, - anisotropyVector.y, anisotropyVector.x );
		vec3 anisotropyPolar = texture2D( anisotropyMap, vAnisotropyMapUv ).rgb;
		vec2 anisotropyV = anisotropyMat * normalize( 2.0 * anisotropyPolar.rg - vec2( 1.0 ) ) * anisotropyPolar.b;
	#else
		vec2 anisotropyV = anisotropyVector;
	#endif
	material.anisotropy = length( anisotropyV );
	if( material.anisotropy == 0.0 ) {
		anisotropyV = vec2( 1.0, 0.0 );
	} else {
		anisotropyV /= material.anisotropy;
		material.anisotropy = saturate( material.anisotropy );
	}
	material.alphaT = mix( pow2( material.roughness ), 1.0, pow2( material.anisotropy ) );
	material.anisotropyT = tbn[ 0 ] * anisotropyV.x + tbn[ 1 ] * anisotropyV.y;
	material.anisotropyB = tbn[ 1 ] * anisotropyV.x - tbn[ 0 ] * anisotropyV.y;
#endif`, lx = `struct PhysicalMaterial {
	vec3 diffuseColor;
	float roughness;
	vec3 specularColor;
	float specularF90;
	float dispersion;
	#ifdef USE_CLEARCOAT
		float clearcoat;
		float clearcoatRoughness;
		vec3 clearcoatF0;
		float clearcoatF90;
	#endif
	#ifdef USE_IRIDESCENCE
		float iridescence;
		float iridescenceIOR;
		float iridescenceThickness;
		vec3 iridescenceFresnel;
		vec3 iridescenceF0;
	#endif
	#ifdef USE_SHEEN
		vec3 sheenColor;
		float sheenRoughness;
	#endif
	#ifdef IOR
		float ior;
	#endif
	#ifdef USE_TRANSMISSION
		float transmission;
		float transmissionAlpha;
		float thickness;
		float attenuationDistance;
		vec3 attenuationColor;
	#endif
	#ifdef USE_ANISOTROPY
		float anisotropy;
		float alphaT;
		vec3 anisotropyT;
		vec3 anisotropyB;
	#endif
};
vec3 clearcoatSpecularDirect = vec3( 0.0 );
vec3 clearcoatSpecularIndirect = vec3( 0.0 );
vec3 sheenSpecularDirect = vec3( 0.0 );
vec3 sheenSpecularIndirect = vec3(0.0 );
vec3 Schlick_to_F0( const in vec3 f, const in float f90, const in float dotVH ) {
    float x = clamp( 1.0 - dotVH, 0.0, 1.0 );
    float x2 = x * x;
    float x5 = clamp( x * x2 * x2, 0.0, 0.9999 );
    return ( f - vec3( f90 ) * x5 ) / ( 1.0 - x5 );
}
float V_GGX_SmithCorrelated( const in float alpha, const in float dotNL, const in float dotNV ) {
	float a2 = pow2( alpha );
	float gv = dotNL * sqrt( a2 + ( 1.0 - a2 ) * pow2( dotNV ) );
	float gl = dotNV * sqrt( a2 + ( 1.0 - a2 ) * pow2( dotNL ) );
	return 0.5 / max( gv + gl, EPSILON );
}
float D_GGX( const in float alpha, const in float dotNH ) {
	float a2 = pow2( alpha );
	float denom = pow2( dotNH ) * ( a2 - 1.0 ) + 1.0;
	return RECIPROCAL_PI * a2 / pow2( denom );
}
#ifdef USE_ANISOTROPY
	float V_GGX_SmithCorrelated_Anisotropic( const in float alphaT, const in float alphaB, const in float dotTV, const in float dotBV, const in float dotTL, const in float dotBL, const in float dotNV, const in float dotNL ) {
		float gv = dotNL * length( vec3( alphaT * dotTV, alphaB * dotBV, dotNV ) );
		float gl = dotNV * length( vec3( alphaT * dotTL, alphaB * dotBL, dotNL ) );
		float v = 0.5 / ( gv + gl );
		return saturate(v);
	}
	float D_GGX_Anisotropic( const in float alphaT, const in float alphaB, const in float dotNH, const in float dotTH, const in float dotBH ) {
		float a2 = alphaT * alphaB;
		highp vec3 v = vec3( alphaB * dotTH, alphaT * dotBH, a2 * dotNH );
		highp float v2 = dot( v, v );
		float w2 = a2 / v2;
		return RECIPROCAL_PI * a2 * pow2 ( w2 );
	}
#endif
#ifdef USE_CLEARCOAT
	vec3 BRDF_GGX_Clearcoat( const in vec3 lightDir, const in vec3 viewDir, const in vec3 normal, const in PhysicalMaterial material) {
		vec3 f0 = material.clearcoatF0;
		float f90 = material.clearcoatF90;
		float roughness = material.clearcoatRoughness;
		float alpha = pow2( roughness );
		vec3 halfDir = normalize( lightDir + viewDir );
		float dotNL = saturate( dot( normal, lightDir ) );
		float dotNV = saturate( dot( normal, viewDir ) );
		float dotNH = saturate( dot( normal, halfDir ) );
		float dotVH = saturate( dot( viewDir, halfDir ) );
		vec3 F = F_Schlick( f0, f90, dotVH );
		float V = V_GGX_SmithCorrelated( alpha, dotNL, dotNV );
		float D = D_GGX( alpha, dotNH );
		return F * ( V * D );
	}
#endif
vec3 BRDF_GGX( const in vec3 lightDir, const in vec3 viewDir, const in vec3 normal, const in PhysicalMaterial material ) {
	vec3 f0 = material.specularColor;
	float f90 = material.specularF90;
	float roughness = material.roughness;
	float alpha = pow2( roughness );
	vec3 halfDir = normalize( lightDir + viewDir );
	float dotNL = saturate( dot( normal, lightDir ) );
	float dotNV = saturate( dot( normal, viewDir ) );
	float dotNH = saturate( dot( normal, halfDir ) );
	float dotVH = saturate( dot( viewDir, halfDir ) );
	vec3 F = F_Schlick( f0, f90, dotVH );
	#ifdef USE_IRIDESCENCE
		F = mix( F, material.iridescenceFresnel, material.iridescence );
	#endif
	#ifdef USE_ANISOTROPY
		float dotTL = dot( material.anisotropyT, lightDir );
		float dotTV = dot( material.anisotropyT, viewDir );
		float dotTH = dot( material.anisotropyT, halfDir );
		float dotBL = dot( material.anisotropyB, lightDir );
		float dotBV = dot( material.anisotropyB, viewDir );
		float dotBH = dot( material.anisotropyB, halfDir );
		float V = V_GGX_SmithCorrelated_Anisotropic( material.alphaT, alpha, dotTV, dotBV, dotTL, dotBL, dotNV, dotNL );
		float D = D_GGX_Anisotropic( material.alphaT, alpha, dotNH, dotTH, dotBH );
	#else
		float V = V_GGX_SmithCorrelated( alpha, dotNL, dotNV );
		float D = D_GGX( alpha, dotNH );
	#endif
	return F * ( V * D );
}
vec2 LTC_Uv( const in vec3 N, const in vec3 V, const in float roughness ) {
	const float LUT_SIZE = 64.0;
	const float LUT_SCALE = ( LUT_SIZE - 1.0 ) / LUT_SIZE;
	const float LUT_BIAS = 0.5 / LUT_SIZE;
	float dotNV = saturate( dot( N, V ) );
	vec2 uv = vec2( roughness, sqrt( 1.0 - dotNV ) );
	uv = uv * LUT_SCALE + LUT_BIAS;
	return uv;
}
float LTC_ClippedSphereFormFactor( const in vec3 f ) {
	float l = length( f );
	return max( ( l * l + f.z ) / ( l + 1.0 ), 0.0 );
}
vec3 LTC_EdgeVectorFormFactor( const in vec3 v1, const in vec3 v2 ) {
	float x = dot( v1, v2 );
	float y = abs( x );
	float a = 0.8543985 + ( 0.4965155 + 0.0145206 * y ) * y;
	float b = 3.4175940 + ( 4.1616724 + y ) * y;
	float v = a / b;
	float theta_sintheta = ( x > 0.0 ) ? v : 0.5 * inversesqrt( max( 1.0 - x * x, 1e-7 ) ) - v;
	return cross( v1, v2 ) * theta_sintheta;
}
vec3 LTC_Evaluate( const in vec3 N, const in vec3 V, const in vec3 P, const in mat3 mInv, const in vec3 rectCoords[ 4 ] ) {
	vec3 v1 = rectCoords[ 1 ] - rectCoords[ 0 ];
	vec3 v2 = rectCoords[ 3 ] - rectCoords[ 0 ];
	vec3 lightNormal = cross( v1, v2 );
	if( dot( lightNormal, P - rectCoords[ 0 ] ) < 0.0 ) return vec3( 0.0 );
	vec3 T1, T2;
	T1 = normalize( V - N * dot( V, N ) );
	T2 = - cross( N, T1 );
	mat3 mat = mInv * transposeMat3( mat3( T1, T2, N ) );
	vec3 coords[ 4 ];
	coords[ 0 ] = mat * ( rectCoords[ 0 ] - P );
	coords[ 1 ] = mat * ( rectCoords[ 1 ] - P );
	coords[ 2 ] = mat * ( rectCoords[ 2 ] - P );
	coords[ 3 ] = mat * ( rectCoords[ 3 ] - P );
	coords[ 0 ] = normalize( coords[ 0 ] );
	coords[ 1 ] = normalize( coords[ 1 ] );
	coords[ 2 ] = normalize( coords[ 2 ] );
	coords[ 3 ] = normalize( coords[ 3 ] );
	vec3 vectorFormFactor = vec3( 0.0 );
	vectorFormFactor += LTC_EdgeVectorFormFactor( coords[ 0 ], coords[ 1 ] );
	vectorFormFactor += LTC_EdgeVectorFormFactor( coords[ 1 ], coords[ 2 ] );
	vectorFormFactor += LTC_EdgeVectorFormFactor( coords[ 2 ], coords[ 3 ] );
	vectorFormFactor += LTC_EdgeVectorFormFactor( coords[ 3 ], coords[ 0 ] );
	float result = LTC_ClippedSphereFormFactor( vectorFormFactor );
	return vec3( result );
}
#if defined( USE_SHEEN )
float D_Charlie( float roughness, float dotNH ) {
	float alpha = pow2( roughness );
	float invAlpha = 1.0 / alpha;
	float cos2h = dotNH * dotNH;
	float sin2h = max( 1.0 - cos2h, 0.0078125 );
	return ( 2.0 + invAlpha ) * pow( sin2h, invAlpha * 0.5 ) / ( 2.0 * PI );
}
float V_Neubelt( float dotNV, float dotNL ) {
	return saturate( 1.0 / ( 4.0 * ( dotNL + dotNV - dotNL * dotNV ) ) );
}
vec3 BRDF_Sheen( const in vec3 lightDir, const in vec3 viewDir, const in vec3 normal, vec3 sheenColor, const in float sheenRoughness ) {
	vec3 halfDir = normalize( lightDir + viewDir );
	float dotNL = saturate( dot( normal, lightDir ) );
	float dotNV = saturate( dot( normal, viewDir ) );
	float dotNH = saturate( dot( normal, halfDir ) );
	float D = D_Charlie( sheenRoughness, dotNH );
	float V = V_Neubelt( dotNV, dotNL );
	return sheenColor * ( D * V );
}
#endif
float IBLSheenBRDF( const in vec3 normal, const in vec3 viewDir, const in float roughness ) {
	float dotNV = saturate( dot( normal, viewDir ) );
	float r2 = roughness * roughness;
	float a = roughness < 0.25 ? -339.2 * r2 + 161.4 * roughness - 25.9 : -8.48 * r2 + 14.3 * roughness - 9.95;
	float b = roughness < 0.25 ? 44.0 * r2 - 23.7 * roughness + 3.26 : 1.97 * r2 - 3.27 * roughness + 0.72;
	float DG = exp( a * dotNV + b ) + ( roughness < 0.25 ? 0.0 : 0.1 * ( roughness - 0.25 ) );
	return saturate( DG * RECIPROCAL_PI );
}
vec2 DFGApprox( const in vec3 normal, const in vec3 viewDir, const in float roughness ) {
	float dotNV = saturate( dot( normal, viewDir ) );
	const vec4 c0 = vec4( - 1, - 0.0275, - 0.572, 0.022 );
	const vec4 c1 = vec4( 1, 0.0425, 1.04, - 0.04 );
	vec4 r = roughness * c0 + c1;
	float a004 = min( r.x * r.x, exp2( - 9.28 * dotNV ) ) * r.x + r.y;
	vec2 fab = vec2( - 1.04, 1.04 ) * a004 + r.zw;
	return fab;
}
vec3 EnvironmentBRDF( const in vec3 normal, const in vec3 viewDir, const in vec3 specularColor, const in float specularF90, const in float roughness ) {
	vec2 fab = DFGApprox( normal, viewDir, roughness );
	return specularColor * fab.x + specularF90 * fab.y;
}
#ifdef USE_IRIDESCENCE
void computeMultiscatteringIridescence( const in vec3 normal, const in vec3 viewDir, const in vec3 specularColor, const in float specularF90, const in float iridescence, const in vec3 iridescenceF0, const in float roughness, inout vec3 singleScatter, inout vec3 multiScatter ) {
#else
void computeMultiscattering( const in vec3 normal, const in vec3 viewDir, const in vec3 specularColor, const in float specularF90, const in float roughness, inout vec3 singleScatter, inout vec3 multiScatter ) {
#endif
	vec2 fab = DFGApprox( normal, viewDir, roughness );
	#ifdef USE_IRIDESCENCE
		vec3 Fr = mix( specularColor, iridescenceF0, iridescence );
	#else
		vec3 Fr = specularColor;
	#endif
	vec3 FssEss = Fr * fab.x + specularF90 * fab.y;
	float Ess = fab.x + fab.y;
	float Ems = 1.0 - Ess;
	vec3 Favg = Fr + ( 1.0 - Fr ) * 0.047619;	vec3 Fms = FssEss * Favg / ( 1.0 - Ems * Favg );
	singleScatter += FssEss;
	multiScatter += Fms * Ems;
}
#if NUM_RECT_AREA_LIGHTS > 0
	void RE_Direct_RectArea_Physical( const in RectAreaLight rectAreaLight, const in vec3 geometryPosition, const in vec3 geometryNormal, const in vec3 geometryViewDir, const in vec3 geometryClearcoatNormal, const in PhysicalMaterial material, inout ReflectedLight reflectedLight ) {
		vec3 normal = geometryNormal;
		vec3 viewDir = geometryViewDir;
		vec3 position = geometryPosition;
		vec3 lightPos = rectAreaLight.position;
		vec3 halfWidth = rectAreaLight.halfWidth;
		vec3 halfHeight = rectAreaLight.halfHeight;
		vec3 lightColor = rectAreaLight.color;
		float roughness = material.roughness;
		vec3 rectCoords[ 4 ];
		rectCoords[ 0 ] = lightPos + halfWidth - halfHeight;		rectCoords[ 1 ] = lightPos - halfWidth - halfHeight;
		rectCoords[ 2 ] = lightPos - halfWidth + halfHeight;
		rectCoords[ 3 ] = lightPos + halfWidth + halfHeight;
		vec2 uv = LTC_Uv( normal, viewDir, roughness );
		vec4 t1 = texture2D( ltc_1, uv );
		vec4 t2 = texture2D( ltc_2, uv );
		mat3 mInv = mat3(
			vec3( t1.x, 0, t1.y ),
			vec3(    0, 1,    0 ),
			vec3( t1.z, 0, t1.w )
		);
		vec3 fresnel = ( material.specularColor * t2.x + ( vec3( 1.0 ) - material.specularColor ) * t2.y );
		reflectedLight.directSpecular += lightColor * fresnel * LTC_Evaluate( normal, viewDir, position, mInv, rectCoords );
		reflectedLight.directDiffuse += lightColor * material.diffuseColor * LTC_Evaluate( normal, viewDir, position, mat3( 1.0 ), rectCoords );
	}
#endif
void RE_Direct_Physical( const in IncidentLight directLight, const in vec3 geometryPosition, const in vec3 geometryNormal, const in vec3 geometryViewDir, const in vec3 geometryClearcoatNormal, const in PhysicalMaterial material, inout ReflectedLight reflectedLight ) {
	float dotNL = saturate( dot( geometryNormal, directLight.direction ) );
	vec3 irradiance = dotNL * directLight.color;
	#ifdef USE_CLEARCOAT
		float dotNLcc = saturate( dot( geometryClearcoatNormal, directLight.direction ) );
		vec3 ccIrradiance = dotNLcc * directLight.color;
		clearcoatSpecularDirect += ccIrradiance * BRDF_GGX_Clearcoat( directLight.direction, geometryViewDir, geometryClearcoatNormal, material );
	#endif
	#ifdef USE_SHEEN
		sheenSpecularDirect += irradiance * BRDF_Sheen( directLight.direction, geometryViewDir, geometryNormal, material.sheenColor, material.sheenRoughness );
	#endif
	reflectedLight.directSpecular += irradiance * BRDF_GGX( directLight.direction, geometryViewDir, geometryNormal, material );
	reflectedLight.directDiffuse += irradiance * BRDF_Lambert( material.diffuseColor );
}
void RE_IndirectDiffuse_Physical( const in vec3 irradiance, const in vec3 geometryPosition, const in vec3 geometryNormal, const in vec3 geometryViewDir, const in vec3 geometryClearcoatNormal, const in PhysicalMaterial material, inout ReflectedLight reflectedLight ) {
	reflectedLight.indirectDiffuse += irradiance * BRDF_Lambert( material.diffuseColor );
}
void RE_IndirectSpecular_Physical( const in vec3 radiance, const in vec3 irradiance, const in vec3 clearcoatRadiance, const in vec3 geometryPosition, const in vec3 geometryNormal, const in vec3 geometryViewDir, const in vec3 geometryClearcoatNormal, const in PhysicalMaterial material, inout ReflectedLight reflectedLight) {
	#ifdef USE_CLEARCOAT
		clearcoatSpecularIndirect += clearcoatRadiance * EnvironmentBRDF( geometryClearcoatNormal, geometryViewDir, material.clearcoatF0, material.clearcoatF90, material.clearcoatRoughness );
	#endif
	#ifdef USE_SHEEN
		sheenSpecularIndirect += irradiance * material.sheenColor * IBLSheenBRDF( geometryNormal, geometryViewDir, material.sheenRoughness );
	#endif
	vec3 singleScattering = vec3( 0.0 );
	vec3 multiScattering = vec3( 0.0 );
	vec3 cosineWeightedIrradiance = irradiance * RECIPROCAL_PI;
	#ifdef USE_IRIDESCENCE
		computeMultiscatteringIridescence( geometryNormal, geometryViewDir, material.specularColor, material.specularF90, material.iridescence, material.iridescenceFresnel, material.roughness, singleScattering, multiScattering );
	#else
		computeMultiscattering( geometryNormal, geometryViewDir, material.specularColor, material.specularF90, material.roughness, singleScattering, multiScattering );
	#endif
	vec3 totalScattering = singleScattering + multiScattering;
	vec3 diffuse = material.diffuseColor * ( 1.0 - max( max( totalScattering.r, totalScattering.g ), totalScattering.b ) );
	reflectedLight.indirectSpecular += radiance * singleScattering;
	reflectedLight.indirectSpecular += multiScattering * cosineWeightedIrradiance;
	reflectedLight.indirectDiffuse += diffuse * cosineWeightedIrradiance;
}
#define RE_Direct				RE_Direct_Physical
#define RE_Direct_RectArea		RE_Direct_RectArea_Physical
#define RE_IndirectDiffuse		RE_IndirectDiffuse_Physical
#define RE_IndirectSpecular		RE_IndirectSpecular_Physical
float computeSpecularOcclusion( const in float dotNV, const in float ambientOcclusion, const in float roughness ) {
	return saturate( pow( dotNV + ambientOcclusion, exp2( - 16.0 * roughness - 1.0 ) ) - 1.0 + ambientOcclusion );
}`, cx = `
vec3 geometryPosition = - vViewPosition;
vec3 geometryNormal = normal;
vec3 geometryViewDir = ( isOrthographic ) ? vec3( 0, 0, 1 ) : normalize( vViewPosition );
vec3 geometryClearcoatNormal = vec3( 0.0 );
#ifdef USE_CLEARCOAT
	geometryClearcoatNormal = clearcoatNormal;
#endif
#ifdef USE_IRIDESCENCE
	float dotNVi = saturate( dot( normal, geometryViewDir ) );
	if ( material.iridescenceThickness == 0.0 ) {
		material.iridescence = 0.0;
	} else {
		material.iridescence = saturate( material.iridescence );
	}
	if ( material.iridescence > 0.0 ) {
		material.iridescenceFresnel = evalIridescence( 1.0, material.iridescenceIOR, dotNVi, material.iridescenceThickness, material.specularColor );
		material.iridescenceF0 = Schlick_to_F0( material.iridescenceFresnel, 1.0, dotNVi );
	}
#endif
IncidentLight directLight;
#if ( NUM_POINT_LIGHTS > 0 ) && defined( RE_Direct )
	PointLight pointLight;
	#if defined( USE_SHADOWMAP ) && NUM_POINT_LIGHT_SHADOWS > 0
	PointLightShadow pointLightShadow;
	#endif
	#pragma unroll_loop_start
	for ( int i = 0; i < NUM_POINT_LIGHTS; i ++ ) {
		pointLight = pointLights[ i ];
		getPointLightInfo( pointLight, geometryPosition, directLight );
		#if defined( USE_SHADOWMAP ) && ( UNROLLED_LOOP_INDEX < NUM_POINT_LIGHT_SHADOWS )
		pointLightShadow = pointLightShadows[ i ];
		directLight.color *= ( directLight.visible && receiveShadow ) ? getPointShadow( pointShadowMap[ i ], pointLightShadow.shadowMapSize, pointLightShadow.shadowIntensity, pointLightShadow.shadowBias, pointLightShadow.shadowRadius, vPointShadowCoord[ i ], pointLightShadow.shadowCameraNear, pointLightShadow.shadowCameraFar ) : 1.0;
		#endif
		RE_Direct( directLight, geometryPosition, geometryNormal, geometryViewDir, geometryClearcoatNormal, material, reflectedLight );
	}
	#pragma unroll_loop_end
#endif
#if ( NUM_SPOT_LIGHTS > 0 ) && defined( RE_Direct )
	SpotLight spotLight;
	vec4 spotColor;
	vec3 spotLightCoord;
	bool inSpotLightMap;
	#if defined( USE_SHADOWMAP ) && NUM_SPOT_LIGHT_SHADOWS > 0
	SpotLightShadow spotLightShadow;
	#endif
	#pragma unroll_loop_start
	for ( int i = 0; i < NUM_SPOT_LIGHTS; i ++ ) {
		spotLight = spotLights[ i ];
		getSpotLightInfo( spotLight, geometryPosition, directLight );
		#if ( UNROLLED_LOOP_INDEX < NUM_SPOT_LIGHT_SHADOWS_WITH_MAPS )
		#define SPOT_LIGHT_MAP_INDEX UNROLLED_LOOP_INDEX
		#elif ( UNROLLED_LOOP_INDEX < NUM_SPOT_LIGHT_SHADOWS )
		#define SPOT_LIGHT_MAP_INDEX NUM_SPOT_LIGHT_MAPS
		#else
		#define SPOT_LIGHT_MAP_INDEX ( UNROLLED_LOOP_INDEX - NUM_SPOT_LIGHT_SHADOWS + NUM_SPOT_LIGHT_SHADOWS_WITH_MAPS )
		#endif
		#if ( SPOT_LIGHT_MAP_INDEX < NUM_SPOT_LIGHT_MAPS )
			spotLightCoord = vSpotLightCoord[ i ].xyz / vSpotLightCoord[ i ].w;
			inSpotLightMap = all( lessThan( abs( spotLightCoord * 2. - 1. ), vec3( 1.0 ) ) );
			spotColor = texture2D( spotLightMap[ SPOT_LIGHT_MAP_INDEX ], spotLightCoord.xy );
			directLight.color = inSpotLightMap ? directLight.color * spotColor.rgb : directLight.color;
		#endif
		#undef SPOT_LIGHT_MAP_INDEX
		#if defined( USE_SHADOWMAP ) && ( UNROLLED_LOOP_INDEX < NUM_SPOT_LIGHT_SHADOWS )
		spotLightShadow = spotLightShadows[ i ];
		directLight.color *= ( directLight.visible && receiveShadow ) ? getShadow( spotShadowMap[ i ], spotLightShadow.shadowMapSize, spotLightShadow.shadowIntensity, spotLightShadow.shadowBias, spotLightShadow.shadowRadius, vSpotLightCoord[ i ] ) : 1.0;
		#endif
		RE_Direct( directLight, geometryPosition, geometryNormal, geometryViewDir, geometryClearcoatNormal, material, reflectedLight );
	}
	#pragma unroll_loop_end
#endif
#if ( NUM_DIR_LIGHTS > 0 ) && defined( RE_Direct )
	DirectionalLight directionalLight;
	#if defined( USE_SHADOWMAP ) && NUM_DIR_LIGHT_SHADOWS > 0
	DirectionalLightShadow directionalLightShadow;
	#endif
	#pragma unroll_loop_start
	for ( int i = 0; i < NUM_DIR_LIGHTS; i ++ ) {
		directionalLight = directionalLights[ i ];
		getDirectionalLightInfo( directionalLight, directLight );
		#if defined( USE_SHADOWMAP ) && ( UNROLLED_LOOP_INDEX < NUM_DIR_LIGHT_SHADOWS )
		directionalLightShadow = directionalLightShadows[ i ];
		directLight.color *= ( directLight.visible && receiveShadow ) ? getShadow( directionalShadowMap[ i ], directionalLightShadow.shadowMapSize, directionalLightShadow.shadowIntensity, directionalLightShadow.shadowBias, directionalLightShadow.shadowRadius, vDirectionalShadowCoord[ i ] ) : 1.0;
		#endif
		RE_Direct( directLight, geometryPosition, geometryNormal, geometryViewDir, geometryClearcoatNormal, material, reflectedLight );
	}
	#pragma unroll_loop_end
#endif
#if ( NUM_RECT_AREA_LIGHTS > 0 ) && defined( RE_Direct_RectArea )
	RectAreaLight rectAreaLight;
	#pragma unroll_loop_start
	for ( int i = 0; i < NUM_RECT_AREA_LIGHTS; i ++ ) {
		rectAreaLight = rectAreaLights[ i ];
		RE_Direct_RectArea( rectAreaLight, geometryPosition, geometryNormal, geometryViewDir, geometryClearcoatNormal, material, reflectedLight );
	}
	#pragma unroll_loop_end
#endif
#if defined( RE_IndirectDiffuse )
	vec3 iblIrradiance = vec3( 0.0 );
	vec3 irradiance = getAmbientLightIrradiance( ambientLightColor );
	#if defined( USE_LIGHT_PROBES )
		irradiance += getLightProbeIrradiance( lightProbe, geometryNormal );
	#endif
	#if ( NUM_HEMI_LIGHTS > 0 )
		#pragma unroll_loop_start
		for ( int i = 0; i < NUM_HEMI_LIGHTS; i ++ ) {
			irradiance += getHemisphereLightIrradiance( hemisphereLights[ i ], geometryNormal );
		}
		#pragma unroll_loop_end
	#endif
#endif
#if defined( RE_IndirectSpecular )
	vec3 radiance = vec3( 0.0 );
	vec3 clearcoatRadiance = vec3( 0.0 );
#endif`, hx = `#if defined( RE_IndirectDiffuse )
	#ifdef USE_LIGHTMAP
		vec4 lightMapTexel = texture2D( lightMap, vLightMapUv );
		vec3 lightMapIrradiance = lightMapTexel.rgb * lightMapIntensity;
		irradiance += lightMapIrradiance;
	#endif
	#if defined( USE_ENVMAP ) && defined( STANDARD ) && defined( ENVMAP_TYPE_CUBE_UV )
		iblIrradiance += getIBLIrradiance( geometryNormal );
	#endif
#endif
#if defined( USE_ENVMAP ) && defined( RE_IndirectSpecular )
	#ifdef USE_ANISOTROPY
		radiance += getIBLAnisotropyRadiance( geometryViewDir, geometryNormal, material.roughness, material.anisotropyB, material.anisotropy );
	#else
		radiance += getIBLRadiance( geometryViewDir, geometryNormal, material.roughness );
	#endif
	#ifdef USE_CLEARCOAT
		clearcoatRadiance += getIBLRadiance( geometryViewDir, geometryClearcoatNormal, material.clearcoatRoughness );
	#endif
#endif`, dx = `#if defined( RE_IndirectDiffuse )
	RE_IndirectDiffuse( irradiance, geometryPosition, geometryNormal, geometryViewDir, geometryClearcoatNormal, material, reflectedLight );
#endif
#if defined( RE_IndirectSpecular )
	RE_IndirectSpecular( radiance, iblIrradiance, clearcoatRadiance, geometryPosition, geometryNormal, geometryViewDir, geometryClearcoatNormal, material, reflectedLight );
#endif`, ux = `#if defined( USE_LOGARITHMIC_DEPTH_BUFFER )
	gl_FragDepth = vIsPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;
#endif`, px = `#if defined( USE_LOGARITHMIC_DEPTH_BUFFER )
	uniform float logDepthBufFC;
	varying float vFragDepth;
	varying float vIsPerspective;
#endif`, fx = `#ifdef USE_LOGARITHMIC_DEPTH_BUFFER
	varying float vFragDepth;
	varying float vIsPerspective;
#endif`, mx = `#ifdef USE_LOGARITHMIC_DEPTH_BUFFER
	vFragDepth = 1.0 + gl_Position.w;
	vIsPerspective = float( isPerspectiveMatrix( projectionMatrix ) );
#endif`, gx = `#ifdef USE_MAP
	vec4 sampledDiffuseColor = texture2D( map, vMapUv );
	#ifdef DECODE_VIDEO_TEXTURE
		sampledDiffuseColor = sRGBTransferEOTF( sampledDiffuseColor );
	#endif
	diffuseColor *= sampledDiffuseColor;
#endif`, _x = `#ifdef USE_MAP
	uniform sampler2D map;
#endif`, yx = `#if defined( USE_MAP ) || defined( USE_ALPHAMAP )
	#if defined( USE_POINTS_UV )
		vec2 uv = vUv;
	#else
		vec2 uv = ( uvTransform * vec3( gl_PointCoord.x, 1.0 - gl_PointCoord.y, 1 ) ).xy;
	#endif
#endif
#ifdef USE_MAP
	diffuseColor *= texture2D( map, uv );
#endif
#ifdef USE_ALPHAMAP
	diffuseColor.a *= texture2D( alphaMap, uv ).g;
#endif`, vx = `#if defined( USE_POINTS_UV )
	varying vec2 vUv;
#else
	#if defined( USE_MAP ) || defined( USE_ALPHAMAP )
		uniform mat3 uvTransform;
	#endif
#endif
#ifdef USE_MAP
	uniform sampler2D map;
#endif
#ifdef USE_ALPHAMAP
	uniform sampler2D alphaMap;
#endif`, xx = `float metalnessFactor = metalness;
#ifdef USE_METALNESSMAP
	vec4 texelMetalness = texture2D( metalnessMap, vMetalnessMapUv );
	metalnessFactor *= texelMetalness.b;
#endif`, bx = `#ifdef USE_METALNESSMAP
	uniform sampler2D metalnessMap;
#endif`, Sx = `#ifdef USE_INSTANCING_MORPH
	float morphTargetInfluences[ MORPHTARGETS_COUNT ];
	float morphTargetBaseInfluence = texelFetch( morphTexture, ivec2( 0, gl_InstanceID ), 0 ).r;
	for ( int i = 0; i < MORPHTARGETS_COUNT; i ++ ) {
		morphTargetInfluences[i] =  texelFetch( morphTexture, ivec2( i + 1, gl_InstanceID ), 0 ).r;
	}
#endif`, Mx = `#if defined( USE_MORPHCOLORS )
	vColor *= morphTargetBaseInfluence;
	for ( int i = 0; i < MORPHTARGETS_COUNT; i ++ ) {
		#if defined( USE_COLOR_ALPHA )
			if ( morphTargetInfluences[ i ] != 0.0 ) vColor += getMorph( gl_VertexID, i, 2 ) * morphTargetInfluences[ i ];
		#elif defined( USE_COLOR )
			if ( morphTargetInfluences[ i ] != 0.0 ) vColor += getMorph( gl_VertexID, i, 2 ).rgb * morphTargetInfluences[ i ];
		#endif
	}
#endif`, wx = `#ifdef USE_MORPHNORMALS
	objectNormal *= morphTargetBaseInfluence;
	for ( int i = 0; i < MORPHTARGETS_COUNT; i ++ ) {
		if ( morphTargetInfluences[ i ] != 0.0 ) objectNormal += getMorph( gl_VertexID, i, 1 ).xyz * morphTargetInfluences[ i ];
	}
#endif`, Ex = `#ifdef USE_MORPHTARGETS
	#ifndef USE_INSTANCING_MORPH
		uniform float morphTargetBaseInfluence;
		uniform float morphTargetInfluences[ MORPHTARGETS_COUNT ];
	#endif
	uniform sampler2DArray morphTargetsTexture;
	uniform ivec2 morphTargetsTextureSize;
	vec4 getMorph( const in int vertexIndex, const in int morphTargetIndex, const in int offset ) {
		int texelIndex = vertexIndex * MORPHTARGETS_TEXTURE_STRIDE + offset;
		int y = texelIndex / morphTargetsTextureSize.x;
		int x = texelIndex - y * morphTargetsTextureSize.x;
		ivec3 morphUV = ivec3( x, y, morphTargetIndex );
		return texelFetch( morphTargetsTexture, morphUV, 0 );
	}
#endif`, Tx = `#ifdef USE_MORPHTARGETS
	transformed *= morphTargetBaseInfluence;
	for ( int i = 0; i < MORPHTARGETS_COUNT; i ++ ) {
		if ( morphTargetInfluences[ i ] != 0.0 ) transformed += getMorph( gl_VertexID, i, 0 ).xyz * morphTargetInfluences[ i ];
	}
#endif`, Ax = `float faceDirection = gl_FrontFacing ? 1.0 : - 1.0;
#ifdef FLAT_SHADED
	vec3 fdx = dFdx( vViewPosition );
	vec3 fdy = dFdy( vViewPosition );
	vec3 normal = normalize( cross( fdx, fdy ) );
#else
	vec3 normal = normalize( vNormal );
	#ifdef DOUBLE_SIDED
		normal *= faceDirection;
	#endif
#endif
#if defined( USE_NORMALMAP_TANGENTSPACE ) || defined( USE_CLEARCOAT_NORMALMAP ) || defined( USE_ANISOTROPY )
	#ifdef USE_TANGENT
		mat3 tbn = mat3( normalize( vTangent ), normalize( vBitangent ), normal );
	#else
		mat3 tbn = getTangentFrame( - vViewPosition, normal,
		#if defined( USE_NORMALMAP )
			vNormalMapUv
		#elif defined( USE_CLEARCOAT_NORMALMAP )
			vClearcoatNormalMapUv
		#else
			vUv
		#endif
		);
	#endif
	#if defined( DOUBLE_SIDED ) && ! defined( FLAT_SHADED )
		tbn[0] *= faceDirection;
		tbn[1] *= faceDirection;
	#endif
#endif
#ifdef USE_CLEARCOAT_NORMALMAP
	#ifdef USE_TANGENT
		mat3 tbn2 = mat3( normalize( vTangent ), normalize( vBitangent ), normal );
	#else
		mat3 tbn2 = getTangentFrame( - vViewPosition, normal, vClearcoatNormalMapUv );
	#endif
	#if defined( DOUBLE_SIDED ) && ! defined( FLAT_SHADED )
		tbn2[0] *= faceDirection;
		tbn2[1] *= faceDirection;
	#endif
#endif
vec3 nonPerturbedNormal = normal;`, Cx = `#ifdef USE_NORMALMAP_OBJECTSPACE
	normal = texture2D( normalMap, vNormalMapUv ).xyz * 2.0 - 1.0;
	#ifdef FLIP_SIDED
		normal = - normal;
	#endif
	#ifdef DOUBLE_SIDED
		normal = normal * faceDirection;
	#endif
	normal = normalize( normalMatrix * normal );
#elif defined( USE_NORMALMAP_TANGENTSPACE )
	vec3 mapN = texture2D( normalMap, vNormalMapUv ).xyz * 2.0 - 1.0;
	mapN.xy *= normalScale;
	normal = normalize( tbn * mapN );
#elif defined( USE_BUMPMAP )
	normal = perturbNormalArb( - vViewPosition, normal, dHdxy_fwd(), faceDirection );
#endif`, Rx = `#ifndef FLAT_SHADED
	varying vec3 vNormal;
	#ifdef USE_TANGENT
		varying vec3 vTangent;
		varying vec3 vBitangent;
	#endif
#endif`, Px = `#ifndef FLAT_SHADED
	varying vec3 vNormal;
	#ifdef USE_TANGENT
		varying vec3 vTangent;
		varying vec3 vBitangent;
	#endif
#endif`, Lx = `#ifndef FLAT_SHADED
	vNormal = normalize( transformedNormal );
	#ifdef USE_TANGENT
		vTangent = normalize( transformedTangent );
		vBitangent = normalize( cross( vNormal, vTangent ) * tangent.w );
	#endif
#endif`, Ix = `#ifdef USE_NORMALMAP
	uniform sampler2D normalMap;
	uniform vec2 normalScale;
#endif
#ifdef USE_NORMALMAP_OBJECTSPACE
	uniform mat3 normalMatrix;
#endif
#if ! defined ( USE_TANGENT ) && ( defined ( USE_NORMALMAP_TANGENTSPACE ) || defined ( USE_CLEARCOAT_NORMALMAP ) || defined( USE_ANISOTROPY ) )
	mat3 getTangentFrame( vec3 eye_pos, vec3 surf_norm, vec2 uv ) {
		vec3 q0 = dFdx( eye_pos.xyz );
		vec3 q1 = dFdy( eye_pos.xyz );
		vec2 st0 = dFdx( uv.st );
		vec2 st1 = dFdy( uv.st );
		vec3 N = surf_norm;
		vec3 q1perp = cross( q1, N );
		vec3 q0perp = cross( N, q0 );
		vec3 T = q1perp * st0.x + q0perp * st1.x;
		vec3 B = q1perp * st0.y + q0perp * st1.y;
		float det = max( dot( T, T ), dot( B, B ) );
		float scale = ( det == 0.0 ) ? 0.0 : inversesqrt( det );
		return mat3( T * scale, B * scale, N );
	}
#endif`, Dx = `#ifdef USE_CLEARCOAT
	vec3 clearcoatNormal = nonPerturbedNormal;
#endif`, Nx = `#ifdef USE_CLEARCOAT_NORMALMAP
	vec3 clearcoatMapN = texture2D( clearcoatNormalMap, vClearcoatNormalMapUv ).xyz * 2.0 - 1.0;
	clearcoatMapN.xy *= clearcoatNormalScale;
	clearcoatNormal = normalize( tbn2 * clearcoatMapN );
#endif`, Ux = `#ifdef USE_CLEARCOATMAP
	uniform sampler2D clearcoatMap;
#endif
#ifdef USE_CLEARCOAT_NORMALMAP
	uniform sampler2D clearcoatNormalMap;
	uniform vec2 clearcoatNormalScale;
#endif
#ifdef USE_CLEARCOAT_ROUGHNESSMAP
	uniform sampler2D clearcoatRoughnessMap;
#endif`, Ox = `#ifdef USE_IRIDESCENCEMAP
	uniform sampler2D iridescenceMap;
#endif
#ifdef USE_IRIDESCENCE_THICKNESSMAP
	uniform sampler2D iridescenceThicknessMap;
#endif`, Fx = `#ifdef OPAQUE
diffuseColor.a = 1.0;
#endif
#ifdef USE_TRANSMISSION
diffuseColor.a *= material.transmissionAlpha;
#endif
gl_FragColor = vec4( outgoingLight, diffuseColor.a );`, Bx = `vec3 packNormalToRGB( const in vec3 normal ) {
	return normalize( normal ) * 0.5 + 0.5;
}
vec3 unpackRGBToNormal( const in vec3 rgb ) {
	return 2.0 * rgb.xyz - 1.0;
}
const float PackUpscale = 256. / 255.;const float UnpackDownscale = 255. / 256.;const float ShiftRight8 = 1. / 256.;
const float Inv255 = 1. / 255.;
const vec4 PackFactors = vec4( 1.0, 256.0, 256.0 * 256.0, 256.0 * 256.0 * 256.0 );
const vec2 UnpackFactors2 = vec2( UnpackDownscale, 1.0 / PackFactors.g );
const vec3 UnpackFactors3 = vec3( UnpackDownscale / PackFactors.rg, 1.0 / PackFactors.b );
const vec4 UnpackFactors4 = vec4( UnpackDownscale / PackFactors.rgb, 1.0 / PackFactors.a );
vec4 packDepthToRGBA( const in float v ) {
	if( v <= 0.0 )
		return vec4( 0., 0., 0., 0. );
	if( v >= 1.0 )
		return vec4( 1., 1., 1., 1. );
	float vuf;
	float af = modf( v * PackFactors.a, vuf );
	float bf = modf( vuf * ShiftRight8, vuf );
	float gf = modf( vuf * ShiftRight8, vuf );
	return vec4( vuf * Inv255, gf * PackUpscale, bf * PackUpscale, af );
}
vec3 packDepthToRGB( const in float v ) {
	if( v <= 0.0 )
		return vec3( 0., 0., 0. );
	if( v >= 1.0 )
		return vec3( 1., 1., 1. );
	float vuf;
	float bf = modf( v * PackFactors.b, vuf );
	float gf = modf( vuf * ShiftRight8, vuf );
	return vec3( vuf * Inv255, gf * PackUpscale, bf );
}
vec2 packDepthToRG( const in float v ) {
	if( v <= 0.0 )
		return vec2( 0., 0. );
	if( v >= 1.0 )
		return vec2( 1., 1. );
	float vuf;
	float gf = modf( v * 256., vuf );
	return vec2( vuf * Inv255, gf );
}
float unpackRGBAToDepth( const in vec4 v ) {
	return dot( v, UnpackFactors4 );
}
float unpackRGBToDepth( const in vec3 v ) {
	return dot( v, UnpackFactors3 );
}
float unpackRGToDepth( const in vec2 v ) {
	return v.r * UnpackFactors2.r + v.g * UnpackFactors2.g;
}
vec4 pack2HalfToRGBA( const in vec2 v ) {
	vec4 r = vec4( v.x, fract( v.x * 255.0 ), v.y, fract( v.y * 255.0 ) );
	return vec4( r.x - r.y / 255.0, r.y, r.z - r.w / 255.0, r.w );
}
vec2 unpackRGBATo2Half( const in vec4 v ) {
	return vec2( v.x + ( v.y / 255.0 ), v.z + ( v.w / 255.0 ) );
}
float viewZToOrthographicDepth( const in float viewZ, const in float near, const in float far ) {
	return ( viewZ + near ) / ( near - far );
}
float orthographicDepthToViewZ( const in float depth, const in float near, const in float far ) {
	return depth * ( near - far ) - near;
}
float viewZToPerspectiveDepth( const in float viewZ, const in float near, const in float far ) {
	return ( ( near + viewZ ) * far ) / ( ( far - near ) * viewZ );
}
float perspectiveDepthToViewZ( const in float depth, const in float near, const in float far ) {
	return ( near * far ) / ( ( far - near ) * depth - far );
}`, kx = `#ifdef PREMULTIPLIED_ALPHA
	gl_FragColor.rgb *= gl_FragColor.a;
#endif`, zx = `vec4 mvPosition = vec4( transformed, 1.0 );
#ifdef USE_BATCHING
	mvPosition = batchingMatrix * mvPosition;
#endif
#ifdef USE_INSTANCING
	mvPosition = instanceMatrix * mvPosition;
#endif
mvPosition = modelViewMatrix * mvPosition;
gl_Position = projectionMatrix * mvPosition;`, Hx = `#ifdef DITHERING
	gl_FragColor.rgb = dithering( gl_FragColor.rgb );
#endif`, Vx = `#ifdef DITHERING
	vec3 dithering( vec3 color ) {
		float grid_position = rand( gl_FragCoord.xy );
		vec3 dither_shift_RGB = vec3( 0.25 / 255.0, -0.25 / 255.0, 0.25 / 255.0 );
		dither_shift_RGB = mix( 2.0 * dither_shift_RGB, -2.0 * dither_shift_RGB, grid_position );
		return color + dither_shift_RGB;
	}
#endif`, Gx = `float roughnessFactor = roughness;
#ifdef USE_ROUGHNESSMAP
	vec4 texelRoughness = texture2D( roughnessMap, vRoughnessMapUv );
	roughnessFactor *= texelRoughness.g;
#endif`, Wx = `#ifdef USE_ROUGHNESSMAP
	uniform sampler2D roughnessMap;
#endif`, Xx = `#if NUM_SPOT_LIGHT_COORDS > 0
	varying vec4 vSpotLightCoord[ NUM_SPOT_LIGHT_COORDS ];
#endif
#if NUM_SPOT_LIGHT_MAPS > 0
	uniform sampler2D spotLightMap[ NUM_SPOT_LIGHT_MAPS ];
#endif
#ifdef USE_SHADOWMAP
	#if NUM_DIR_LIGHT_SHADOWS > 0
		uniform sampler2D directionalShadowMap[ NUM_DIR_LIGHT_SHADOWS ];
		varying vec4 vDirectionalShadowCoord[ NUM_DIR_LIGHT_SHADOWS ];
		struct DirectionalLightShadow {
			float shadowIntensity;
			float shadowBias;
			float shadowNormalBias;
			float shadowRadius;
			vec2 shadowMapSize;
		};
		uniform DirectionalLightShadow directionalLightShadows[ NUM_DIR_LIGHT_SHADOWS ];
	#endif
	#if NUM_SPOT_LIGHT_SHADOWS > 0
		uniform sampler2D spotShadowMap[ NUM_SPOT_LIGHT_SHADOWS ];
		struct SpotLightShadow {
			float shadowIntensity;
			float shadowBias;
			float shadowNormalBias;
			float shadowRadius;
			vec2 shadowMapSize;
		};
		uniform SpotLightShadow spotLightShadows[ NUM_SPOT_LIGHT_SHADOWS ];
	#endif
	#if NUM_POINT_LIGHT_SHADOWS > 0
		uniform sampler2D pointShadowMap[ NUM_POINT_LIGHT_SHADOWS ];
		varying vec4 vPointShadowCoord[ NUM_POINT_LIGHT_SHADOWS ];
		struct PointLightShadow {
			float shadowIntensity;
			float shadowBias;
			float shadowNormalBias;
			float shadowRadius;
			vec2 shadowMapSize;
			float shadowCameraNear;
			float shadowCameraFar;
		};
		uniform PointLightShadow pointLightShadows[ NUM_POINT_LIGHT_SHADOWS ];
	#endif
	float texture2DCompare( sampler2D depths, vec2 uv, float compare ) {
		float depth = unpackRGBAToDepth( texture2D( depths, uv ) );
		#ifdef USE_REVERSED_DEPTH_BUFFER
			return step( depth, compare );
		#else
			return step( compare, depth );
		#endif
	}
	vec2 texture2DDistribution( sampler2D shadow, vec2 uv ) {
		return unpackRGBATo2Half( texture2D( shadow, uv ) );
	}
	float VSMShadow( sampler2D shadow, vec2 uv, float compare ) {
		float occlusion = 1.0;
		vec2 distribution = texture2DDistribution( shadow, uv );
		#ifdef USE_REVERSED_DEPTH_BUFFER
			float hard_shadow = step( distribution.x, compare );
		#else
			float hard_shadow = step( compare, distribution.x );
		#endif
		if ( hard_shadow != 1.0 ) {
			float distance = compare - distribution.x;
			float variance = max( 0.00000, distribution.y * distribution.y );
			float softness_probability = variance / (variance + distance * distance );			softness_probability = clamp( ( softness_probability - 0.3 ) / ( 0.95 - 0.3 ), 0.0, 1.0 );			occlusion = clamp( max( hard_shadow, softness_probability ), 0.0, 1.0 );
		}
		return occlusion;
	}
	float getShadow( sampler2D shadowMap, vec2 shadowMapSize, float shadowIntensity, float shadowBias, float shadowRadius, vec4 shadowCoord ) {
		float shadow = 1.0;
		shadowCoord.xyz /= shadowCoord.w;
		shadowCoord.z += shadowBias;
		bool inFrustum = shadowCoord.x >= 0.0 && shadowCoord.x <= 1.0 && shadowCoord.y >= 0.0 && shadowCoord.y <= 1.0;
		bool frustumTest = inFrustum && shadowCoord.z <= 1.0;
		if ( frustumTest ) {
		#if defined( SHADOWMAP_TYPE_PCF )
			vec2 texelSize = vec2( 1.0 ) / shadowMapSize;
			float dx0 = - texelSize.x * shadowRadius;
			float dy0 = - texelSize.y * shadowRadius;
			float dx1 = + texelSize.x * shadowRadius;
			float dy1 = + texelSize.y * shadowRadius;
			float dx2 = dx0 / 2.0;
			float dy2 = dy0 / 2.0;
			float dx3 = dx1 / 2.0;
			float dy3 = dy1 / 2.0;
			shadow = (
				texture2DCompare( shadowMap, shadowCoord.xy + vec2( dx0, dy0 ), shadowCoord.z ) +
				texture2DCompare( shadowMap, shadowCoord.xy + vec2( 0.0, dy0 ), shadowCoord.z ) +
				texture2DCompare( shadowMap, shadowCoord.xy + vec2( dx1, dy0 ), shadowCoord.z ) +
				texture2DCompare( shadowMap, shadowCoord.xy + vec2( dx2, dy2 ), shadowCoord.z ) +
				texture2DCompare( shadowMap, shadowCoord.xy + vec2( 0.0, dy2 ), shadowCoord.z ) +
				texture2DCompare( shadowMap, shadowCoord.xy + vec2( dx3, dy2 ), shadowCoord.z ) +
				texture2DCompare( shadowMap, shadowCoord.xy + vec2( dx0, 0.0 ), shadowCoord.z ) +
				texture2DCompare( shadowMap, shadowCoord.xy + vec2( dx2, 0.0 ), shadowCoord.z ) +
				texture2DCompare( shadowMap, shadowCoord.xy, shadowCoord.z ) +
				texture2DCompare( shadowMap, shadowCoord.xy + vec2( dx3, 0.0 ), shadowCoord.z ) +
				texture2DCompare( shadowMap, shadowCoord.xy + vec2( dx1, 0.0 ), shadowCoord.z ) +
				texture2DCompare( shadowMap, shadowCoord.xy + vec2( dx2, dy3 ), shadowCoord.z ) +
				texture2DCompare( shadowMap, shadowCoord.xy + vec2( 0.0, dy3 ), shadowCoord.z ) +
				texture2DCompare( shadowMap, shadowCoord.xy + vec2( dx3, dy3 ), shadowCoord.z ) +
				texture2DCompare( shadowMap, shadowCoord.xy + vec2( dx0, dy1 ), shadowCoord.z ) +
				texture2DCompare( shadowMap, shadowCoord.xy + vec2( 0.0, dy1 ), shadowCoord.z ) +
				texture2DCompare( shadowMap, shadowCoord.xy + vec2( dx1, dy1 ), shadowCoord.z )
			) * ( 1.0 / 17.0 );
		#elif defined( SHADOWMAP_TYPE_PCF_SOFT )
			vec2 texelSize = vec2( 1.0 ) / shadowMapSize;
			float dx = texelSize.x;
			float dy = texelSize.y;
			vec2 uv = shadowCoord.xy;
			vec2 f = fract( uv * shadowMapSize + 0.5 );
			uv -= f * texelSize;
			shadow = (
				texture2DCompare( shadowMap, uv, shadowCoord.z ) +
				texture2DCompare( shadowMap, uv + vec2( dx, 0.0 ), shadowCoord.z ) +
				texture2DCompare( shadowMap, uv + vec2( 0.0, dy ), shadowCoord.z ) +
				texture2DCompare( shadowMap, uv + texelSize, shadowCoord.z ) +
				mix( texture2DCompare( shadowMap, uv + vec2( -dx, 0.0 ), shadowCoord.z ),
					 texture2DCompare( shadowMap, uv + vec2( 2.0 * dx, 0.0 ), shadowCoord.z ),
					 f.x ) +
				mix( texture2DCompare( shadowMap, uv + vec2( -dx, dy ), shadowCoord.z ),
					 texture2DCompare( shadowMap, uv + vec2( 2.0 * dx, dy ), shadowCoord.z ),
					 f.x ) +
				mix( texture2DCompare( shadowMap, uv + vec2( 0.0, -dy ), shadowCoord.z ),
					 texture2DCompare( shadowMap, uv + vec2( 0.0, 2.0 * dy ), shadowCoord.z ),
					 f.y ) +
				mix( texture2DCompare( shadowMap, uv + vec2( dx, -dy ), shadowCoord.z ),
					 texture2DCompare( shadowMap, uv + vec2( dx, 2.0 * dy ), shadowCoord.z ),
					 f.y ) +
				mix( mix( texture2DCompare( shadowMap, uv + vec2( -dx, -dy ), shadowCoord.z ),
						  texture2DCompare( shadowMap, uv + vec2( 2.0 * dx, -dy ), shadowCoord.z ),
						  f.x ),
					 mix( texture2DCompare( shadowMap, uv + vec2( -dx, 2.0 * dy ), shadowCoord.z ),
						  texture2DCompare( shadowMap, uv + vec2( 2.0 * dx, 2.0 * dy ), shadowCoord.z ),
						  f.x ),
					 f.y )
			) * ( 1.0 / 9.0 );
		#elif defined( SHADOWMAP_TYPE_VSM )
			shadow = VSMShadow( shadowMap, shadowCoord.xy, shadowCoord.z );
		#else
			shadow = texture2DCompare( shadowMap, shadowCoord.xy, shadowCoord.z );
		#endif
		}
		return mix( 1.0, shadow, shadowIntensity );
	}
	vec2 cubeToUV( vec3 v, float texelSizeY ) {
		vec3 absV = abs( v );
		float scaleToCube = 1.0 / max( absV.x, max( absV.y, absV.z ) );
		absV *= scaleToCube;
		v *= scaleToCube * ( 1.0 - 2.0 * texelSizeY );
		vec2 planar = v.xy;
		float almostATexel = 1.5 * texelSizeY;
		float almostOne = 1.0 - almostATexel;
		if ( absV.z >= almostOne ) {
			if ( v.z > 0.0 )
				planar.x = 4.0 - v.x;
		} else if ( absV.x >= almostOne ) {
			float signX = sign( v.x );
			planar.x = v.z * signX + 2.0 * signX;
		} else if ( absV.y >= almostOne ) {
			float signY = sign( v.y );
			planar.x = v.x + 2.0 * signY + 2.0;
			planar.y = v.z * signY - 2.0;
		}
		return vec2( 0.125, 0.25 ) * planar + vec2( 0.375, 0.75 );
	}
	float getPointShadow( sampler2D shadowMap, vec2 shadowMapSize, float shadowIntensity, float shadowBias, float shadowRadius, vec4 shadowCoord, float shadowCameraNear, float shadowCameraFar ) {
		float shadow = 1.0;
		vec3 lightToPosition = shadowCoord.xyz;
		
		float lightToPositionLength = length( lightToPosition );
		if ( lightToPositionLength - shadowCameraFar <= 0.0 && lightToPositionLength - shadowCameraNear >= 0.0 ) {
			float dp = ( lightToPositionLength - shadowCameraNear ) / ( shadowCameraFar - shadowCameraNear );			dp += shadowBias;
			vec3 bd3D = normalize( lightToPosition );
			vec2 texelSize = vec2( 1.0 ) / ( shadowMapSize * vec2( 4.0, 2.0 ) );
			#if defined( SHADOWMAP_TYPE_PCF ) || defined( SHADOWMAP_TYPE_PCF_SOFT ) || defined( SHADOWMAP_TYPE_VSM )
				vec2 offset = vec2( - 1, 1 ) * shadowRadius * texelSize.y;
				shadow = (
					texture2DCompare( shadowMap, cubeToUV( bd3D + offset.xyy, texelSize.y ), dp ) +
					texture2DCompare( shadowMap, cubeToUV( bd3D + offset.yyy, texelSize.y ), dp ) +
					texture2DCompare( shadowMap, cubeToUV( bd3D + offset.xyx, texelSize.y ), dp ) +
					texture2DCompare( shadowMap, cubeToUV( bd3D + offset.yyx, texelSize.y ), dp ) +
					texture2DCompare( shadowMap, cubeToUV( bd3D, texelSize.y ), dp ) +
					texture2DCompare( shadowMap, cubeToUV( bd3D + offset.xxy, texelSize.y ), dp ) +
					texture2DCompare( shadowMap, cubeToUV( bd3D + offset.yxy, texelSize.y ), dp ) +
					texture2DCompare( shadowMap, cubeToUV( bd3D + offset.xxx, texelSize.y ), dp ) +
					texture2DCompare( shadowMap, cubeToUV( bd3D + offset.yxx, texelSize.y ), dp )
				) * ( 1.0 / 9.0 );
			#else
				shadow = texture2DCompare( shadowMap, cubeToUV( bd3D, texelSize.y ), dp );
			#endif
		}
		return mix( 1.0, shadow, shadowIntensity );
	}
#endif`, qx = `#if NUM_SPOT_LIGHT_COORDS > 0
	uniform mat4 spotLightMatrix[ NUM_SPOT_LIGHT_COORDS ];
	varying vec4 vSpotLightCoord[ NUM_SPOT_LIGHT_COORDS ];
#endif
#ifdef USE_SHADOWMAP
	#if NUM_DIR_LIGHT_SHADOWS > 0
		uniform mat4 directionalShadowMatrix[ NUM_DIR_LIGHT_SHADOWS ];
		varying vec4 vDirectionalShadowCoord[ NUM_DIR_LIGHT_SHADOWS ];
		struct DirectionalLightShadow {
			float shadowIntensity;
			float shadowBias;
			float shadowNormalBias;
			float shadowRadius;
			vec2 shadowMapSize;
		};
		uniform DirectionalLightShadow directionalLightShadows[ NUM_DIR_LIGHT_SHADOWS ];
	#endif
	#if NUM_SPOT_LIGHT_SHADOWS > 0
		struct SpotLightShadow {
			float shadowIntensity;
			float shadowBias;
			float shadowNormalBias;
			float shadowRadius;
			vec2 shadowMapSize;
		};
		uniform SpotLightShadow spotLightShadows[ NUM_SPOT_LIGHT_SHADOWS ];
	#endif
	#if NUM_POINT_LIGHT_SHADOWS > 0
		uniform mat4 pointShadowMatrix[ NUM_POINT_LIGHT_SHADOWS ];
		varying vec4 vPointShadowCoord[ NUM_POINT_LIGHT_SHADOWS ];
		struct PointLightShadow {
			float shadowIntensity;
			float shadowBias;
			float shadowNormalBias;
			float shadowRadius;
			vec2 shadowMapSize;
			float shadowCameraNear;
			float shadowCameraFar;
		};
		uniform PointLightShadow pointLightShadows[ NUM_POINT_LIGHT_SHADOWS ];
	#endif
#endif`, Zx = `#if ( defined( USE_SHADOWMAP ) && ( NUM_DIR_LIGHT_SHADOWS > 0 || NUM_POINT_LIGHT_SHADOWS > 0 ) ) || ( NUM_SPOT_LIGHT_COORDS > 0 )
	vec3 shadowWorldNormal = inverseTransformDirection( transformedNormal, viewMatrix );
	vec4 shadowWorldPosition;
#endif
#if defined( USE_SHADOWMAP )
	#if NUM_DIR_LIGHT_SHADOWS > 0
		#pragma unroll_loop_start
		for ( int i = 0; i < NUM_DIR_LIGHT_SHADOWS; i ++ ) {
			shadowWorldPosition = worldPosition + vec4( shadowWorldNormal * directionalLightShadows[ i ].shadowNormalBias, 0 );
			vDirectionalShadowCoord[ i ] = directionalShadowMatrix[ i ] * shadowWorldPosition;
		}
		#pragma unroll_loop_end
	#endif
	#if NUM_POINT_LIGHT_SHADOWS > 0
		#pragma unroll_loop_start
		for ( int i = 0; i < NUM_POINT_LIGHT_SHADOWS; i ++ ) {
			shadowWorldPosition = worldPosition + vec4( shadowWorldNormal * pointLightShadows[ i ].shadowNormalBias, 0 );
			vPointShadowCoord[ i ] = pointShadowMatrix[ i ] * shadowWorldPosition;
		}
		#pragma unroll_loop_end
	#endif
#endif
#if NUM_SPOT_LIGHT_COORDS > 0
	#pragma unroll_loop_start
	for ( int i = 0; i < NUM_SPOT_LIGHT_COORDS; i ++ ) {
		shadowWorldPosition = worldPosition;
		#if ( defined( USE_SHADOWMAP ) && UNROLLED_LOOP_INDEX < NUM_SPOT_LIGHT_SHADOWS )
			shadowWorldPosition.xyz += shadowWorldNormal * spotLightShadows[ i ].shadowNormalBias;
		#endif
		vSpotLightCoord[ i ] = spotLightMatrix[ i ] * shadowWorldPosition;
	}
	#pragma unroll_loop_end
#endif`, Yx = `float getShadowMask() {
	float shadow = 1.0;
	#ifdef USE_SHADOWMAP
	#if NUM_DIR_LIGHT_SHADOWS > 0
	DirectionalLightShadow directionalLight;
	#pragma unroll_loop_start
	for ( int i = 0; i < NUM_DIR_LIGHT_SHADOWS; i ++ ) {
		directionalLight = directionalLightShadows[ i ];
		shadow *= receiveShadow ? getShadow( directionalShadowMap[ i ], directionalLight.shadowMapSize, directionalLight.shadowIntensity, directionalLight.shadowBias, directionalLight.shadowRadius, vDirectionalShadowCoord[ i ] ) : 1.0;
	}
	#pragma unroll_loop_end
	#endif
	#if NUM_SPOT_LIGHT_SHADOWS > 0
	SpotLightShadow spotLight;
	#pragma unroll_loop_start
	for ( int i = 0; i < NUM_SPOT_LIGHT_SHADOWS; i ++ ) {
		spotLight = spotLightShadows[ i ];
		shadow *= receiveShadow ? getShadow( spotShadowMap[ i ], spotLight.shadowMapSize, spotLight.shadowIntensity, spotLight.shadowBias, spotLight.shadowRadius, vSpotLightCoord[ i ] ) : 1.0;
	}
	#pragma unroll_loop_end
	#endif
	#if NUM_POINT_LIGHT_SHADOWS > 0
	PointLightShadow pointLight;
	#pragma unroll_loop_start
	for ( int i = 0; i < NUM_POINT_LIGHT_SHADOWS; i ++ ) {
		pointLight = pointLightShadows[ i ];
		shadow *= receiveShadow ? getPointShadow( pointShadowMap[ i ], pointLight.shadowMapSize, pointLight.shadowIntensity, pointLight.shadowBias, pointLight.shadowRadius, vPointShadowCoord[ i ], pointLight.shadowCameraNear, pointLight.shadowCameraFar ) : 1.0;
	}
	#pragma unroll_loop_end
	#endif
	#endif
	return shadow;
}`, jx = `#ifdef USE_SKINNING
	mat4 boneMatX = getBoneMatrix( skinIndex.x );
	mat4 boneMatY = getBoneMatrix( skinIndex.y );
	mat4 boneMatZ = getBoneMatrix( skinIndex.z );
	mat4 boneMatW = getBoneMatrix( skinIndex.w );
#endif`, $x = `#ifdef USE_SKINNING
	uniform mat4 bindMatrix;
	uniform mat4 bindMatrixInverse;
	uniform highp sampler2D boneTexture;
	mat4 getBoneMatrix( const in float i ) {
		int size = textureSize( boneTexture, 0 ).x;
		int j = int( i ) * 4;
		int x = j % size;
		int y = j / size;
		vec4 v1 = texelFetch( boneTexture, ivec2( x, y ), 0 );
		vec4 v2 = texelFetch( boneTexture, ivec2( x + 1, y ), 0 );
		vec4 v3 = texelFetch( boneTexture, ivec2( x + 2, y ), 0 );
		vec4 v4 = texelFetch( boneTexture, ivec2( x + 3, y ), 0 );
		return mat4( v1, v2, v3, v4 );
	}
#endif`, Kx = `#ifdef USE_SKINNING
	vec4 skinVertex = bindMatrix * vec4( transformed, 1.0 );
	vec4 skinned = vec4( 0.0 );
	skinned += boneMatX * skinVertex * skinWeight.x;
	skinned += boneMatY * skinVertex * skinWeight.y;
	skinned += boneMatZ * skinVertex * skinWeight.z;
	skinned += boneMatW * skinVertex * skinWeight.w;
	transformed = ( bindMatrixInverse * skinned ).xyz;
#endif`, Jx = `#ifdef USE_SKINNING
	mat4 skinMatrix = mat4( 0.0 );
	skinMatrix += skinWeight.x * boneMatX;
	skinMatrix += skinWeight.y * boneMatY;
	skinMatrix += skinWeight.z * boneMatZ;
	skinMatrix += skinWeight.w * boneMatW;
	skinMatrix = bindMatrixInverse * skinMatrix * bindMatrix;
	objectNormal = vec4( skinMatrix * vec4( objectNormal, 0.0 ) ).xyz;
	#ifdef USE_TANGENT
		objectTangent = vec4( skinMatrix * vec4( objectTangent, 0.0 ) ).xyz;
	#endif
#endif`, Qx = `float specularStrength;
#ifdef USE_SPECULARMAP
	vec4 texelSpecular = texture2D( specularMap, vSpecularMapUv );
	specularStrength = texelSpecular.r;
#else
	specularStrength = 1.0;
#endif`, eb = `#ifdef USE_SPECULARMAP
	uniform sampler2D specularMap;
#endif`, tb = `#if defined( TONE_MAPPING )
	gl_FragColor.rgb = toneMapping( gl_FragColor.rgb );
#endif`, ib = `#ifndef saturate
#define saturate( a ) clamp( a, 0.0, 1.0 )
#endif
uniform float toneMappingExposure;
vec3 LinearToneMapping( vec3 color ) {
	return saturate( toneMappingExposure * color );
}
vec3 ReinhardToneMapping( vec3 color ) {
	color *= toneMappingExposure;
	return saturate( color / ( vec3( 1.0 ) + color ) );
}
vec3 CineonToneMapping( vec3 color ) {
	color *= toneMappingExposure;
	color = max( vec3( 0.0 ), color - 0.004 );
	return pow( ( color * ( 6.2 * color + 0.5 ) ) / ( color * ( 6.2 * color + 1.7 ) + 0.06 ), vec3( 2.2 ) );
}
vec3 RRTAndODTFit( vec3 v ) {
	vec3 a = v * ( v + 0.0245786 ) - 0.000090537;
	vec3 b = v * ( 0.983729 * v + 0.4329510 ) + 0.238081;
	return a / b;
}
vec3 ACESFilmicToneMapping( vec3 color ) {
	const mat3 ACESInputMat = mat3(
		vec3( 0.59719, 0.07600, 0.02840 ),		vec3( 0.35458, 0.90834, 0.13383 ),
		vec3( 0.04823, 0.01566, 0.83777 )
	);
	const mat3 ACESOutputMat = mat3(
		vec3(  1.60475, -0.10208, -0.00327 ),		vec3( -0.53108,  1.10813, -0.07276 ),
		vec3( -0.07367, -0.00605,  1.07602 )
	);
	color *= toneMappingExposure / 0.6;
	color = ACESInputMat * color;
	color = RRTAndODTFit( color );
	color = ACESOutputMat * color;
	return saturate( color );
}
const mat3 LINEAR_REC2020_TO_LINEAR_SRGB = mat3(
	vec3( 1.6605, - 0.1246, - 0.0182 ),
	vec3( - 0.5876, 1.1329, - 0.1006 ),
	vec3( - 0.0728, - 0.0083, 1.1187 )
);
const mat3 LINEAR_SRGB_TO_LINEAR_REC2020 = mat3(
	vec3( 0.6274, 0.0691, 0.0164 ),
	vec3( 0.3293, 0.9195, 0.0880 ),
	vec3( 0.0433, 0.0113, 0.8956 )
);
vec3 agxDefaultContrastApprox( vec3 x ) {
	vec3 x2 = x * x;
	vec3 x4 = x2 * x2;
	return + 15.5 * x4 * x2
		- 40.14 * x4 * x
		+ 31.96 * x4
		- 6.868 * x2 * x
		+ 0.4298 * x2
		+ 0.1191 * x
		- 0.00232;
}
vec3 AgXToneMapping( vec3 color ) {
	const mat3 AgXInsetMatrix = mat3(
		vec3( 0.856627153315983, 0.137318972929847, 0.11189821299995 ),
		vec3( 0.0951212405381588, 0.761241990602591, 0.0767994186031903 ),
		vec3( 0.0482516061458583, 0.101439036467562, 0.811302368396859 )
	);
	const mat3 AgXOutsetMatrix = mat3(
		vec3( 1.1271005818144368, - 0.1413297634984383, - 0.14132976349843826 ),
		vec3( - 0.11060664309660323, 1.157823702216272, - 0.11060664309660294 ),
		vec3( - 0.016493938717834573, - 0.016493938717834257, 1.2519364065950405 )
	);
	const float AgxMinEv = - 12.47393;	const float AgxMaxEv = 4.026069;
	color *= toneMappingExposure;
	color = LINEAR_SRGB_TO_LINEAR_REC2020 * color;
	color = AgXInsetMatrix * color;
	color = max( color, 1e-10 );	color = log2( color );
	color = ( color - AgxMinEv ) / ( AgxMaxEv - AgxMinEv );
	color = clamp( color, 0.0, 1.0 );
	color = agxDefaultContrastApprox( color );
	color = AgXOutsetMatrix * color;
	color = pow( max( vec3( 0.0 ), color ), vec3( 2.2 ) );
	color = LINEAR_REC2020_TO_LINEAR_SRGB * color;
	color = clamp( color, 0.0, 1.0 );
	return color;
}
vec3 NeutralToneMapping( vec3 color ) {
	const float StartCompression = 0.8 - 0.04;
	const float Desaturation = 0.15;
	color *= toneMappingExposure;
	float x = min( color.r, min( color.g, color.b ) );
	float offset = x < 0.08 ? x - 6.25 * x * x : 0.04;
	color -= offset;
	float peak = max( color.r, max( color.g, color.b ) );
	if ( peak < StartCompression ) return color;
	float d = 1. - StartCompression;
	float newPeak = 1. - d * d / ( peak + d - StartCompression );
	color *= newPeak / peak;
	float g = 1. - 1. / ( Desaturation * ( peak - newPeak ) + 1. );
	return mix( color, vec3( newPeak ), g );
}
vec3 CustomToneMapping( vec3 color ) { return color; }`, nb = `#ifdef USE_TRANSMISSION
	material.transmission = transmission;
	material.transmissionAlpha = 1.0;
	material.thickness = thickness;
	material.attenuationDistance = attenuationDistance;
	material.attenuationColor = attenuationColor;
	#ifdef USE_TRANSMISSIONMAP
		material.transmission *= texture2D( transmissionMap, vTransmissionMapUv ).r;
	#endif
	#ifdef USE_THICKNESSMAP
		material.thickness *= texture2D( thicknessMap, vThicknessMapUv ).g;
	#endif
	vec3 pos = vWorldPosition;
	vec3 v = normalize( cameraPosition - pos );
	vec3 n = inverseTransformDirection( normal, viewMatrix );
	vec4 transmitted = getIBLVolumeRefraction(
		n, v, material.roughness, material.diffuseColor, material.specularColor, material.specularF90,
		pos, modelMatrix, viewMatrix, projectionMatrix, material.dispersion, material.ior, material.thickness,
		material.attenuationColor, material.attenuationDistance );
	material.transmissionAlpha = mix( material.transmissionAlpha, transmitted.a, material.transmission );
	totalDiffuse = mix( totalDiffuse, transmitted.rgb, material.transmission );
#endif`, sb = `#ifdef USE_TRANSMISSION
	uniform float transmission;
	uniform float thickness;
	uniform float attenuationDistance;
	uniform vec3 attenuationColor;
	#ifdef USE_TRANSMISSIONMAP
		uniform sampler2D transmissionMap;
	#endif
	#ifdef USE_THICKNESSMAP
		uniform sampler2D thicknessMap;
	#endif
	uniform vec2 transmissionSamplerSize;
	uniform sampler2D transmissionSamplerMap;
	uniform mat4 modelMatrix;
	uniform mat4 projectionMatrix;
	varying vec3 vWorldPosition;
	float w0( float a ) {
		return ( 1.0 / 6.0 ) * ( a * ( a * ( - a + 3.0 ) - 3.0 ) + 1.0 );
	}
	float w1( float a ) {
		return ( 1.0 / 6.0 ) * ( a *  a * ( 3.0 * a - 6.0 ) + 4.0 );
	}
	float w2( float a ){
		return ( 1.0 / 6.0 ) * ( a * ( a * ( - 3.0 * a + 3.0 ) + 3.0 ) + 1.0 );
	}
	float w3( float a ) {
		return ( 1.0 / 6.0 ) * ( a * a * a );
	}
	float g0( float a ) {
		return w0( a ) + w1( a );
	}
	float g1( float a ) {
		return w2( a ) + w3( a );
	}
	float h0( float a ) {
		return - 1.0 + w1( a ) / ( w0( a ) + w1( a ) );
	}
	float h1( float a ) {
		return 1.0 + w3( a ) / ( w2( a ) + w3( a ) );
	}
	vec4 bicubic( sampler2D tex, vec2 uv, vec4 texelSize, float lod ) {
		uv = uv * texelSize.zw + 0.5;
		vec2 iuv = floor( uv );
		vec2 fuv = fract( uv );
		float g0x = g0( fuv.x );
		float g1x = g1( fuv.x );
		float h0x = h0( fuv.x );
		float h1x = h1( fuv.x );
		float h0y = h0( fuv.y );
		float h1y = h1( fuv.y );
		vec2 p0 = ( vec2( iuv.x + h0x, iuv.y + h0y ) - 0.5 ) * texelSize.xy;
		vec2 p1 = ( vec2( iuv.x + h1x, iuv.y + h0y ) - 0.5 ) * texelSize.xy;
		vec2 p2 = ( vec2( iuv.x + h0x, iuv.y + h1y ) - 0.5 ) * texelSize.xy;
		vec2 p3 = ( vec2( iuv.x + h1x, iuv.y + h1y ) - 0.5 ) * texelSize.xy;
		return g0( fuv.y ) * ( g0x * textureLod( tex, p0, lod ) + g1x * textureLod( tex, p1, lod ) ) +
			g1( fuv.y ) * ( g0x * textureLod( tex, p2, lod ) + g1x * textureLod( tex, p3, lod ) );
	}
	vec4 textureBicubic( sampler2D sampler, vec2 uv, float lod ) {
		vec2 fLodSize = vec2( textureSize( sampler, int( lod ) ) );
		vec2 cLodSize = vec2( textureSize( sampler, int( lod + 1.0 ) ) );
		vec2 fLodSizeInv = 1.0 / fLodSize;
		vec2 cLodSizeInv = 1.0 / cLodSize;
		vec4 fSample = bicubic( sampler, uv, vec4( fLodSizeInv, fLodSize ), floor( lod ) );
		vec4 cSample = bicubic( sampler, uv, vec4( cLodSizeInv, cLodSize ), ceil( lod ) );
		return mix( fSample, cSample, fract( lod ) );
	}
	vec3 getVolumeTransmissionRay( const in vec3 n, const in vec3 v, const in float thickness, const in float ior, const in mat4 modelMatrix ) {
		vec3 refractionVector = refract( - v, normalize( n ), 1.0 / ior );
		vec3 modelScale;
		modelScale.x = length( vec3( modelMatrix[ 0 ].xyz ) );
		modelScale.y = length( vec3( modelMatrix[ 1 ].xyz ) );
		modelScale.z = length( vec3( modelMatrix[ 2 ].xyz ) );
		return normalize( refractionVector ) * thickness * modelScale;
	}
	float applyIorToRoughness( const in float roughness, const in float ior ) {
		return roughness * clamp( ior * 2.0 - 2.0, 0.0, 1.0 );
	}
	vec4 getTransmissionSample( const in vec2 fragCoord, const in float roughness, const in float ior ) {
		float lod = log2( transmissionSamplerSize.x ) * applyIorToRoughness( roughness, ior );
		return textureBicubic( transmissionSamplerMap, fragCoord.xy, lod );
	}
	vec3 volumeAttenuation( const in float transmissionDistance, const in vec3 attenuationColor, const in float attenuationDistance ) {
		if ( isinf( attenuationDistance ) ) {
			return vec3( 1.0 );
		} else {
			vec3 attenuationCoefficient = -log( attenuationColor ) / attenuationDistance;
			vec3 transmittance = exp( - attenuationCoefficient * transmissionDistance );			return transmittance;
		}
	}
	vec4 getIBLVolumeRefraction( const in vec3 n, const in vec3 v, const in float roughness, const in vec3 diffuseColor,
		const in vec3 specularColor, const in float specularF90, const in vec3 position, const in mat4 modelMatrix,
		const in mat4 viewMatrix, const in mat4 projMatrix, const in float dispersion, const in float ior, const in float thickness,
		const in vec3 attenuationColor, const in float attenuationDistance ) {
		vec4 transmittedLight;
		vec3 transmittance;
		#ifdef USE_DISPERSION
			float halfSpread = ( ior - 1.0 ) * 0.025 * dispersion;
			vec3 iors = vec3( ior - halfSpread, ior, ior + halfSpread );
			for ( int i = 0; i < 3; i ++ ) {
				vec3 transmissionRay = getVolumeTransmissionRay( n, v, thickness, iors[ i ], modelMatrix );
				vec3 refractedRayExit = position + transmissionRay;
				vec4 ndcPos = projMatrix * viewMatrix * vec4( refractedRayExit, 1.0 );
				vec2 refractionCoords = ndcPos.xy / ndcPos.w;
				refractionCoords += 1.0;
				refractionCoords /= 2.0;
				vec4 transmissionSample = getTransmissionSample( refractionCoords, roughness, iors[ i ] );
				transmittedLight[ i ] = transmissionSample[ i ];
				transmittedLight.a += transmissionSample.a;
				transmittance[ i ] = diffuseColor[ i ] * volumeAttenuation( length( transmissionRay ), attenuationColor, attenuationDistance )[ i ];
			}
			transmittedLight.a /= 3.0;
		#else
			vec3 transmissionRay = getVolumeTransmissionRay( n, v, thickness, ior, modelMatrix );
			vec3 refractedRayExit = position + transmissionRay;
			vec4 ndcPos = projMatrix * viewMatrix * vec4( refractedRayExit, 1.0 );
			vec2 refractionCoords = ndcPos.xy / ndcPos.w;
			refractionCoords += 1.0;
			refractionCoords /= 2.0;
			transmittedLight = getTransmissionSample( refractionCoords, roughness, ior );
			transmittance = diffuseColor * volumeAttenuation( length( transmissionRay ), attenuationColor, attenuationDistance );
		#endif
		vec3 attenuatedColor = transmittance * transmittedLight.rgb;
		vec3 F = EnvironmentBRDF( n, v, specularColor, specularF90, roughness );
		float transmittanceFactor = ( transmittance.r + transmittance.g + transmittance.b ) / 3.0;
		return vec4( ( 1.0 - F ) * attenuatedColor, 1.0 - ( 1.0 - transmittedLight.a ) * transmittanceFactor );
	}
#endif`, rb = `#if defined( USE_UV ) || defined( USE_ANISOTROPY )
	varying vec2 vUv;
#endif
#ifdef USE_MAP
	varying vec2 vMapUv;
#endif
#ifdef USE_ALPHAMAP
	varying vec2 vAlphaMapUv;
#endif
#ifdef USE_LIGHTMAP
	varying vec2 vLightMapUv;
#endif
#ifdef USE_AOMAP
	varying vec2 vAoMapUv;
#endif
#ifdef USE_BUMPMAP
	varying vec2 vBumpMapUv;
#endif
#ifdef USE_NORMALMAP
	varying vec2 vNormalMapUv;
#endif
#ifdef USE_EMISSIVEMAP
	varying vec2 vEmissiveMapUv;
#endif
#ifdef USE_METALNESSMAP
	varying vec2 vMetalnessMapUv;
#endif
#ifdef USE_ROUGHNESSMAP
	varying vec2 vRoughnessMapUv;
#endif
#ifdef USE_ANISOTROPYMAP
	varying vec2 vAnisotropyMapUv;
#endif
#ifdef USE_CLEARCOATMAP
	varying vec2 vClearcoatMapUv;
#endif
#ifdef USE_CLEARCOAT_NORMALMAP
	varying vec2 vClearcoatNormalMapUv;
#endif
#ifdef USE_CLEARCOAT_ROUGHNESSMAP
	varying vec2 vClearcoatRoughnessMapUv;
#endif
#ifdef USE_IRIDESCENCEMAP
	varying vec2 vIridescenceMapUv;
#endif
#ifdef USE_IRIDESCENCE_THICKNESSMAP
	varying vec2 vIridescenceThicknessMapUv;
#endif
#ifdef USE_SHEEN_COLORMAP
	varying vec2 vSheenColorMapUv;
#endif
#ifdef USE_SHEEN_ROUGHNESSMAP
	varying vec2 vSheenRoughnessMapUv;
#endif
#ifdef USE_SPECULARMAP
	varying vec2 vSpecularMapUv;
#endif
#ifdef USE_SPECULAR_COLORMAP
	varying vec2 vSpecularColorMapUv;
#endif
#ifdef USE_SPECULAR_INTENSITYMAP
	varying vec2 vSpecularIntensityMapUv;
#endif
#ifdef USE_TRANSMISSIONMAP
	uniform mat3 transmissionMapTransform;
	varying vec2 vTransmissionMapUv;
#endif
#ifdef USE_THICKNESSMAP
	uniform mat3 thicknessMapTransform;
	varying vec2 vThicknessMapUv;
#endif`, ab = `#if defined( USE_UV ) || defined( USE_ANISOTROPY )
	varying vec2 vUv;
#endif
#ifdef USE_MAP
	uniform mat3 mapTransform;
	varying vec2 vMapUv;
#endif
#ifdef USE_ALPHAMAP
	uniform mat3 alphaMapTransform;
	varying vec2 vAlphaMapUv;
#endif
#ifdef USE_LIGHTMAP
	uniform mat3 lightMapTransform;
	varying vec2 vLightMapUv;
#endif
#ifdef USE_AOMAP
	uniform mat3 aoMapTransform;
	varying vec2 vAoMapUv;
#endif
#ifdef USE_BUMPMAP
	uniform mat3 bumpMapTransform;
	varying vec2 vBumpMapUv;
#endif
#ifdef USE_NORMALMAP
	uniform mat3 normalMapTransform;
	varying vec2 vNormalMapUv;
#endif
#ifdef USE_DISPLACEMENTMAP
	uniform mat3 displacementMapTransform;
	varying vec2 vDisplacementMapUv;
#endif
#ifdef USE_EMISSIVEMAP
	uniform mat3 emissiveMapTransform;
	varying vec2 vEmissiveMapUv;
#endif
#ifdef USE_METALNESSMAP
	uniform mat3 metalnessMapTransform;
	varying vec2 vMetalnessMapUv;
#endif
#ifdef USE_ROUGHNESSMAP
	uniform mat3 roughnessMapTransform;
	varying vec2 vRoughnessMapUv;
#endif
#ifdef USE_ANISOTROPYMAP
	uniform mat3 anisotropyMapTransform;
	varying vec2 vAnisotropyMapUv;
#endif
#ifdef USE_CLEARCOATMAP
	uniform mat3 clearcoatMapTransform;
	varying vec2 vClearcoatMapUv;
#endif
#ifdef USE_CLEARCOAT_NORMALMAP
	uniform mat3 clearcoatNormalMapTransform;
	varying vec2 vClearcoatNormalMapUv;
#endif
#ifdef USE_CLEARCOAT_ROUGHNESSMAP
	uniform mat3 clearcoatRoughnessMapTransform;
	varying vec2 vClearcoatRoughnessMapUv;
#endif
#ifdef USE_SHEEN_COLORMAP
	uniform mat3 sheenColorMapTransform;
	varying vec2 vSheenColorMapUv;
#endif
#ifdef USE_SHEEN_ROUGHNESSMAP
	uniform mat3 sheenRoughnessMapTransform;
	varying vec2 vSheenRoughnessMapUv;
#endif
#ifdef USE_IRIDESCENCEMAP
	uniform mat3 iridescenceMapTransform;
	varying vec2 vIridescenceMapUv;
#endif
#ifdef USE_IRIDESCENCE_THICKNESSMAP
	uniform mat3 iridescenceThicknessMapTransform;
	varying vec2 vIridescenceThicknessMapUv;
#endif
#ifdef USE_SPECULARMAP
	uniform mat3 specularMapTransform;
	varying vec2 vSpecularMapUv;
#endif
#ifdef USE_SPECULAR_COLORMAP
	uniform mat3 specularColorMapTransform;
	varying vec2 vSpecularColorMapUv;
#endif
#ifdef USE_SPECULAR_INTENSITYMAP
	uniform mat3 specularIntensityMapTransform;
	varying vec2 vSpecularIntensityMapUv;
#endif
#ifdef USE_TRANSMISSIONMAP
	uniform mat3 transmissionMapTransform;
	varying vec2 vTransmissionMapUv;
#endif
#ifdef USE_THICKNESSMAP
	uniform mat3 thicknessMapTransform;
	varying vec2 vThicknessMapUv;
#endif`, ob = `#if defined( USE_UV ) || defined( USE_ANISOTROPY )
	vUv = vec3( uv, 1 ).xy;
#endif
#ifdef USE_MAP
	vMapUv = ( mapTransform * vec3( MAP_UV, 1 ) ).xy;
#endif
#ifdef USE_ALPHAMAP
	vAlphaMapUv = ( alphaMapTransform * vec3( ALPHAMAP_UV, 1 ) ).xy;
#endif
#ifdef USE_LIGHTMAP
	vLightMapUv = ( lightMapTransform * vec3( LIGHTMAP_UV, 1 ) ).xy;
#endif
#ifdef USE_AOMAP
	vAoMapUv = ( aoMapTransform * vec3( AOMAP_UV, 1 ) ).xy;
#endif
#ifdef USE_BUMPMAP
	vBumpMapUv = ( bumpMapTransform * vec3( BUMPMAP_UV, 1 ) ).xy;
#endif
#ifdef USE_NORMALMAP
	vNormalMapUv = ( normalMapTransform * vec3( NORMALMAP_UV, 1 ) ).xy;
#endif
#ifdef USE_DISPLACEMENTMAP
	vDisplacementMapUv = ( displacementMapTransform * vec3( DISPLACEMENTMAP_UV, 1 ) ).xy;
#endif
#ifdef USE_EMISSIVEMAP
	vEmissiveMapUv = ( emissiveMapTransform * vec3( EMISSIVEMAP_UV, 1 ) ).xy;
#endif
#ifdef USE_METALNESSMAP
	vMetalnessMapUv = ( metalnessMapTransform * vec3( METALNESSMAP_UV, 1 ) ).xy;
#endif
#ifdef USE_ROUGHNESSMAP
	vRoughnessMapUv = ( roughnessMapTransform * vec3( ROUGHNESSMAP_UV, 1 ) ).xy;
#endif
#ifdef USE_ANISOTROPYMAP
	vAnisotropyMapUv = ( anisotropyMapTransform * vec3( ANISOTROPYMAP_UV, 1 ) ).xy;
#endif
#ifdef USE_CLEARCOATMAP
	vClearcoatMapUv = ( clearcoatMapTransform * vec3( CLEARCOATMAP_UV, 1 ) ).xy;
#endif
#ifdef USE_CLEARCOAT_NORMALMAP
	vClearcoatNormalMapUv = ( clearcoatNormalMapTransform * vec3( CLEARCOAT_NORMALMAP_UV, 1 ) ).xy;
#endif
#ifdef USE_CLEARCOAT_ROUGHNESSMAP
	vClearcoatRoughnessMapUv = ( clearcoatRoughnessMapTransform * vec3( CLEARCOAT_ROUGHNESSMAP_UV, 1 ) ).xy;
#endif
#ifdef USE_IRIDESCENCEMAP
	vIridescenceMapUv = ( iridescenceMapTransform * vec3( IRIDESCENCEMAP_UV, 1 ) ).xy;
#endif
#ifdef USE_IRIDESCENCE_THICKNESSMAP
	vIridescenceThicknessMapUv = ( iridescenceThicknessMapTransform * vec3( IRIDESCENCE_THICKNESSMAP_UV, 1 ) ).xy;
#endif
#ifdef USE_SHEEN_COLORMAP
	vSheenColorMapUv = ( sheenColorMapTransform * vec3( SHEEN_COLORMAP_UV, 1 ) ).xy;
#endif
#ifdef USE_SHEEN_ROUGHNESSMAP
	vSheenRoughnessMapUv = ( sheenRoughnessMapTransform * vec3( SHEEN_ROUGHNESSMAP_UV, 1 ) ).xy;
#endif
#ifdef USE_SPECULARMAP
	vSpecularMapUv = ( specularMapTransform * vec3( SPECULARMAP_UV, 1 ) ).xy;
#endif
#ifdef USE_SPECULAR_COLORMAP
	vSpecularColorMapUv = ( specularColorMapTransform * vec3( SPECULAR_COLORMAP_UV, 1 ) ).xy;
#endif
#ifdef USE_SPECULAR_INTENSITYMAP
	vSpecularIntensityMapUv = ( specularIntensityMapTransform * vec3( SPECULAR_INTENSITYMAP_UV, 1 ) ).xy;
#endif
#ifdef USE_TRANSMISSIONMAP
	vTransmissionMapUv = ( transmissionMapTransform * vec3( TRANSMISSIONMAP_UV, 1 ) ).xy;
#endif
#ifdef USE_THICKNESSMAP
	vThicknessMapUv = ( thicknessMapTransform * vec3( THICKNESSMAP_UV, 1 ) ).xy;
#endif`, lb = `#if defined( USE_ENVMAP ) || defined( DISTANCE ) || defined ( USE_SHADOWMAP ) || defined ( USE_TRANSMISSION ) || NUM_SPOT_LIGHT_COORDS > 0
	vec4 worldPosition = vec4( transformed, 1.0 );
	#ifdef USE_BATCHING
		worldPosition = batchingMatrix * worldPosition;
	#endif
	#ifdef USE_INSTANCING
		worldPosition = instanceMatrix * worldPosition;
	#endif
	worldPosition = modelMatrix * worldPosition;
#endif`;
const cb = `varying vec2 vUv;
uniform mat3 uvTransform;
void main() {
	vUv = ( uvTransform * vec3( uv, 1 ) ).xy;
	gl_Position = vec4( position.xy, 1.0, 1.0 );
}`, hb = `uniform sampler2D t2D;
uniform float backgroundIntensity;
varying vec2 vUv;
void main() {
	vec4 texColor = texture2D( t2D, vUv );
	#ifdef DECODE_VIDEO_TEXTURE
		texColor = vec4( mix( pow( texColor.rgb * 0.9478672986 + vec3( 0.0521327014 ), vec3( 2.4 ) ), texColor.rgb * 0.0773993808, vec3( lessThanEqual( texColor.rgb, vec3( 0.04045 ) ) ) ), texColor.w );
	#endif
	texColor.rgb *= backgroundIntensity;
	gl_FragColor = texColor;
	#include <tonemapping_fragment>
	#include <colorspace_fragment>
}`, db = `varying vec3 vWorldDirection;
#include <common>
void main() {
	vWorldDirection = transformDirection( position, modelMatrix );
	#include <begin_vertex>
	#include <project_vertex>
	gl_Position.z = gl_Position.w;
}`, ub = `#ifdef ENVMAP_TYPE_CUBE
	uniform samplerCube envMap;
#elif defined( ENVMAP_TYPE_CUBE_UV )
	uniform sampler2D envMap;
#endif
uniform float flipEnvMap;
uniform float backgroundBlurriness;
uniform float backgroundIntensity;
uniform mat3 backgroundRotation;
varying vec3 vWorldDirection;
#include <cube_uv_reflection_fragment>
void main() {
	#ifdef ENVMAP_TYPE_CUBE
		vec4 texColor = textureCube( envMap, backgroundRotation * vec3( flipEnvMap * vWorldDirection.x, vWorldDirection.yz ) );
	#elif defined( ENVMAP_TYPE_CUBE_UV )
		vec4 texColor = textureCubeUV( envMap, backgroundRotation * vWorldDirection, backgroundBlurriness );
	#else
		vec4 texColor = vec4( 0.0, 0.0, 0.0, 1.0 );
	#endif
	texColor.rgb *= backgroundIntensity;
	gl_FragColor = texColor;
	#include <tonemapping_fragment>
	#include <colorspace_fragment>
}`, pb = `varying vec3 vWorldDirection;
#include <common>
void main() {
	vWorldDirection = transformDirection( position, modelMatrix );
	#include <begin_vertex>
	#include <project_vertex>
	gl_Position.z = gl_Position.w;
}`, fb = `uniform samplerCube tCube;
uniform float tFlip;
uniform float opacity;
varying vec3 vWorldDirection;
void main() {
	vec4 texColor = textureCube( tCube, vec3( tFlip * vWorldDirection.x, vWorldDirection.yz ) );
	gl_FragColor = texColor;
	gl_FragColor.a *= opacity;
	#include <tonemapping_fragment>
	#include <colorspace_fragment>
}`, mb = `#include <common>
#include <batching_pars_vertex>
#include <uv_pars_vertex>
#include <displacementmap_pars_vertex>
#include <morphtarget_pars_vertex>
#include <skinning_pars_vertex>
#include <logdepthbuf_pars_vertex>
#include <clipping_planes_pars_vertex>
varying vec2 vHighPrecisionZW;
void main() {
	#include <uv_vertex>
	#include <batching_vertex>
	#include <skinbase_vertex>
	#include <morphinstance_vertex>
	#ifdef USE_DISPLACEMENTMAP
		#include <beginnormal_vertex>
		#include <morphnormal_vertex>
		#include <skinnormal_vertex>
	#endif
	#include <begin_vertex>
	#include <morphtarget_vertex>
	#include <skinning_vertex>
	#include <displacementmap_vertex>
	#include <project_vertex>
	#include <logdepthbuf_vertex>
	#include <clipping_planes_vertex>
	vHighPrecisionZW = gl_Position.zw;
}`, gb = `#if DEPTH_PACKING == 3200
	uniform float opacity;
#endif
#include <common>
#include <packing>
#include <uv_pars_fragment>
#include <map_pars_fragment>
#include <alphamap_pars_fragment>
#include <alphatest_pars_fragment>
#include <alphahash_pars_fragment>
#include <logdepthbuf_pars_fragment>
#include <clipping_planes_pars_fragment>
varying vec2 vHighPrecisionZW;
void main() {
	vec4 diffuseColor = vec4( 1.0 );
	#include <clipping_planes_fragment>
	#if DEPTH_PACKING == 3200
		diffuseColor.a = opacity;
	#endif
	#include <map_fragment>
	#include <alphamap_fragment>
	#include <alphatest_fragment>
	#include <alphahash_fragment>
	#include <logdepthbuf_fragment>
	#ifdef USE_REVERSED_DEPTH_BUFFER
		float fragCoordZ = vHighPrecisionZW[ 0 ] / vHighPrecisionZW[ 1 ];
	#else
		float fragCoordZ = 0.5 * vHighPrecisionZW[ 0 ] / vHighPrecisionZW[ 1 ] + 0.5;
	#endif
	#if DEPTH_PACKING == 3200
		gl_FragColor = vec4( vec3( 1.0 - fragCoordZ ), opacity );
	#elif DEPTH_PACKING == 3201
		gl_FragColor = packDepthToRGBA( fragCoordZ );
	#elif DEPTH_PACKING == 3202
		gl_FragColor = vec4( packDepthToRGB( fragCoordZ ), 1.0 );
	#elif DEPTH_PACKING == 3203
		gl_FragColor = vec4( packDepthToRG( fragCoordZ ), 0.0, 1.0 );
	#endif
}`, _b = `#define DISTANCE
varying vec3 vWorldPosition;
#include <common>
#include <batching_pars_vertex>
#include <uv_pars_vertex>
#include <displacementmap_pars_vertex>
#include <morphtarget_pars_vertex>
#include <skinning_pars_vertex>
#include <clipping_planes_pars_vertex>
void main() {
	#include <uv_vertex>
	#include <batching_vertex>
	#include <skinbase_vertex>
	#include <morphinstance_vertex>
	#ifdef USE_DISPLACEMENTMAP
		#include <beginnormal_vertex>
		#include <morphnormal_vertex>
		#include <skinnormal_vertex>
	#endif
	#include <begin_vertex>
	#include <morphtarget_vertex>
	#include <skinning_vertex>
	#include <displacementmap_vertex>
	#include <project_vertex>
	#include <worldpos_vertex>
	#include <clipping_planes_vertex>
	vWorldPosition = worldPosition.xyz;
}`, yb = `#define DISTANCE
uniform vec3 referencePosition;
uniform float nearDistance;
uniform float farDistance;
varying vec3 vWorldPosition;
#include <common>
#include <packing>
#include <uv_pars_fragment>
#include <map_pars_fragment>
#include <alphamap_pars_fragment>
#include <alphatest_pars_fragment>
#include <alphahash_pars_fragment>
#include <clipping_planes_pars_fragment>
void main () {
	vec4 diffuseColor = vec4( 1.0 );
	#include <clipping_planes_fragment>
	#include <map_fragment>
	#include <alphamap_fragment>
	#include <alphatest_fragment>
	#include <alphahash_fragment>
	float dist = length( vWorldPosition - referencePosition );
	dist = ( dist - nearDistance ) / ( farDistance - nearDistance );
	dist = saturate( dist );
	gl_FragColor = packDepthToRGBA( dist );
}`, vb = `varying vec3 vWorldDirection;
#include <common>
void main() {
	vWorldDirection = transformDirection( position, modelMatrix );
	#include <begin_vertex>
	#include <project_vertex>
}`, xb = `uniform sampler2D tEquirect;
varying vec3 vWorldDirection;
#include <common>
void main() {
	vec3 direction = normalize( vWorldDirection );
	vec2 sampleUV = equirectUv( direction );
	gl_FragColor = texture2D( tEquirect, sampleUV );
	#include <tonemapping_fragment>
	#include <colorspace_fragment>
}`, bb = `uniform float scale;
attribute float lineDistance;
varying float vLineDistance;
#include <common>
#include <uv_pars_vertex>
#include <color_pars_vertex>
#include <fog_pars_vertex>
#include <morphtarget_pars_vertex>
#include <logdepthbuf_pars_vertex>
#include <clipping_planes_pars_vertex>
void main() {
	vLineDistance = scale * lineDistance;
	#include <uv_vertex>
	#include <color_vertex>
	#include <morphinstance_vertex>
	#include <morphcolor_vertex>
	#include <begin_vertex>
	#include <morphtarget_vertex>
	#include <project_vertex>
	#include <logdepthbuf_vertex>
	#include <clipping_planes_vertex>
	#include <fog_vertex>
}`, Sb = `uniform vec3 diffuse;
uniform float opacity;
uniform float dashSize;
uniform float totalSize;
varying float vLineDistance;
#include <common>
#include <color_pars_fragment>
#include <uv_pars_fragment>
#include <map_pars_fragment>
#include <fog_pars_fragment>
#include <logdepthbuf_pars_fragment>
#include <clipping_planes_pars_fragment>
void main() {
	vec4 diffuseColor = vec4( diffuse, opacity );
	#include <clipping_planes_fragment>
	if ( mod( vLineDistance, totalSize ) > dashSize ) {
		discard;
	}
	vec3 outgoingLight = vec3( 0.0 );
	#include <logdepthbuf_fragment>
	#include <map_fragment>
	#include <color_fragment>
	outgoingLight = diffuseColor.rgb;
	#include <opaque_fragment>
	#include <tonemapping_fragment>
	#include <colorspace_fragment>
	#include <fog_fragment>
	#include <premultiplied_alpha_fragment>
}`, Mb = `#include <common>
#include <batching_pars_vertex>
#include <uv_pars_vertex>
#include <envmap_pars_vertex>
#include <color_pars_vertex>
#include <fog_pars_vertex>
#include <morphtarget_pars_vertex>
#include <skinning_pars_vertex>
#include <logdepthbuf_pars_vertex>
#include <clipping_planes_pars_vertex>
void main() {
	#include <uv_vertex>
	#include <color_vertex>
	#include <morphinstance_vertex>
	#include <morphcolor_vertex>
	#include <batching_vertex>
	#if defined ( USE_ENVMAP ) || defined ( USE_SKINNING )
		#include <beginnormal_vertex>
		#include <morphnormal_vertex>
		#include <skinbase_vertex>
		#include <skinnormal_vertex>
		#include <defaultnormal_vertex>
	#endif
	#include <begin_vertex>
	#include <morphtarget_vertex>
	#include <skinning_vertex>
	#include <project_vertex>
	#include <logdepthbuf_vertex>
	#include <clipping_planes_vertex>
	#include <worldpos_vertex>
	#include <envmap_vertex>
	#include <fog_vertex>
}`, wb = `uniform vec3 diffuse;
uniform float opacity;
#ifndef FLAT_SHADED
	varying vec3 vNormal;
#endif
#include <common>
#include <dithering_pars_fragment>
#include <color_pars_fragment>
#include <uv_pars_fragment>
#include <map_pars_fragment>
#include <alphamap_pars_fragment>
#include <alphatest_pars_fragment>
#include <alphahash_pars_fragment>
#include <aomap_pars_fragment>
#include <lightmap_pars_fragment>
#include <envmap_common_pars_fragment>
#include <envmap_pars_fragment>
#include <fog_pars_fragment>
#include <specularmap_pars_fragment>
#include <logdepthbuf_pars_fragment>
#include <clipping_planes_pars_fragment>
void main() {
	vec4 diffuseColor = vec4( diffuse, opacity );
	#include <clipping_planes_fragment>
	#include <logdepthbuf_fragment>
	#include <map_fragment>
	#include <color_fragment>
	#include <alphamap_fragment>
	#include <alphatest_fragment>
	#include <alphahash_fragment>
	#include <specularmap_fragment>
	ReflectedLight reflectedLight = ReflectedLight( vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ) );
	#ifdef USE_LIGHTMAP
		vec4 lightMapTexel = texture2D( lightMap, vLightMapUv );
		reflectedLight.indirectDiffuse += lightMapTexel.rgb * lightMapIntensity * RECIPROCAL_PI;
	#else
		reflectedLight.indirectDiffuse += vec3( 1.0 );
	#endif
	#include <aomap_fragment>
	reflectedLight.indirectDiffuse *= diffuseColor.rgb;
	vec3 outgoingLight = reflectedLight.indirectDiffuse;
	#include <envmap_fragment>
	#include <opaque_fragment>
	#include <tonemapping_fragment>
	#include <colorspace_fragment>
	#include <fog_fragment>
	#include <premultiplied_alpha_fragment>
	#include <dithering_fragment>
}`, Eb = `#define LAMBERT
varying vec3 vViewPosition;
#include <common>
#include <batching_pars_vertex>
#include <uv_pars_vertex>
#include <displacementmap_pars_vertex>
#include <envmap_pars_vertex>
#include <color_pars_vertex>
#include <fog_pars_vertex>
#include <normal_pars_vertex>
#include <morphtarget_pars_vertex>
#include <skinning_pars_vertex>
#include <shadowmap_pars_vertex>
#include <logdepthbuf_pars_vertex>
#include <clipping_planes_pars_vertex>
void main() {
	#include <uv_vertex>
	#include <color_vertex>
	#include <morphinstance_vertex>
	#include <morphcolor_vertex>
	#include <batching_vertex>
	#include <beginnormal_vertex>
	#include <morphnormal_vertex>
	#include <skinbase_vertex>
	#include <skinnormal_vertex>
	#include <defaultnormal_vertex>
	#include <normal_vertex>
	#include <begin_vertex>
	#include <morphtarget_vertex>
	#include <skinning_vertex>
	#include <displacementmap_vertex>
	#include <project_vertex>
	#include <logdepthbuf_vertex>
	#include <clipping_planes_vertex>
	vViewPosition = - mvPosition.xyz;
	#include <worldpos_vertex>
	#include <envmap_vertex>
	#include <shadowmap_vertex>
	#include <fog_vertex>
}`, Tb = `#define LAMBERT
uniform vec3 diffuse;
uniform vec3 emissive;
uniform float opacity;
#include <common>
#include <packing>
#include <dithering_pars_fragment>
#include <color_pars_fragment>
#include <uv_pars_fragment>
#include <map_pars_fragment>
#include <alphamap_pars_fragment>
#include <alphatest_pars_fragment>
#include <alphahash_pars_fragment>
#include <aomap_pars_fragment>
#include <lightmap_pars_fragment>
#include <emissivemap_pars_fragment>
#include <envmap_common_pars_fragment>
#include <envmap_pars_fragment>
#include <fog_pars_fragment>
#include <bsdfs>
#include <lights_pars_begin>
#include <normal_pars_fragment>
#include <lights_lambert_pars_fragment>
#include <shadowmap_pars_fragment>
#include <bumpmap_pars_fragment>
#include <normalmap_pars_fragment>
#include <specularmap_pars_fragment>
#include <logdepthbuf_pars_fragment>
#include <clipping_planes_pars_fragment>
void main() {
	vec4 diffuseColor = vec4( diffuse, opacity );
	#include <clipping_planes_fragment>
	ReflectedLight reflectedLight = ReflectedLight( vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ) );
	vec3 totalEmissiveRadiance = emissive;
	#include <logdepthbuf_fragment>
	#include <map_fragment>
	#include <color_fragment>
	#include <alphamap_fragment>
	#include <alphatest_fragment>
	#include <alphahash_fragment>
	#include <specularmap_fragment>
	#include <normal_fragment_begin>
	#include <normal_fragment_maps>
	#include <emissivemap_fragment>
	#include <lights_lambert_fragment>
	#include <lights_fragment_begin>
	#include <lights_fragment_maps>
	#include <lights_fragment_end>
	#include <aomap_fragment>
	vec3 outgoingLight = reflectedLight.directDiffuse + reflectedLight.indirectDiffuse + totalEmissiveRadiance;
	#include <envmap_fragment>
	#include <opaque_fragment>
	#include <tonemapping_fragment>
	#include <colorspace_fragment>
	#include <fog_fragment>
	#include <premultiplied_alpha_fragment>
	#include <dithering_fragment>
}`, Ab = `#define MATCAP
varying vec3 vViewPosition;
#include <common>
#include <batching_pars_vertex>
#include <uv_pars_vertex>
#include <color_pars_vertex>
#include <displacementmap_pars_vertex>
#include <fog_pars_vertex>
#include <normal_pars_vertex>
#include <morphtarget_pars_vertex>
#include <skinning_pars_vertex>
#include <logdepthbuf_pars_vertex>
#include <clipping_planes_pars_vertex>
void main() {
	#include <uv_vertex>
	#include <color_vertex>
	#include <morphinstance_vertex>
	#include <morphcolor_vertex>
	#include <batching_vertex>
	#include <beginnormal_vertex>
	#include <morphnormal_vertex>
	#include <skinbase_vertex>
	#include <skinnormal_vertex>
	#include <defaultnormal_vertex>
	#include <normal_vertex>
	#include <begin_vertex>
	#include <morphtarget_vertex>
	#include <skinning_vertex>
	#include <displacementmap_vertex>
	#include <project_vertex>
	#include <logdepthbuf_vertex>
	#include <clipping_planes_vertex>
	#include <fog_vertex>
	vViewPosition = - mvPosition.xyz;
}`, Cb = `#define MATCAP
uniform vec3 diffuse;
uniform float opacity;
uniform sampler2D matcap;
varying vec3 vViewPosition;
#include <common>
#include <dithering_pars_fragment>
#include <color_pars_fragment>
#include <uv_pars_fragment>
#include <map_pars_fragment>
#include <alphamap_pars_fragment>
#include <alphatest_pars_fragment>
#include <alphahash_pars_fragment>
#include <fog_pars_fragment>
#include <normal_pars_fragment>
#include <bumpmap_pars_fragment>
#include <normalmap_pars_fragment>
#include <logdepthbuf_pars_fragment>
#include <clipping_planes_pars_fragment>
void main() {
	vec4 diffuseColor = vec4( diffuse, opacity );
	#include <clipping_planes_fragment>
	#include <logdepthbuf_fragment>
	#include <map_fragment>
	#include <color_fragment>
	#include <alphamap_fragment>
	#include <alphatest_fragment>
	#include <alphahash_fragment>
	#include <normal_fragment_begin>
	#include <normal_fragment_maps>
	vec3 viewDir = normalize( vViewPosition );
	vec3 x = normalize( vec3( viewDir.z, 0.0, - viewDir.x ) );
	vec3 y = cross( viewDir, x );
	vec2 uv = vec2( dot( x, normal ), dot( y, normal ) ) * 0.495 + 0.5;
	#ifdef USE_MATCAP
		vec4 matcapColor = texture2D( matcap, uv );
	#else
		vec4 matcapColor = vec4( vec3( mix( 0.2, 0.8, uv.y ) ), 1.0 );
	#endif
	vec3 outgoingLight = diffuseColor.rgb * matcapColor.rgb;
	#include <opaque_fragment>
	#include <tonemapping_fragment>
	#include <colorspace_fragment>
	#include <fog_fragment>
	#include <premultiplied_alpha_fragment>
	#include <dithering_fragment>
}`, Rb = `#define NORMAL
#if defined( FLAT_SHADED ) || defined( USE_BUMPMAP ) || defined( USE_NORMALMAP_TANGENTSPACE )
	varying vec3 vViewPosition;
#endif
#include <common>
#include <batching_pars_vertex>
#include <uv_pars_vertex>
#include <displacementmap_pars_vertex>
#include <normal_pars_vertex>
#include <morphtarget_pars_vertex>
#include <skinning_pars_vertex>
#include <logdepthbuf_pars_vertex>
#include <clipping_planes_pars_vertex>
void main() {
	#include <uv_vertex>
	#include <batching_vertex>
	#include <beginnormal_vertex>
	#include <morphinstance_vertex>
	#include <morphnormal_vertex>
	#include <skinbase_vertex>
	#include <skinnormal_vertex>
	#include <defaultnormal_vertex>
	#include <normal_vertex>
	#include <begin_vertex>
	#include <morphtarget_vertex>
	#include <skinning_vertex>
	#include <displacementmap_vertex>
	#include <project_vertex>
	#include <logdepthbuf_vertex>
	#include <clipping_planes_vertex>
#if defined( FLAT_SHADED ) || defined( USE_BUMPMAP ) || defined( USE_NORMALMAP_TANGENTSPACE )
	vViewPosition = - mvPosition.xyz;
#endif
}`, Pb = `#define NORMAL
uniform float opacity;
#if defined( FLAT_SHADED ) || defined( USE_BUMPMAP ) || defined( USE_NORMALMAP_TANGENTSPACE )
	varying vec3 vViewPosition;
#endif
#include <packing>
#include <uv_pars_fragment>
#include <normal_pars_fragment>
#include <bumpmap_pars_fragment>
#include <normalmap_pars_fragment>
#include <logdepthbuf_pars_fragment>
#include <clipping_planes_pars_fragment>
void main() {
	vec4 diffuseColor = vec4( 0.0, 0.0, 0.0, opacity );
	#include <clipping_planes_fragment>
	#include <logdepthbuf_fragment>
	#include <normal_fragment_begin>
	#include <normal_fragment_maps>
	gl_FragColor = vec4( packNormalToRGB( normal ), diffuseColor.a );
	#ifdef OPAQUE
		gl_FragColor.a = 1.0;
	#endif
}`, Lb = `#define PHONG
varying vec3 vViewPosition;
#include <common>
#include <batching_pars_vertex>
#include <uv_pars_vertex>
#include <displacementmap_pars_vertex>
#include <envmap_pars_vertex>
#include <color_pars_vertex>
#include <fog_pars_vertex>
#include <normal_pars_vertex>
#include <morphtarget_pars_vertex>
#include <skinning_pars_vertex>
#include <shadowmap_pars_vertex>
#include <logdepthbuf_pars_vertex>
#include <clipping_planes_pars_vertex>
void main() {
	#include <uv_vertex>
	#include <color_vertex>
	#include <morphcolor_vertex>
	#include <batching_vertex>
	#include <beginnormal_vertex>
	#include <morphinstance_vertex>
	#include <morphnormal_vertex>
	#include <skinbase_vertex>
	#include <skinnormal_vertex>
	#include <defaultnormal_vertex>
	#include <normal_vertex>
	#include <begin_vertex>
	#include <morphtarget_vertex>
	#include <skinning_vertex>
	#include <displacementmap_vertex>
	#include <project_vertex>
	#include <logdepthbuf_vertex>
	#include <clipping_planes_vertex>
	vViewPosition = - mvPosition.xyz;
	#include <worldpos_vertex>
	#include <envmap_vertex>
	#include <shadowmap_vertex>
	#include <fog_vertex>
}`, Ib = `#define PHONG
uniform vec3 diffuse;
uniform vec3 emissive;
uniform vec3 specular;
uniform float shininess;
uniform float opacity;
#include <common>
#include <packing>
#include <dithering_pars_fragment>
#include <color_pars_fragment>
#include <uv_pars_fragment>
#include <map_pars_fragment>
#include <alphamap_pars_fragment>
#include <alphatest_pars_fragment>
#include <alphahash_pars_fragment>
#include <aomap_pars_fragment>
#include <lightmap_pars_fragment>
#include <emissivemap_pars_fragment>
#include <envmap_common_pars_fragment>
#include <envmap_pars_fragment>
#include <fog_pars_fragment>
#include <bsdfs>
#include <lights_pars_begin>
#include <normal_pars_fragment>
#include <lights_phong_pars_fragment>
#include <shadowmap_pars_fragment>
#include <bumpmap_pars_fragment>
#include <normalmap_pars_fragment>
#include <specularmap_pars_fragment>
#include <logdepthbuf_pars_fragment>
#include <clipping_planes_pars_fragment>
void main() {
	vec4 diffuseColor = vec4( diffuse, opacity );
	#include <clipping_planes_fragment>
	ReflectedLight reflectedLight = ReflectedLight( vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ) );
	vec3 totalEmissiveRadiance = emissive;
	#include <logdepthbuf_fragment>
	#include <map_fragment>
	#include <color_fragment>
	#include <alphamap_fragment>
	#include <alphatest_fragment>
	#include <alphahash_fragment>
	#include <specularmap_fragment>
	#include <normal_fragment_begin>
	#include <normal_fragment_maps>
	#include <emissivemap_fragment>
	#include <lights_phong_fragment>
	#include <lights_fragment_begin>
	#include <lights_fragment_maps>
	#include <lights_fragment_end>
	#include <aomap_fragment>
	vec3 outgoingLight = reflectedLight.directDiffuse + reflectedLight.indirectDiffuse + reflectedLight.directSpecular + reflectedLight.indirectSpecular + totalEmissiveRadiance;
	#include <envmap_fragment>
	#include <opaque_fragment>
	#include <tonemapping_fragment>
	#include <colorspace_fragment>
	#include <fog_fragment>
	#include <premultiplied_alpha_fragment>
	#include <dithering_fragment>
}`, Db = `#define STANDARD
varying vec3 vViewPosition;
#ifdef USE_TRANSMISSION
	varying vec3 vWorldPosition;
#endif
#include <common>
#include <batching_pars_vertex>
#include <uv_pars_vertex>
#include <displacementmap_pars_vertex>
#include <color_pars_vertex>
#include <fog_pars_vertex>
#include <normal_pars_vertex>
#include <morphtarget_pars_vertex>
#include <skinning_pars_vertex>
#include <shadowmap_pars_vertex>
#include <logdepthbuf_pars_vertex>
#include <clipping_planes_pars_vertex>
void main() {
	#include <uv_vertex>
	#include <color_vertex>
	#include <morphinstance_vertex>
	#include <morphcolor_vertex>
	#include <batching_vertex>
	#include <beginnormal_vertex>
	#include <morphnormal_vertex>
	#include <skinbase_vertex>
	#include <skinnormal_vertex>
	#include <defaultnormal_vertex>
	#include <normal_vertex>
	#include <begin_vertex>
	#include <morphtarget_vertex>
	#include <skinning_vertex>
	#include <displacementmap_vertex>
	#include <project_vertex>
	#include <logdepthbuf_vertex>
	#include <clipping_planes_vertex>
	vViewPosition = - mvPosition.xyz;
	#include <worldpos_vertex>
	#include <shadowmap_vertex>
	#include <fog_vertex>
#ifdef USE_TRANSMISSION
	vWorldPosition = worldPosition.xyz;
#endif
}`, Nb = `#define STANDARD
#ifdef PHYSICAL
	#define IOR
	#define USE_SPECULAR
#endif
uniform vec3 diffuse;
uniform vec3 emissive;
uniform float roughness;
uniform float metalness;
uniform float opacity;
#ifdef IOR
	uniform float ior;
#endif
#ifdef USE_SPECULAR
	uniform float specularIntensity;
	uniform vec3 specularColor;
	#ifdef USE_SPECULAR_COLORMAP
		uniform sampler2D specularColorMap;
	#endif
	#ifdef USE_SPECULAR_INTENSITYMAP
		uniform sampler2D specularIntensityMap;
	#endif
#endif
#ifdef USE_CLEARCOAT
	uniform float clearcoat;
	uniform float clearcoatRoughness;
#endif
#ifdef USE_DISPERSION
	uniform float dispersion;
#endif
#ifdef USE_IRIDESCENCE
	uniform float iridescence;
	uniform float iridescenceIOR;
	uniform float iridescenceThicknessMinimum;
	uniform float iridescenceThicknessMaximum;
#endif
#ifdef USE_SHEEN
	uniform vec3 sheenColor;
	uniform float sheenRoughness;
	#ifdef USE_SHEEN_COLORMAP
		uniform sampler2D sheenColorMap;
	#endif
	#ifdef USE_SHEEN_ROUGHNESSMAP
		uniform sampler2D sheenRoughnessMap;
	#endif
#endif
#ifdef USE_ANISOTROPY
	uniform vec2 anisotropyVector;
	#ifdef USE_ANISOTROPYMAP
		uniform sampler2D anisotropyMap;
	#endif
#endif
varying vec3 vViewPosition;
#include <common>
#include <packing>
#include <dithering_pars_fragment>
#include <color_pars_fragment>
#include <uv_pars_fragment>
#include <map_pars_fragment>
#include <alphamap_pars_fragment>
#include <alphatest_pars_fragment>
#include <alphahash_pars_fragment>
#include <aomap_pars_fragment>
#include <lightmap_pars_fragment>
#include <emissivemap_pars_fragment>
#include <iridescence_fragment>
#include <cube_uv_reflection_fragment>
#include <envmap_common_pars_fragment>
#include <envmap_physical_pars_fragment>
#include <fog_pars_fragment>
#include <lights_pars_begin>
#include <normal_pars_fragment>
#include <lights_physical_pars_fragment>
#include <transmission_pars_fragment>
#include <shadowmap_pars_fragment>
#include <bumpmap_pars_fragment>
#include <normalmap_pars_fragment>
#include <clearcoat_pars_fragment>
#include <iridescence_pars_fragment>
#include <roughnessmap_pars_fragment>
#include <metalnessmap_pars_fragment>
#include <logdepthbuf_pars_fragment>
#include <clipping_planes_pars_fragment>
void main() {
	vec4 diffuseColor = vec4( diffuse, opacity );
	#include <clipping_planes_fragment>
	ReflectedLight reflectedLight = ReflectedLight( vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ) );
	vec3 totalEmissiveRadiance = emissive;
	#include <logdepthbuf_fragment>
	#include <map_fragment>
	#include <color_fragment>
	#include <alphamap_fragment>
	#include <alphatest_fragment>
	#include <alphahash_fragment>
	#include <roughnessmap_fragment>
	#include <metalnessmap_fragment>
	#include <normal_fragment_begin>
	#include <normal_fragment_maps>
	#include <clearcoat_normal_fragment_begin>
	#include <clearcoat_normal_fragment_maps>
	#include <emissivemap_fragment>
	#include <lights_physical_fragment>
	#include <lights_fragment_begin>
	#include <lights_fragment_maps>
	#include <lights_fragment_end>
	#include <aomap_fragment>
	vec3 totalDiffuse = reflectedLight.directDiffuse + reflectedLight.indirectDiffuse;
	vec3 totalSpecular = reflectedLight.directSpecular + reflectedLight.indirectSpecular;
	#include <transmission_fragment>
	vec3 outgoingLight = totalDiffuse + totalSpecular + totalEmissiveRadiance;
	#ifdef USE_SHEEN
		float sheenEnergyComp = 1.0 - 0.157 * max3( material.sheenColor );
		outgoingLight = outgoingLight * sheenEnergyComp + sheenSpecularDirect + sheenSpecularIndirect;
	#endif
	#ifdef USE_CLEARCOAT
		float dotNVcc = saturate( dot( geometryClearcoatNormal, geometryViewDir ) );
		vec3 Fcc = F_Schlick( material.clearcoatF0, material.clearcoatF90, dotNVcc );
		outgoingLight = outgoingLight * ( 1.0 - material.clearcoat * Fcc ) + ( clearcoatSpecularDirect + clearcoatSpecularIndirect ) * material.clearcoat;
	#endif
	#include <opaque_fragment>
	#include <tonemapping_fragment>
	#include <colorspace_fragment>
	#include <fog_fragment>
	#include <premultiplied_alpha_fragment>
	#include <dithering_fragment>
}`, Ub = `#define TOON
varying vec3 vViewPosition;
#include <common>
#include <batching_pars_vertex>
#include <uv_pars_vertex>
#include <displacementmap_pars_vertex>
#include <color_pars_vertex>
#include <fog_pars_vertex>
#include <normal_pars_vertex>
#include <morphtarget_pars_vertex>
#include <skinning_pars_vertex>
#include <shadowmap_pars_vertex>
#include <logdepthbuf_pars_vertex>
#include <clipping_planes_pars_vertex>
void main() {
	#include <uv_vertex>
	#include <color_vertex>
	#include <morphinstance_vertex>
	#include <morphcolor_vertex>
	#include <batching_vertex>
	#include <beginnormal_vertex>
	#include <morphnormal_vertex>
	#include <skinbase_vertex>
	#include <skinnormal_vertex>
	#include <defaultnormal_vertex>
	#include <normal_vertex>
	#include <begin_vertex>
	#include <morphtarget_vertex>
	#include <skinning_vertex>
	#include <displacementmap_vertex>
	#include <project_vertex>
	#include <logdepthbuf_vertex>
	#include <clipping_planes_vertex>
	vViewPosition = - mvPosition.xyz;
	#include <worldpos_vertex>
	#include <shadowmap_vertex>
	#include <fog_vertex>
}`, Ob = `#define TOON
uniform vec3 diffuse;
uniform vec3 emissive;
uniform float opacity;
#include <common>
#include <packing>
#include <dithering_pars_fragment>
#include <color_pars_fragment>
#include <uv_pars_fragment>
#include <map_pars_fragment>
#include <alphamap_pars_fragment>
#include <alphatest_pars_fragment>
#include <alphahash_pars_fragment>
#include <aomap_pars_fragment>
#include <lightmap_pars_fragment>
#include <emissivemap_pars_fragment>
#include <gradientmap_pars_fragment>
#include <fog_pars_fragment>
#include <bsdfs>
#include <lights_pars_begin>
#include <normal_pars_fragment>
#include <lights_toon_pars_fragment>
#include <shadowmap_pars_fragment>
#include <bumpmap_pars_fragment>
#include <normalmap_pars_fragment>
#include <logdepthbuf_pars_fragment>
#include <clipping_planes_pars_fragment>
void main() {
	vec4 diffuseColor = vec4( diffuse, opacity );
	#include <clipping_planes_fragment>
	ReflectedLight reflectedLight = ReflectedLight( vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ) );
	vec3 totalEmissiveRadiance = emissive;
	#include <logdepthbuf_fragment>
	#include <map_fragment>
	#include <color_fragment>
	#include <alphamap_fragment>
	#include <alphatest_fragment>
	#include <alphahash_fragment>
	#include <normal_fragment_begin>
	#include <normal_fragment_maps>
	#include <emissivemap_fragment>
	#include <lights_toon_fragment>
	#include <lights_fragment_begin>
	#include <lights_fragment_maps>
	#include <lights_fragment_end>
	#include <aomap_fragment>
	vec3 outgoingLight = reflectedLight.directDiffuse + reflectedLight.indirectDiffuse + totalEmissiveRadiance;
	#include <opaque_fragment>
	#include <tonemapping_fragment>
	#include <colorspace_fragment>
	#include <fog_fragment>
	#include <premultiplied_alpha_fragment>
	#include <dithering_fragment>
}`, Fb = `uniform float size;
uniform float scale;
#include <common>
#include <color_pars_vertex>
#include <fog_pars_vertex>
#include <morphtarget_pars_vertex>
#include <logdepthbuf_pars_vertex>
#include <clipping_planes_pars_vertex>
#ifdef USE_POINTS_UV
	varying vec2 vUv;
	uniform mat3 uvTransform;
#endif
void main() {
	#ifdef USE_POINTS_UV
		vUv = ( uvTransform * vec3( uv, 1 ) ).xy;
	#endif
	#include <color_vertex>
	#include <morphinstance_vertex>
	#include <morphcolor_vertex>
	#include <begin_vertex>
	#include <morphtarget_vertex>
	#include <project_vertex>
	gl_PointSize = size;
	#ifdef USE_SIZEATTENUATION
		bool isPerspective = isPerspectiveMatrix( projectionMatrix );
		if ( isPerspective ) gl_PointSize *= ( scale / - mvPosition.z );
	#endif
	#include <logdepthbuf_vertex>
	#include <clipping_planes_vertex>
	#include <worldpos_vertex>
	#include <fog_vertex>
}`, Bb = `uniform vec3 diffuse;
uniform float opacity;
#include <common>
#include <color_pars_fragment>
#include <map_particle_pars_fragment>
#include <alphatest_pars_fragment>
#include <alphahash_pars_fragment>
#include <fog_pars_fragment>
#include <logdepthbuf_pars_fragment>
#include <clipping_planes_pars_fragment>
void main() {
	vec4 diffuseColor = vec4( diffuse, opacity );
	#include <clipping_planes_fragment>
	vec3 outgoingLight = vec3( 0.0 );
	#include <logdepthbuf_fragment>
	#include <map_particle_fragment>
	#include <color_fragment>
	#include <alphatest_fragment>
	#include <alphahash_fragment>
	outgoingLight = diffuseColor.rgb;
	#include <opaque_fragment>
	#include <tonemapping_fragment>
	#include <colorspace_fragment>
	#include <fog_fragment>
	#include <premultiplied_alpha_fragment>
}`, kb = `#include <common>
#include <batching_pars_vertex>
#include <fog_pars_vertex>
#include <morphtarget_pars_vertex>
#include <skinning_pars_vertex>
#include <logdepthbuf_pars_vertex>
#include <shadowmap_pars_vertex>
void main() {
	#include <batching_vertex>
	#include <beginnormal_vertex>
	#include <morphinstance_vertex>
	#include <morphnormal_vertex>
	#include <skinbase_vertex>
	#include <skinnormal_vertex>
	#include <defaultnormal_vertex>
	#include <begin_vertex>
	#include <morphtarget_vertex>
	#include <skinning_vertex>
	#include <project_vertex>
	#include <logdepthbuf_vertex>
	#include <worldpos_vertex>
	#include <shadowmap_vertex>
	#include <fog_vertex>
}`, zb = `uniform vec3 color;
uniform float opacity;
#include <common>
#include <packing>
#include <fog_pars_fragment>
#include <bsdfs>
#include <lights_pars_begin>
#include <logdepthbuf_pars_fragment>
#include <shadowmap_pars_fragment>
#include <shadowmask_pars_fragment>
void main() {
	#include <logdepthbuf_fragment>
	gl_FragColor = vec4( color, opacity * ( 1.0 - getShadowMask() ) );
	#include <tonemapping_fragment>
	#include <colorspace_fragment>
	#include <fog_fragment>
}`, Hb = `uniform float rotation;
uniform vec2 center;
#include <common>
#include <uv_pars_vertex>
#include <fog_pars_vertex>
#include <logdepthbuf_pars_vertex>
#include <clipping_planes_pars_vertex>
void main() {
	#include <uv_vertex>
	vec4 mvPosition = modelViewMatrix[ 3 ];
	vec2 scale = vec2( length( modelMatrix[ 0 ].xyz ), length( modelMatrix[ 1 ].xyz ) );
	#ifndef USE_SIZEATTENUATION
		bool isPerspective = isPerspectiveMatrix( projectionMatrix );
		if ( isPerspective ) scale *= - mvPosition.z;
	#endif
	vec2 alignedPosition = ( position.xy - ( center - vec2( 0.5 ) ) ) * scale;
	vec2 rotatedPosition;
	rotatedPosition.x = cos( rotation ) * alignedPosition.x - sin( rotation ) * alignedPosition.y;
	rotatedPosition.y = sin( rotation ) * alignedPosition.x + cos( rotation ) * alignedPosition.y;
	mvPosition.xy += rotatedPosition;
	gl_Position = projectionMatrix * mvPosition;
	#include <logdepthbuf_vertex>
	#include <clipping_planes_vertex>
	#include <fog_vertex>
}`, Vb = `uniform vec3 diffuse;
uniform float opacity;
#include <common>
#include <uv_pars_fragment>
#include <map_pars_fragment>
#include <alphamap_pars_fragment>
#include <alphatest_pars_fragment>
#include <alphahash_pars_fragment>
#include <fog_pars_fragment>
#include <logdepthbuf_pars_fragment>
#include <clipping_planes_pars_fragment>
void main() {
	vec4 diffuseColor = vec4( diffuse, opacity );
	#include <clipping_planes_fragment>
	vec3 outgoingLight = vec3( 0.0 );
	#include <logdepthbuf_fragment>
	#include <map_fragment>
	#include <alphamap_fragment>
	#include <alphatest_fragment>
	#include <alphahash_fragment>
	outgoingLight = diffuseColor.rgb;
	#include <opaque_fragment>
	#include <tonemapping_fragment>
	#include <colorspace_fragment>
	#include <fog_fragment>
}`, Ze = {
  alphahash_fragment: hv,
  alphahash_pars_fragment: dv,
  alphamap_fragment: uv,
  alphamap_pars_fragment: pv,
  alphatest_fragment: fv,
  alphatest_pars_fragment: mv,
  aomap_fragment: gv,
  aomap_pars_fragment: _v,
  batching_pars_vertex: yv,
  batching_vertex: vv,
  begin_vertex: xv,
  beginnormal_vertex: bv,
  bsdfs: Sv,
  iridescence_fragment: Mv,
  bumpmap_pars_fragment: wv,
  clipping_planes_fragment: Ev,
  clipping_planes_pars_fragment: Tv,
  clipping_planes_pars_vertex: Av,
  clipping_planes_vertex: Cv,
  color_fragment: Rv,
  color_pars_fragment: Pv,
  color_pars_vertex: Lv,
  color_vertex: Iv,
  common: Dv,
  cube_uv_reflection_fragment: Nv,
  defaultnormal_vertex: Uv,
  displacementmap_pars_vertex: Ov,
  displacementmap_vertex: Fv,
  emissivemap_fragment: Bv,
  emissivemap_pars_fragment: kv,
  colorspace_fragment: zv,
  colorspace_pars_fragment: Hv,
  envmap_fragment: Vv,
  envmap_common_pars_fragment: Gv,
  envmap_pars_fragment: Wv,
  envmap_pars_vertex: Xv,
  envmap_physical_pars_fragment: ix,
  envmap_vertex: qv,
  fog_vertex: Zv,
  fog_pars_vertex: Yv,
  fog_fragment: jv,
  fog_pars_fragment: $v,
  gradientmap_pars_fragment: Kv,
  lightmap_pars_fragment: Jv,
  lights_lambert_fragment: Qv,
  lights_lambert_pars_fragment: ex,
  lights_pars_begin: tx,
  lights_toon_fragment: nx,
  lights_toon_pars_fragment: sx,
  lights_phong_fragment: rx,
  lights_phong_pars_fragment: ax,
  lights_physical_fragment: ox,
  lights_physical_pars_fragment: lx,
  lights_fragment_begin: cx,
  lights_fragment_maps: hx,
  lights_fragment_end: dx,
  logdepthbuf_fragment: ux,
  logdepthbuf_pars_fragment: px,
  logdepthbuf_pars_vertex: fx,
  logdepthbuf_vertex: mx,
  map_fragment: gx,
  map_pars_fragment: _x,
  map_particle_fragment: yx,
  map_particle_pars_fragment: vx,
  metalnessmap_fragment: xx,
  metalnessmap_pars_fragment: bx,
  morphinstance_vertex: Sx,
  morphcolor_vertex: Mx,
  morphnormal_vertex: wx,
  morphtarget_pars_vertex: Ex,
  morphtarget_vertex: Tx,
  normal_fragment_begin: Ax,
  normal_fragment_maps: Cx,
  normal_pars_fragment: Rx,
  normal_pars_vertex: Px,
  normal_vertex: Lx,
  normalmap_pars_fragment: Ix,
  clearcoat_normal_fragment_begin: Dx,
  clearcoat_normal_fragment_maps: Nx,
  clearcoat_pars_fragment: Ux,
  iridescence_pars_fragment: Ox,
  opaque_fragment: Fx,
  packing: Bx,
  premultiplied_alpha_fragment: kx,
  project_vertex: zx,
  dithering_fragment: Hx,
  dithering_pars_fragment: Vx,
  roughnessmap_fragment: Gx,
  roughnessmap_pars_fragment: Wx,
  shadowmap_pars_fragment: Xx,
  shadowmap_pars_vertex: qx,
  shadowmap_vertex: Zx,
  shadowmask_pars_fragment: Yx,
  skinbase_vertex: jx,
  skinning_pars_vertex: $x,
  skinning_vertex: Kx,
  skinnormal_vertex: Jx,
  specularmap_fragment: Qx,
  specularmap_pars_fragment: eb,
  tonemapping_fragment: tb,
  tonemapping_pars_fragment: ib,
  transmission_fragment: nb,
  transmission_pars_fragment: sb,
  uv_pars_fragment: rb,
  uv_pars_vertex: ab,
  uv_vertex: ob,
  worldpos_vertex: lb,
  background_vert: cb,
  background_frag: hb,
  backgroundCube_vert: db,
  backgroundCube_frag: ub,
  cube_vert: pb,
  cube_frag: fb,
  depth_vert: mb,
  depth_frag: gb,
  distanceRGBA_vert: _b,
  distanceRGBA_frag: yb,
  equirect_vert: vb,
  equirect_frag: xb,
  linedashed_vert: bb,
  linedashed_frag: Sb,
  meshbasic_vert: Mb,
  meshbasic_frag: wb,
  meshlambert_vert: Eb,
  meshlambert_frag: Tb,
  meshmatcap_vert: Ab,
  meshmatcap_frag: Cb,
  meshnormal_vert: Rb,
  meshnormal_frag: Pb,
  meshphong_vert: Lb,
  meshphong_frag: Ib,
  meshphysical_vert: Db,
  meshphysical_frag: Nb,
  meshtoon_vert: Ub,
  meshtoon_frag: Ob,
  points_vert: Fb,
  points_frag: Bb,
  shadow_vert: kb,
  shadow_frag: zb,
  sprite_vert: Hb,
  sprite_frag: Vb
}, pe = {
  common: {
    diffuse: { value: /* @__PURE__ */ new oe(16777215) },
    opacity: { value: 1 },
    map: { value: null },
    mapTransform: { value: /* @__PURE__ */ new He() },
    alphaMap: { value: null },
    alphaMapTransform: { value: /* @__PURE__ */ new He() },
    alphaTest: { value: 0 }
  },
  specularmap: {
    specularMap: { value: null },
    specularMapTransform: { value: /* @__PURE__ */ new He() }
  },
  envmap: {
    envMap: { value: null },
    envMapRotation: { value: /* @__PURE__ */ new He() },
    flipEnvMap: { value: -1 },
    reflectivity: { value: 1 },
    // basic, lambert, phong
    ior: { value: 1.5 },
    // physical
    refractionRatio: { value: 0.98 }
    // basic, lambert, phong
  },
  aomap: {
    aoMap: { value: null },
    aoMapIntensity: { value: 1 },
    aoMapTransform: { value: /* @__PURE__ */ new He() }
  },
  lightmap: {
    lightMap: { value: null },
    lightMapIntensity: { value: 1 },
    lightMapTransform: { value: /* @__PURE__ */ new He() }
  },
  bumpmap: {
    bumpMap: { value: null },
    bumpMapTransform: { value: /* @__PURE__ */ new He() },
    bumpScale: { value: 1 }
  },
  normalmap: {
    normalMap: { value: null },
    normalMapTransform: { value: /* @__PURE__ */ new He() },
    normalScale: { value: /* @__PURE__ */ new H(1, 1) }
  },
  displacementmap: {
    displacementMap: { value: null },
    displacementMapTransform: { value: /* @__PURE__ */ new He() },
    displacementScale: { value: 1 },
    displacementBias: { value: 0 }
  },
  emissivemap: {
    emissiveMap: { value: null },
    emissiveMapTransform: { value: /* @__PURE__ */ new He() }
  },
  metalnessmap: {
    metalnessMap: { value: null },
    metalnessMapTransform: { value: /* @__PURE__ */ new He() }
  },
  roughnessmap: {
    roughnessMap: { value: null },
    roughnessMapTransform: { value: /* @__PURE__ */ new He() }
  },
  gradientmap: {
    gradientMap: { value: null }
  },
  fog: {
    fogDensity: { value: 25e-5 },
    fogNear: { value: 1 },
    fogFar: { value: 2e3 },
    fogColor: { value: /* @__PURE__ */ new oe(16777215) }
  },
  lights: {
    ambientLightColor: { value: [] },
    lightProbe: { value: [] },
    directionalLights: { value: [], properties: {
      direction: {},
      color: {}
    } },
    directionalLightShadows: { value: [], properties: {
      shadowIntensity: 1,
      shadowBias: {},
      shadowNormalBias: {},
      shadowRadius: {},
      shadowMapSize: {}
    } },
    directionalShadowMap: { value: [] },
    directionalShadowMatrix: { value: [] },
    spotLights: { value: [], properties: {
      color: {},
      position: {},
      direction: {},
      distance: {},
      coneCos: {},
      penumbraCos: {},
      decay: {}
    } },
    spotLightShadows: { value: [], properties: {
      shadowIntensity: 1,
      shadowBias: {},
      shadowNormalBias: {},
      shadowRadius: {},
      shadowMapSize: {}
    } },
    spotLightMap: { value: [] },
    spotShadowMap: { value: [] },
    spotLightMatrix: { value: [] },
    pointLights: { value: [], properties: {
      color: {},
      position: {},
      decay: {},
      distance: {}
    } },
    pointLightShadows: { value: [], properties: {
      shadowIntensity: 1,
      shadowBias: {},
      shadowNormalBias: {},
      shadowRadius: {},
      shadowMapSize: {},
      shadowCameraNear: {},
      shadowCameraFar: {}
    } },
    pointShadowMap: { value: [] },
    pointShadowMatrix: { value: [] },
    hemisphereLights: { value: [], properties: {
      direction: {},
      skyColor: {},
      groundColor: {}
    } },
    // TODO (abelnation): RectAreaLight BRDF data needs to be moved from example to main src
    rectAreaLights: { value: [], properties: {
      color: {},
      position: {},
      width: {},
      height: {}
    } },
    ltc_1: { value: null },
    ltc_2: { value: null }
  },
  points: {
    diffuse: { value: /* @__PURE__ */ new oe(16777215) },
    opacity: { value: 1 },
    size: { value: 1 },
    scale: { value: 1 },
    map: { value: null },
    alphaMap: { value: null },
    alphaMapTransform: { value: /* @__PURE__ */ new He() },
    alphaTest: { value: 0 },
    uvTransform: { value: /* @__PURE__ */ new He() }
  },
  sprite: {
    diffuse: { value: /* @__PURE__ */ new oe(16777215) },
    opacity: { value: 1 },
    center: { value: /* @__PURE__ */ new H(0.5, 0.5) },
    rotation: { value: 0 },
    map: { value: null },
    mapTransform: { value: /* @__PURE__ */ new He() },
    alphaMap: { value: null },
    alphaMapTransform: { value: /* @__PURE__ */ new He() },
    alphaTest: { value: 0 }
  }
}, si = {
  basic: {
    uniforms: /* @__PURE__ */ ni([
      pe.common,
      pe.specularmap,
      pe.envmap,
      pe.aomap,
      pe.lightmap,
      pe.fog
    ]),
    vertexShader: Ze.meshbasic_vert,
    fragmentShader: Ze.meshbasic_frag
  },
  lambert: {
    uniforms: /* @__PURE__ */ ni([
      pe.common,
      pe.specularmap,
      pe.envmap,
      pe.aomap,
      pe.lightmap,
      pe.emissivemap,
      pe.bumpmap,
      pe.normalmap,
      pe.displacementmap,
      pe.fog,
      pe.lights,
      {
        emissive: { value: /* @__PURE__ */ new oe(0) }
      }
    ]),
    vertexShader: Ze.meshlambert_vert,
    fragmentShader: Ze.meshlambert_frag
  },
  phong: {
    uniforms: /* @__PURE__ */ ni([
      pe.common,
      pe.specularmap,
      pe.envmap,
      pe.aomap,
      pe.lightmap,
      pe.emissivemap,
      pe.bumpmap,
      pe.normalmap,
      pe.displacementmap,
      pe.fog,
      pe.lights,
      {
        emissive: { value: /* @__PURE__ */ new oe(0) },
        specular: { value: /* @__PURE__ */ new oe(1118481) },
        shininess: { value: 30 }
      }
    ]),
    vertexShader: Ze.meshphong_vert,
    fragmentShader: Ze.meshphong_frag
  },
  standard: {
    uniforms: /* @__PURE__ */ ni([
      pe.common,
      pe.envmap,
      pe.aomap,
      pe.lightmap,
      pe.emissivemap,
      pe.bumpmap,
      pe.normalmap,
      pe.displacementmap,
      pe.roughnessmap,
      pe.metalnessmap,
      pe.fog,
      pe.lights,
      {
        emissive: { value: /* @__PURE__ */ new oe(0) },
        roughness: { value: 1 },
        metalness: { value: 0 },
        envMapIntensity: { value: 1 }
      }
    ]),
    vertexShader: Ze.meshphysical_vert,
    fragmentShader: Ze.meshphysical_frag
  },
  toon: {
    uniforms: /* @__PURE__ */ ni([
      pe.common,
      pe.aomap,
      pe.lightmap,
      pe.emissivemap,
      pe.bumpmap,
      pe.normalmap,
      pe.displacementmap,
      pe.gradientmap,
      pe.fog,
      pe.lights,
      {
        emissive: { value: /* @__PURE__ */ new oe(0) }
      }
    ]),
    vertexShader: Ze.meshtoon_vert,
    fragmentShader: Ze.meshtoon_frag
  },
  matcap: {
    uniforms: /* @__PURE__ */ ni([
      pe.common,
      pe.bumpmap,
      pe.normalmap,
      pe.displacementmap,
      pe.fog,
      {
        matcap: { value: null }
      }
    ]),
    vertexShader: Ze.meshmatcap_vert,
    fragmentShader: Ze.meshmatcap_frag
  },
  points: {
    uniforms: /* @__PURE__ */ ni([
      pe.points,
      pe.fog
    ]),
    vertexShader: Ze.points_vert,
    fragmentShader: Ze.points_frag
  },
  dashed: {
    uniforms: /* @__PURE__ */ ni([
      pe.common,
      pe.fog,
      {
        scale: { value: 1 },
        dashSize: { value: 1 },
        totalSize: { value: 2 }
      }
    ]),
    vertexShader: Ze.linedashed_vert,
    fragmentShader: Ze.linedashed_frag
  },
  depth: {
    uniforms: /* @__PURE__ */ ni([
      pe.common,
      pe.displacementmap
    ]),
    vertexShader: Ze.depth_vert,
    fragmentShader: Ze.depth_frag
  },
  normal: {
    uniforms: /* @__PURE__ */ ni([
      pe.common,
      pe.bumpmap,
      pe.normalmap,
      pe.displacementmap,
      {
        opacity: { value: 1 }
      }
    ]),
    vertexShader: Ze.meshnormal_vert,
    fragmentShader: Ze.meshnormal_frag
  },
  sprite: {
    uniforms: /* @__PURE__ */ ni([
      pe.sprite,
      pe.fog
    ]),
    vertexShader: Ze.sprite_vert,
    fragmentShader: Ze.sprite_frag
  },
  background: {
    uniforms: {
      uvTransform: { value: /* @__PURE__ */ new He() },
      t2D: { value: null },
      backgroundIntensity: { value: 1 }
    },
    vertexShader: Ze.background_vert,
    fragmentShader: Ze.background_frag
  },
  backgroundCube: {
    uniforms: {
      envMap: { value: null },
      flipEnvMap: { value: -1 },
      backgroundBlurriness: { value: 0 },
      backgroundIntensity: { value: 1 },
      backgroundRotation: { value: /* @__PURE__ */ new He() }
    },
    vertexShader: Ze.backgroundCube_vert,
    fragmentShader: Ze.backgroundCube_frag
  },
  cube: {
    uniforms: {
      tCube: { value: null },
      tFlip: { value: -1 },
      opacity: { value: 1 }
    },
    vertexShader: Ze.cube_vert,
    fragmentShader: Ze.cube_frag
  },
  equirect: {
    uniforms: {
      tEquirect: { value: null }
    },
    vertexShader: Ze.equirect_vert,
    fragmentShader: Ze.equirect_frag
  },
  distanceRGBA: {
    uniforms: /* @__PURE__ */ ni([
      pe.common,
      pe.displacementmap,
      {
        referencePosition: { value: /* @__PURE__ */ new b() },
        nearDistance: { value: 1 },
        farDistance: { value: 1e3 }
      }
    ]),
    vertexShader: Ze.distanceRGBA_vert,
    fragmentShader: Ze.distanceRGBA_frag
  },
  shadow: {
    uniforms: /* @__PURE__ */ ni([
      pe.lights,
      pe.fog,
      {
        color: { value: /* @__PURE__ */ new oe(0) },
        opacity: { value: 1 }
      }
    ]),
    vertexShader: Ze.shadow_vert,
    fragmentShader: Ze.shadow_frag
  }
};
si.physical = {
  uniforms: /* @__PURE__ */ ni([
    si.standard.uniforms,
    {
      clearcoat: { value: 0 },
      clearcoatMap: { value: null },
      clearcoatMapTransform: { value: /* @__PURE__ */ new He() },
      clearcoatNormalMap: { value: null },
      clearcoatNormalMapTransform: { value: /* @__PURE__ */ new He() },
      clearcoatNormalScale: { value: /* @__PURE__ */ new H(1, 1) },
      clearcoatRoughness: { value: 0 },
      clearcoatRoughnessMap: { value: null },
      clearcoatRoughnessMapTransform: { value: /* @__PURE__ */ new He() },
      dispersion: { value: 0 },
      iridescence: { value: 0 },
      iridescenceMap: { value: null },
      iridescenceMapTransform: { value: /* @__PURE__ */ new He() },
      iridescenceIOR: { value: 1.3 },
      iridescenceThicknessMinimum: { value: 100 },
      iridescenceThicknessMaximum: { value: 400 },
      iridescenceThicknessMap: { value: null },
      iridescenceThicknessMapTransform: { value: /* @__PURE__ */ new He() },
      sheen: { value: 0 },
      sheenColor: { value: /* @__PURE__ */ new oe(0) },
      sheenColorMap: { value: null },
      sheenColorMapTransform: { value: /* @__PURE__ */ new He() },
      sheenRoughness: { value: 1 },
      sheenRoughnessMap: { value: null },
      sheenRoughnessMapTransform: { value: /* @__PURE__ */ new He() },
      transmission: { value: 0 },
      transmissionMap: { value: null },
      transmissionMapTransform: { value: /* @__PURE__ */ new He() },
      transmissionSamplerSize: { value: /* @__PURE__ */ new H() },
      transmissionSamplerMap: { value: null },
      thickness: { value: 0 },
      thicknessMap: { value: null },
      thicknessMapTransform: { value: /* @__PURE__ */ new He() },
      attenuationDistance: { value: 0 },
      attenuationColor: { value: /* @__PURE__ */ new oe(0) },
      specularColor: { value: /* @__PURE__ */ new oe(1, 1, 1) },
      specularColorMap: { value: null },
      specularColorMapTransform: { value: /* @__PURE__ */ new He() },
      specularIntensity: { value: 1 },
      specularIntensityMap: { value: null },
      specularIntensityMapTransform: { value: /* @__PURE__ */ new He() },
      anisotropyVector: { value: /* @__PURE__ */ new H() },
      anisotropyMap: { value: null },
      anisotropyMapTransform: { value: /* @__PURE__ */ new He() }
    }
  ]),
  vertexShader: Ze.meshphysical_vert,
  fragmentShader: Ze.meshphysical_frag
};
const vo = { r: 0, b: 0, g: 0 }, ss = /* @__PURE__ */ new Ai(), Gb = /* @__PURE__ */ new Ne();
function Wb(r, e, t, i, n, s, a) {
  const o = new oe(0);
  let l = s === !0 ? 0 : 1, c, h, d = null, u = 0, p = null;
  function m(x) {
    let y = x.isScene === !0 ? x.background : null;
    return y && y.isTexture && (y = (x.backgroundBlurriness > 0 ? t : e).get(y)), y;
  }
  function _(x) {
    let y = !1;
    const A = m(x);
    A === null ? f(o, l) : A && A.isColor && (f(A, 1), y = !0);
    const S = r.xr.getEnvironmentBlendMode();
    S === "additive" ? i.buffers.color.setClear(0, 0, 0, 1, a) : S === "alpha-blend" && i.buffers.color.setClear(0, 0, 0, 0, a), (r.autoClear || y) && (i.buffers.depth.setTest(!0), i.buffers.depth.setMask(!0), i.buffers.color.setMask(!0), r.clear(r.autoClearColor, r.autoClearDepth, r.autoClearStencil));
  }
  function g(x, y) {
    const A = m(y);
    A && (A.isCubeTexture || A.mapping === xr) ? (h === void 0 && (h = new Je(
      new Es(1, 1, 1),
      new Ci({
        name: "BackgroundCubeMaterial",
        uniforms: mr(si.backgroundCube.uniforms),
        vertexShader: si.backgroundCube.vertexShader,
        fragmentShader: si.backgroundCube.fragmentShader,
        side: zt,
        depthTest: !1,
        depthWrite: !1,
        fog: !1,
        allowOverride: !1
      })
    ), h.geometry.deleteAttribute("normal"), h.geometry.deleteAttribute("uv"), h.onBeforeRender = function(S, C, P) {
      this.matrixWorld.copyPosition(P.matrixWorld);
    }, Object.defineProperty(h.material, "envMap", {
      get: function() {
        return this.uniforms.envMap.value;
      }
    }), n.update(h)), ss.copy(y.backgroundRotation), ss.x *= -1, ss.y *= -1, ss.z *= -1, A.isCubeTexture && A.isRenderTargetTexture === !1 && (ss.y *= -1, ss.z *= -1), h.material.uniforms.envMap.value = A, h.material.uniforms.flipEnvMap.value = A.isCubeTexture && A.isRenderTargetTexture === !1 ? -1 : 1, h.material.uniforms.backgroundBlurriness.value = y.backgroundBlurriness, h.material.uniforms.backgroundIntensity.value = y.backgroundIntensity, h.material.uniforms.backgroundRotation.value.setFromMatrix4(Gb.makeRotationFromEuler(ss)), h.material.toneMapped = et.getTransfer(A.colorSpace) !== ut, (d !== A || u !== A.version || p !== r.toneMapping) && (h.material.needsUpdate = !0, d = A, u = A.version, p = r.toneMapping), h.layers.enableAll(), x.unshift(h, h.geometry, h.material, 0, 0, null)) : A && A.isTexture && (c === void 0 && (c = new Je(
      new Vn(2, 2),
      new Ci({
        name: "BackgroundMaterial",
        uniforms: mr(si.background.uniforms),
        vertexShader: si.background.vertexShader,
        fragmentShader: si.background.fragmentShader,
        side: Di,
        depthTest: !1,
        depthWrite: !1,
        fog: !1,
        allowOverride: !1
      })
    ), c.geometry.deleteAttribute("normal"), Object.defineProperty(c.material, "map", {
      get: function() {
        return this.uniforms.t2D.value;
      }
    }), n.update(c)), c.material.uniforms.t2D.value = A, c.material.uniforms.backgroundIntensity.value = y.backgroundIntensity, c.material.toneMapped = et.getTransfer(A.colorSpace) !== ut, A.matrixAutoUpdate === !0 && A.updateMatrix(), c.material.uniforms.uvTransform.value.copy(A.matrix), (d !== A || u !== A.version || p !== r.toneMapping) && (c.material.needsUpdate = !0, d = A, u = A.version, p = r.toneMapping), c.layers.enableAll(), x.unshift(c, c.geometry, c.material, 0, 0, null));
  }
  function f(x, y) {
    x.getRGB(vo, um(r)), i.buffers.color.setClear(vo.r, vo.g, vo.b, y, a);
  }
  function v() {
    h !== void 0 && (h.geometry.dispose(), h.material.dispose(), h = void 0), c !== void 0 && (c.geometry.dispose(), c.material.dispose(), c = void 0);
  }
  return {
    getClearColor: function() {
      return o;
    },
    setClearColor: function(x, y = 1) {
      o.set(x), l = y, f(o, l);
    },
    getClearAlpha: function() {
      return l;
    },
    setClearAlpha: function(x) {
      l = x, f(o, l);
    },
    render: _,
    addToRenderList: g,
    dispose: v
  };
}
function Xb(r, e) {
  const t = r.getParameter(r.MAX_VERTEX_ATTRIBS), i = {}, n = u(null);
  let s = n, a = !1;
  function o(w, L, N, B, W) {
    let Z = !1;
    const X = d(B, N, L);
    s !== X && (s = X, c(s.object)), Z = p(w, B, N, W), Z && m(w, B, N, W), W !== null && e.update(W, r.ELEMENT_ARRAY_BUFFER), (Z || a) && (a = !1, y(w, L, N, B), W !== null && r.bindBuffer(r.ELEMENT_ARRAY_BUFFER, e.get(W).buffer));
  }
  function l() {
    return r.createVertexArray();
  }
  function c(w) {
    return r.bindVertexArray(w);
  }
  function h(w) {
    return r.deleteVertexArray(w);
  }
  function d(w, L, N) {
    const B = N.wireframe === !0;
    let W = i[w.id];
    W === void 0 && (W = {}, i[w.id] = W);
    let Z = W[L.id];
    Z === void 0 && (Z = {}, W[L.id] = Z);
    let X = Z[B];
    return X === void 0 && (X = u(l()), Z[B] = X), X;
  }
  function u(w) {
    const L = [], N = [], B = [];
    for (let W = 0; W < t; W++)
      L[W] = 0, N[W] = 0, B[W] = 0;
    return {
      // for backward compatibility on non-VAO support browser
      geometry: null,
      program: null,
      wireframe: !1,
      newAttributes: L,
      enabledAttributes: N,
      attributeDivisors: B,
      object: w,
      attributes: {},
      index: null
    };
  }
  function p(w, L, N, B) {
    const W = s.attributes, Z = L.attributes;
    let X = 0;
    const ie = N.getAttributes();
    for (const G in ie)
      if (ie[G].location >= 0) {
        const me = W[G];
        let Se = Z[G];
        if (Se === void 0 && (G === "instanceMatrix" && w.instanceMatrix && (Se = w.instanceMatrix), G === "instanceColor" && w.instanceColor && (Se = w.instanceColor)), me === void 0 || me.attribute !== Se || Se && me.data !== Se.data) return !0;
        X++;
      }
    return s.attributesNum !== X || s.index !== B;
  }
  function m(w, L, N, B) {
    const W = {}, Z = L.attributes;
    let X = 0;
    const ie = N.getAttributes();
    for (const G in ie)
      if (ie[G].location >= 0) {
        let me = Z[G];
        me === void 0 && (G === "instanceMatrix" && w.instanceMatrix && (me = w.instanceMatrix), G === "instanceColor" && w.instanceColor && (me = w.instanceColor));
        const Se = {};
        Se.attribute = me, me && me.data && (Se.data = me.data), W[G] = Se, X++;
      }
    s.attributes = W, s.attributesNum = X, s.index = B;
  }
  function _() {
    const w = s.newAttributes;
    for (let L = 0, N = w.length; L < N; L++)
      w[L] = 0;
  }
  function g(w) {
    f(w, 0);
  }
  function f(w, L) {
    const N = s.newAttributes, B = s.enabledAttributes, W = s.attributeDivisors;
    N[w] = 1, B[w] === 0 && (r.enableVertexAttribArray(w), B[w] = 1), W[w] !== L && (r.vertexAttribDivisor(w, L), W[w] = L);
  }
  function v() {
    const w = s.newAttributes, L = s.enabledAttributes;
    for (let N = 0, B = L.length; N < B; N++)
      L[N] !== w[N] && (r.disableVertexAttribArray(N), L[N] = 0);
  }
  function x(w, L, N, B, W, Z, X) {
    X === !0 ? r.vertexAttribIPointer(w, L, N, W, Z) : r.vertexAttribPointer(w, L, N, B, W, Z);
  }
  function y(w, L, N, B) {
    _();
    const W = B.attributes, Z = N.getAttributes(), X = L.defaultAttributeValues;
    for (const ie in Z) {
      const G = Z[ie];
      if (G.location >= 0) {
        let he = W[ie];
        if (he === void 0 && (ie === "instanceMatrix" && w.instanceMatrix && (he = w.instanceMatrix), ie === "instanceColor" && w.instanceColor && (he = w.instanceColor)), he !== void 0) {
          const me = he.normalized, Se = he.itemSize, We = e.get(he);
          if (We === void 0) continue;
          const Qe = We.buffer, ht = We.type, nt = We.bytesPerElement, Y = ht === r.INT || ht === r.UNSIGNED_INT || he.gpuType === Fl;
          if (he.isInterleavedBufferAttribute) {
            const te = he.data, be = te.stride, Le = he.offset;
            if (te.isInstancedInterleavedBuffer) {
              for (let Ee = 0; Ee < G.locationSize; Ee++)
                f(G.location + Ee, te.meshPerAttribute);
              w.isInstancedMesh !== !0 && B._maxInstanceCount === void 0 && (B._maxInstanceCount = te.meshPerAttribute * te.count);
            } else
              for (let Ee = 0; Ee < G.locationSize; Ee++)
                g(G.location + Ee);
            r.bindBuffer(r.ARRAY_BUFFER, Qe);
            for (let Ee = 0; Ee < G.locationSize; Ee++)
              x(
                G.location + Ee,
                Se / G.locationSize,
                ht,
                me,
                be * nt,
                (Le + Se / G.locationSize * Ee) * nt,
                Y
              );
          } else {
            if (he.isInstancedBufferAttribute) {
              for (let te = 0; te < G.locationSize; te++)
                f(G.location + te, he.meshPerAttribute);
              w.isInstancedMesh !== !0 && B._maxInstanceCount === void 0 && (B._maxInstanceCount = he.meshPerAttribute * he.count);
            } else
              for (let te = 0; te < G.locationSize; te++)
                g(G.location + te);
            r.bindBuffer(r.ARRAY_BUFFER, Qe);
            for (let te = 0; te < G.locationSize; te++)
              x(
                G.location + te,
                Se / G.locationSize,
                ht,
                me,
                Se * nt,
                Se / G.locationSize * te * nt,
                Y
              );
          }
        } else if (X !== void 0) {
          const me = X[ie];
          if (me !== void 0)
            switch (me.length) {
              case 2:
                r.vertexAttrib2fv(G.location, me);
                break;
              case 3:
                r.vertexAttrib3fv(G.location, me);
                break;
              case 4:
                r.vertexAttrib4fv(G.location, me);
                break;
              default:
                r.vertexAttrib1fv(G.location, me);
            }
        }
      }
    }
    v();
  }
  function A() {
    P();
    for (const w in i) {
      const L = i[w];
      for (const N in L) {
        const B = L[N];
        for (const W in B)
          h(B[W].object), delete B[W];
        delete L[N];
      }
      delete i[w];
    }
  }
  function S(w) {
    if (i[w.id] === void 0) return;
    const L = i[w.id];
    for (const N in L) {
      const B = L[N];
      for (const W in B)
        h(B[W].object), delete B[W];
      delete L[N];
    }
    delete i[w.id];
  }
  function C(w) {
    for (const L in i) {
      const N = i[L];
      if (N[w.id] === void 0) continue;
      const B = N[w.id];
      for (const W in B)
        h(B[W].object), delete B[W];
      delete N[w.id];
    }
  }
  function P() {
    E(), a = !0, s !== n && (s = n, c(s.object));
  }
  function E() {
    n.geometry = null, n.program = null, n.wireframe = !1;
  }
  return {
    setup: o,
    reset: P,
    resetDefaultState: E,
    dispose: A,
    releaseStatesOfGeometry: S,
    releaseStatesOfProgram: C,
    initAttributes: _,
    enableAttribute: g,
    disableUnusedAttributes: v
  };
}
function qb(r, e, t) {
  let i;
  function n(c) {
    i = c;
  }
  function s(c, h) {
    r.drawArrays(i, c, h), t.update(h, i, 1);
  }
  function a(c, h, d) {
    d !== 0 && (r.drawArraysInstanced(i, c, h, d), t.update(h, i, d));
  }
  function o(c, h, d) {
    if (d === 0) return;
    e.get("WEBGL_multi_draw").multiDrawArraysWEBGL(i, c, 0, h, 0, d);
    let p = 0;
    for (let m = 0; m < d; m++)
      p += h[m];
    t.update(p, i, 1);
  }
  function l(c, h, d, u) {
    if (d === 0) return;
    const p = e.get("WEBGL_multi_draw");
    if (p === null)
      for (let m = 0; m < c.length; m++)
        a(c[m], h[m], u[m]);
    else {
      p.multiDrawArraysInstancedWEBGL(i, c, 0, h, 0, u, 0, d);
      let m = 0;
      for (let _ = 0; _ < d; _++)
        m += h[_] * u[_];
      t.update(m, i, 1);
    }
  }
  this.setMode = n, this.render = s, this.renderInstances = a, this.renderMultiDraw = o, this.renderMultiDrawInstances = l;
}
function Zb(r, e, t, i) {
  let n;
  function s() {
    if (n !== void 0) return n;
    if (e.has("EXT_texture_filter_anisotropic") === !0) {
      const C = e.get("EXT_texture_filter_anisotropic");
      n = r.getParameter(C.MAX_TEXTURE_MAX_ANISOTROPY_EXT);
    } else
      n = 0;
    return n;
  }
  function a(C) {
    return !(C !== oi && i.convert(C) !== r.getParameter(r.IMPLEMENTATION_COLOR_READ_FORMAT));
  }
  function o(C) {
    const P = C === br && (e.has("EXT_color_buffer_half_float") || e.has("EXT_color_buffer_float"));
    return !(C !== Hi && i.convert(C) !== r.getParameter(r.IMPLEMENTATION_COLOR_READ_TYPE) && // Edge and Chrome Mac < 52 (#9513)
    C !== mi && !P);
  }
  function l(C) {
    if (C === "highp") {
      if (r.getShaderPrecisionFormat(r.VERTEX_SHADER, r.HIGH_FLOAT).precision > 0 && r.getShaderPrecisionFormat(r.FRAGMENT_SHADER, r.HIGH_FLOAT).precision > 0)
        return "highp";
      C = "mediump";
    }
    return C === "mediump" && r.getShaderPrecisionFormat(r.VERTEX_SHADER, r.MEDIUM_FLOAT).precision > 0 && r.getShaderPrecisionFormat(r.FRAGMENT_SHADER, r.MEDIUM_FLOAT).precision > 0 ? "mediump" : "lowp";
  }
  let c = t.precision !== void 0 ? t.precision : "highp";
  const h = l(c);
  h !== c && (console.warn("THREE.WebGLRenderer:", c, "not supported, using", h, "instead."), c = h);
  const d = t.logarithmicDepthBuffer === !0, u = t.reversedDepthBuffer === !0 && e.has("EXT_clip_control"), p = r.getParameter(r.MAX_TEXTURE_IMAGE_UNITS), m = r.getParameter(r.MAX_VERTEX_TEXTURE_IMAGE_UNITS), _ = r.getParameter(r.MAX_TEXTURE_SIZE), g = r.getParameter(r.MAX_CUBE_MAP_TEXTURE_SIZE), f = r.getParameter(r.MAX_VERTEX_ATTRIBS), v = r.getParameter(r.MAX_VERTEX_UNIFORM_VECTORS), x = r.getParameter(r.MAX_VARYING_VECTORS), y = r.getParameter(r.MAX_FRAGMENT_UNIFORM_VECTORS), A = m > 0, S = r.getParameter(r.MAX_SAMPLES);
  return {
    isWebGL2: !0,
    // keeping this for backwards compatibility
    getMaxAnisotropy: s,
    getMaxPrecision: l,
    textureFormatReadable: a,
    textureTypeReadable: o,
    precision: c,
    logarithmicDepthBuffer: d,
    reversedDepthBuffer: u,
    maxTextures: p,
    maxVertexTextures: m,
    maxTextureSize: _,
    maxCubemapSize: g,
    maxAttributes: f,
    maxVertexUniforms: v,
    maxVaryings: x,
    maxFragmentUniforms: y,
    vertexTextures: A,
    maxSamples: S
  };
}
function Yb(r) {
  const e = this;
  let t = null, i = 0, n = !1, s = !1;
  const a = new $i(), o = new He(), l = { value: null, needsUpdate: !1 };
  this.uniform = l, this.numPlanes = 0, this.numIntersection = 0, this.init = function(d, u) {
    const p = d.length !== 0 || u || // enable state of previous frame - the clipping code has to
    // run another frame in order to reset the state:
    i !== 0 || n;
    return n = u, i = d.length, p;
  }, this.beginShadows = function() {
    s = !0, h(null);
  }, this.endShadows = function() {
    s = !1;
  }, this.setGlobalState = function(d, u) {
    t = h(d, u, 0);
  }, this.setState = function(d, u, p) {
    const m = d.clippingPlanes, _ = d.clipIntersection, g = d.clipShadows, f = r.get(d);
    if (!n || m === null || m.length === 0 || s && !g)
      s ? h(null) : c();
    else {
      const v = s ? 0 : i, x = v * 4;
      let y = f.clippingState || null;
      l.value = y, y = h(m, u, x, p);
      for (let A = 0; A !== x; ++A)
        y[A] = t[A];
      f.clippingState = y, this.numIntersection = _ ? this.numPlanes : 0, this.numPlanes += v;
    }
  };
  function c() {
    l.value !== t && (l.value = t, l.needsUpdate = i > 0), e.numPlanes = i, e.numIntersection = 0;
  }
  function h(d, u, p, m) {
    const _ = d !== null ? d.length : 0;
    let g = null;
    if (_ !== 0) {
      if (g = l.value, m !== !0 || g === null) {
        const f = p + _ * 4, v = u.matrixWorldInverse;
        o.getNormalMatrix(v), (g === null || g.length < f) && (g = new Float32Array(f));
        for (let x = 0, y = p; x !== _; ++x, y += 4)
          a.copy(d[x]).applyMatrix4(v, o), a.normal.toArray(g, y), g[y + 3] = a.constant;
      }
      l.value = g, l.needsUpdate = !0;
    }
    return e.numPlanes = _, e.numIntersection = 0, g;
  }
}
function jb(r) {
  let e = /* @__PURE__ */ new WeakMap();
  function t(a, o) {
    return o === na ? a.mapping = _n : o === sa && (a.mapping = Un), a;
  }
  function i(a) {
    if (a && a.isTexture) {
      const o = a.mapping;
      if (o === na || o === sa)
        if (e.has(a)) {
          const l = e.get(a).texture;
          return t(l, a.mapping);
        } else {
          const l = a.image;
          if (l && l.height > 0) {
            const c = new fm(l.height);
            return c.fromEquirectangularTexture(r, a), e.set(a, c), a.addEventListener("dispose", n), t(c.texture, a.mapping);
          } else
            return null;
        }
    }
    return a;
  }
  function n(a) {
    const o = a.target;
    o.removeEventListener("dispose", n);
    const l = e.get(o);
    l !== void 0 && (e.delete(o), l.dispose());
  }
  function s() {
    e = /* @__PURE__ */ new WeakMap();
  }
  return {
    get: i,
    dispose: s
  };
}
const rr = 4, lp = [0.125, 0.215, 0.35, 0.446, 0.526, 0.582], cs = 20, sh = /* @__PURE__ */ new kn(), cp = /* @__PURE__ */ new oe();
let rh = null, ah = 0, oh = 0, lh = !1;
const ls = (1 + Math.sqrt(5)) / 2, $s = 1 / ls, hp = [
  /* @__PURE__ */ new b(-ls, $s, 0),
  /* @__PURE__ */ new b(ls, $s, 0),
  /* @__PURE__ */ new b(-$s, 0, ls),
  /* @__PURE__ */ new b($s, 0, ls),
  /* @__PURE__ */ new b(0, ls, -$s),
  /* @__PURE__ */ new b(0, ls, $s),
  /* @__PURE__ */ new b(-1, 1, -1),
  /* @__PURE__ */ new b(1, 1, -1),
  /* @__PURE__ */ new b(-1, 1, 1),
  /* @__PURE__ */ new b(1, 1, 1)
], $b = /* @__PURE__ */ new b();
class Wh {
  /**
   * Constructs a new PMREM generator.
   *
   * @param {WebGLRenderer} renderer - The renderer.
   */
  constructor(e) {
    this._renderer = e, this._pingPongRenderTarget = null, this._lodMax = 0, this._cubeSize = 0, this._lodPlanes = [], this._sizeLods = [], this._sigmas = [], this._blurMaterial = null, this._cubemapMaterial = null, this._equirectMaterial = null, this._compileMaterial(this._blurMaterial);
  }
  /**
   * Generates a PMREM from a supplied Scene, which can be faster than using an
   * image if networking bandwidth is low. Optional sigma specifies a blur radius
   * in radians to be applied to the scene before PMREM generation. Optional near
   * and far planes ensure the scene is rendered in its entirety.
   *
   * @param {Scene} scene - The scene to be captured.
   * @param {number} [sigma=0] - The blur radius in radians.
   * @param {number} [near=0.1] - The near plane distance.
   * @param {number} [far=100] - The far plane distance.
   * @param {Object} [options={}] - The configuration options.
   * @param {number} [options.size=256] - The texture size of the PMREM.
   * @param {Vector3} [options.renderTarget=origin] - The position of the internal cube camera that renders the scene.
   * @return {WebGLRenderTarget} The resulting PMREM.
   */
  fromScene(e, t = 0, i = 0.1, n = 100, s = {}) {
    const {
      size: a = 256,
      position: o = $b
    } = s;
    rh = this._renderer.getRenderTarget(), ah = this._renderer.getActiveCubeFace(), oh = this._renderer.getActiveMipmapLevel(), lh = this._renderer.xr.enabled, this._renderer.xr.enabled = !1, this._setSize(a);
    const l = this._allocateTargets();
    return l.depthBuffer = !0, this._sceneToCubeUV(e, i, n, l, o), t > 0 && this._blur(l, 0, 0, t), this._applyPMREM(l), this._cleanup(l), l;
  }
  /**
   * Generates a PMREM from an equirectangular texture, which can be either LDR
   * or HDR. The ideal input image size is 1k (1024 x 512),
   * as this matches best with the 256 x 256 cubemap output.
   *
   * @param {Texture} equirectangular - The equirectangular texture to be converted.
   * @param {?WebGLRenderTarget} [renderTarget=null] - The render target to use.
   * @return {WebGLRenderTarget} The resulting PMREM.
   */
  fromEquirectangular(e, t = null) {
    return this._fromTexture(e, t);
  }
  /**
   * Generates a PMREM from an cubemap texture, which can be either LDR
   * or HDR. The ideal input cube size is 256 x 256,
   * as this matches best with the 256 x 256 cubemap output.
   *
   * @param {Texture} cubemap - The cubemap texture to be converted.
   * @param {?WebGLRenderTarget} [renderTarget=null] - The render target to use.
   * @return {WebGLRenderTarget} The resulting PMREM.
   */
  fromCubemap(e, t = null) {
    return this._fromTexture(e, t);
  }
  /**
   * Pre-compiles the cubemap shader. You can get faster start-up by invoking this method during
   * your texture's network fetch for increased concurrency.
   */
  compileCubemapShader() {
    this._cubemapMaterial === null && (this._cubemapMaterial = pp(), this._compileMaterial(this._cubemapMaterial));
  }
  /**
   * Pre-compiles the equirectangular shader. You can get faster start-up by invoking this method during
   * your texture's network fetch for increased concurrency.
   */
  compileEquirectangularShader() {
    this._equirectMaterial === null && (this._equirectMaterial = up(), this._compileMaterial(this._equirectMaterial));
  }
  /**
   * Disposes of the PMREMGenerator's internal memory. Note that PMREMGenerator is a static class,
   * so you should not need more than one PMREMGenerator object. If you do, calling dispose() on
   * one of them will cause any others to also become unusable.
   */
  dispose() {
    this._dispose(), this._cubemapMaterial !== null && this._cubemapMaterial.dispose(), this._equirectMaterial !== null && this._equirectMaterial.dispose();
  }
  // private interface
  _setSize(e) {
    this._lodMax = Math.floor(Math.log2(e)), this._cubeSize = Math.pow(2, this._lodMax);
  }
  _dispose() {
    this._blurMaterial !== null && this._blurMaterial.dispose(), this._pingPongRenderTarget !== null && this._pingPongRenderTarget.dispose();
    for (let e = 0; e < this._lodPlanes.length; e++)
      this._lodPlanes[e].dispose();
  }
  _cleanup(e) {
    this._renderer.setRenderTarget(rh, ah, oh), this._renderer.xr.enabled = lh, e.scissorTest = !1, xo(e, 0, 0, e.width, e.height);
  }
  _fromTexture(e, t) {
    e.mapping === _n || e.mapping === Un ? this._setSize(e.image.length === 0 ? 16 : e.image[0].width || e.image[0].image.width) : this._setSize(e.image.width / 4), rh = this._renderer.getRenderTarget(), ah = this._renderer.getActiveCubeFace(), oh = this._renderer.getActiveMipmapLevel(), lh = this._renderer.xr.enabled, this._renderer.xr.enabled = !1;
    const i = t || this._allocateTargets();
    return this._textureToCubeUV(e, i), this._applyPMREM(i), this._cleanup(i), i;
  }
  _allocateTargets() {
    const e = 3 * Math.max(this._cubeSize, 112), t = 4 * this._cubeSize, i = {
      magFilter: Pt,
      minFilter: Pt,
      generateMipmaps: !1,
      type: br,
      format: oi,
      colorSpace: On,
      depthBuffer: !1
    }, n = dp(e, t, i);
    if (this._pingPongRenderTarget === null || this._pingPongRenderTarget.width !== e || this._pingPongRenderTarget.height !== t) {
      this._pingPongRenderTarget !== null && this._dispose(), this._pingPongRenderTarget = dp(e, t, i);
      const { _lodMax: s } = this;
      ({ sizeLods: this._sizeLods, lodPlanes: this._lodPlanes, sigmas: this._sigmas } = Kb(s)), this._blurMaterial = Jb(s, e, t);
    }
    return n;
  }
  _compileMaterial(e) {
    const t = new Je(this._lodPlanes[0], e);
    this._renderer.compile(t, sh);
  }
  _sceneToCubeUV(e, t, i, n, s) {
    const l = new kt(90, 1, t, i), c = [1, -1, 1, 1, 1, 1], h = [1, 1, 1, -1, -1, -1], d = this._renderer, u = d.autoClear, p = d.toneMapping;
    d.getClearColor(cp), d.toneMapping = mn, d.autoClear = !1, d.state.buffers.depth.getReversed() && (d.setRenderTarget(n), d.clearDepth(), d.setRenderTarget(null));
    const _ = new Ht({
      name: "PMREM.Background",
      side: zt,
      depthWrite: !1,
      depthTest: !1
    }), g = new Je(new Es(), _);
    let f = !1;
    const v = e.background;
    v ? v.isColor && (_.color.copy(v), e.background = null, f = !0) : (_.color.copy(cp), f = !0);
    for (let x = 0; x < 6; x++) {
      const y = x % 3;
      y === 0 ? (l.up.set(0, c[x], 0), l.position.set(s.x, s.y, s.z), l.lookAt(s.x + h[x], s.y, s.z)) : y === 1 ? (l.up.set(0, 0, c[x]), l.position.set(s.x, s.y, s.z), l.lookAt(s.x, s.y + h[x], s.z)) : (l.up.set(0, c[x], 0), l.position.set(s.x, s.y, s.z), l.lookAt(s.x, s.y, s.z + h[x]));
      const A = this._cubeSize;
      xo(n, y * A, x > 2 ? A : 0, A, A), d.setRenderTarget(n), f && d.render(g, l), d.render(e, l);
    }
    g.geometry.dispose(), g.material.dispose(), d.toneMapping = p, d.autoClear = u, e.background = v;
  }
  _textureToCubeUV(e, t) {
    const i = this._renderer, n = e.mapping === _n || e.mapping === Un;
    n ? (this._cubemapMaterial === null && (this._cubemapMaterial = pp()), this._cubemapMaterial.uniforms.flipEnvMap.value = e.isRenderTargetTexture === !1 ? -1 : 1) : this._equirectMaterial === null && (this._equirectMaterial = up());
    const s = n ? this._cubemapMaterial : this._equirectMaterial, a = new Je(this._lodPlanes[0], s), o = s.uniforms;
    o.envMap.value = e;
    const l = this._cubeSize;
    xo(t, 0, 0, 3 * l, 2 * l), i.setRenderTarget(t), i.render(a, sh);
  }
  _applyPMREM(e) {
    const t = this._renderer, i = t.autoClear;
    t.autoClear = !1;
    const n = this._lodPlanes.length;
    for (let s = 1; s < n; s++) {
      const a = Math.sqrt(this._sigmas[s] * this._sigmas[s] - this._sigmas[s - 1] * this._sigmas[s - 1]), o = hp[(n - s - 1) % hp.length];
      this._blur(e, s - 1, s, a, o);
    }
    t.autoClear = i;
  }
  /**
   * This is a two-pass Gaussian blur for a cubemap. Normally this is done
   * vertically and horizontally, but this breaks down on a cube. Here we apply
   * the blur latitudinally (around the poles), and then longitudinally (towards
   * the poles) to approximate the orthogonally-separable blur. It is least
   * accurate at the poles, but still does a decent job.
   *
   * @private
   * @param {WebGLRenderTarget} cubeUVRenderTarget
   * @param {number} lodIn
   * @param {number} lodOut
   * @param {number} sigma
   * @param {Vector3} [poleAxis]
   */
  _blur(e, t, i, n, s) {
    const a = this._pingPongRenderTarget;
    this._halfBlur(
      e,
      a,
      t,
      i,
      n,
      "latitudinal",
      s
    ), this._halfBlur(
      a,
      e,
      i,
      i,
      n,
      "longitudinal",
      s
    );
  }
  _halfBlur(e, t, i, n, s, a, o) {
    const l = this._renderer, c = this._blurMaterial;
    a !== "latitudinal" && a !== "longitudinal" && console.error(
      "blur direction must be either latitudinal or longitudinal!"
    );
    const h = 3, d = new Je(this._lodPlanes[n], c), u = c.uniforms, p = this._sizeLods[i] - 1, m = isFinite(s) ? Math.PI / (2 * p) : 2 * Math.PI / (2 * cs - 1), _ = s / m, g = isFinite(s) ? 1 + Math.floor(h * _) : cs;
    g > cs && console.warn(`sigmaRadians, ${s}, is too large and will clip, as it requested ${g} samples when the maximum is set to ${cs}`);
    const f = [];
    let v = 0;
    for (let C = 0; C < cs; ++C) {
      const P = C / _, E = Math.exp(-P * P / 2);
      f.push(E), C === 0 ? v += E : C < g && (v += 2 * E);
    }
    for (let C = 0; C < f.length; C++)
      f[C] = f[C] / v;
    u.envMap.value = e.texture, u.samples.value = g, u.weights.value = f, u.latitudinal.value = a === "latitudinal", o && (u.poleAxis.value = o);
    const { _lodMax: x } = this;
    u.dTheta.value = m, u.mipInt.value = x - i;
    const y = this._sizeLods[n], A = 3 * y * (n > x - rr ? n - x + rr : 0), S = 4 * (this._cubeSize - y);
    xo(t, A, S, 3 * y, 2 * y), l.setRenderTarget(t), l.render(d, sh);
  }
}
function Kb(r) {
  const e = [], t = [], i = [];
  let n = r;
  const s = r - rr + 1 + lp.length;
  for (let a = 0; a < s; a++) {
    const o = Math.pow(2, n);
    t.push(o);
    let l = 1 / o;
    a > r - rr ? l = lp[a - r + rr - 1] : a === 0 && (l = 0), i.push(l);
    const c = 1 / (o - 2), h = -c, d = 1 + c, u = [h, h, d, h, d, d, h, h, d, d, h, d], p = 6, m = 6, _ = 3, g = 2, f = 1, v = new Float32Array(_ * m * p), x = new Float32Array(g * m * p), y = new Float32Array(f * m * p);
    for (let S = 0; S < p; S++) {
      const C = S % 3 * 2 / 3 - 1, P = S > 2 ? 0 : -1, E = [
        C,
        P,
        0,
        C + 2 / 3,
        P,
        0,
        C + 2 / 3,
        P + 1,
        0,
        C,
        P,
        0,
        C + 2 / 3,
        P + 1,
        0,
        C,
        P + 1,
        0
      ];
      v.set(E, _ * m * S), x.set(u, g * m * S);
      const w = [S, S, S, S, S, S];
      y.set(w, f * m * S);
    }
    const A = new Ue();
    A.setAttribute("position", new it(v, _)), A.setAttribute("uv", new it(x, g)), A.setAttribute("faceIndex", new it(y, f)), e.push(A), n > rr && n--;
  }
  return { lodPlanes: e, sizeLods: t, sigmas: i };
}
function dp(r, e, t) {
  const i = new nn(r, e, t);
  return i.texture.mapping = xr, i.texture.name = "PMREM.cubeUv", i.scissorTest = !0, i;
}
function xo(r, e, t, i, n) {
  r.viewport.set(e, t, i, n), r.scissor.set(e, t, i, n);
}
function Jb(r, e, t) {
  const i = new Float32Array(cs), n = new b(0, 1, 0);
  return new Ci({
    name: "SphericalGaussianBlur",
    defines: {
      n: cs,
      CUBEUV_TEXEL_WIDTH: 1 / e,
      CUBEUV_TEXEL_HEIGHT: 1 / t,
      CUBEUV_MAX_MIP: `${r}.0`
    },
    uniforms: {
      envMap: { value: null },
      samples: { value: 1 },
      weights: { value: i },
      latitudinal: { value: !1 },
      dTheta: { value: 0 },
      mipInt: { value: 0 },
      poleAxis: { value: n }
    },
    vertexShader: Hd(),
    fragmentShader: (
      /* glsl */
      `

			precision mediump float;
			precision mediump int;

			varying vec3 vOutputDirection;

			uniform sampler2D envMap;
			uniform int samples;
			uniform float weights[ n ];
			uniform bool latitudinal;
			uniform float dTheta;
			uniform float mipInt;
			uniform vec3 poleAxis;

			#define ENVMAP_TYPE_CUBE_UV
			#include <cube_uv_reflection_fragment>

			vec3 getSample( float theta, vec3 axis ) {

				float cosTheta = cos( theta );
				// Rodrigues' axis-angle rotation
				vec3 sampleDirection = vOutputDirection * cosTheta
					+ cross( axis, vOutputDirection ) * sin( theta )
					+ axis * dot( axis, vOutputDirection ) * ( 1.0 - cosTheta );

				return bilinearCubeUV( envMap, sampleDirection, mipInt );

			}

			void main() {

				vec3 axis = latitudinal ? poleAxis : cross( poleAxis, vOutputDirection );

				if ( all( equal( axis, vec3( 0.0 ) ) ) ) {

					axis = vec3( vOutputDirection.z, 0.0, - vOutputDirection.x );

				}

				axis = normalize( axis );

				gl_FragColor = vec4( 0.0, 0.0, 0.0, 1.0 );
				gl_FragColor.rgb += weights[ 0 ] * getSample( 0.0, axis );

				for ( int i = 1; i < n; i++ ) {

					if ( i >= samples ) {

						break;

					}

					float theta = dTheta * float( i );
					gl_FragColor.rgb += weights[ i ] * getSample( -1.0 * theta, axis );
					gl_FragColor.rgb += weights[ i ] * getSample( theta, axis );

				}

			}
		`
    ),
    blending: fn,
    depthTest: !1,
    depthWrite: !1
  });
}
function up() {
  return new Ci({
    name: "EquirectangularToCubeUV",
    uniforms: {
      envMap: { value: null }
    },
    vertexShader: Hd(),
    fragmentShader: (
      /* glsl */
      `

			precision mediump float;
			precision mediump int;

			varying vec3 vOutputDirection;

			uniform sampler2D envMap;

			#include <common>

			void main() {

				vec3 outputDirection = normalize( vOutputDirection );
				vec2 uv = equirectUv( outputDirection );

				gl_FragColor = vec4( texture2D ( envMap, uv ).rgb, 1.0 );

			}
		`
    ),
    blending: fn,
    depthTest: !1,
    depthWrite: !1
  });
}
function pp() {
  return new Ci({
    name: "CubemapToCubeUV",
    uniforms: {
      envMap: { value: null },
      flipEnvMap: { value: -1 }
    },
    vertexShader: Hd(),
    fragmentShader: (
      /* glsl */
      `

			precision mediump float;
			precision mediump int;

			uniform float flipEnvMap;

			varying vec3 vOutputDirection;

			uniform samplerCube envMap;

			void main() {

				gl_FragColor = textureCube( envMap, vec3( flipEnvMap * vOutputDirection.x, vOutputDirection.yz ) );

			}
		`
    ),
    blending: fn,
    depthTest: !1,
    depthWrite: !1
  });
}
function Hd() {
  return (
    /* glsl */
    `

		precision mediump float;
		precision mediump int;

		attribute float faceIndex;

		varying vec3 vOutputDirection;

		// RH coordinate system; PMREM face-indexing convention
		vec3 getDirection( vec2 uv, float face ) {

			uv = 2.0 * uv - 1.0;

			vec3 direction = vec3( uv, 1.0 );

			if ( face == 0.0 ) {

				direction = direction.zyx; // ( 1, v, u ) pos x

			} else if ( face == 1.0 ) {

				direction = direction.xzy;
				direction.xz *= -1.0; // ( -u, 1, -v ) pos y

			} else if ( face == 2.0 ) {

				direction.x *= -1.0; // ( -u, v, 1 ) pos z

			} else if ( face == 3.0 ) {

				direction = direction.zyx;
				direction.xz *= -1.0; // ( -1, v, -u ) neg x

			} else if ( face == 4.0 ) {

				direction = direction.xzy;
				direction.xy *= -1.0; // ( -u, -1, v ) neg y

			} else if ( face == 5.0 ) {

				direction.z *= -1.0; // ( u, v, -1 ) neg z

			}

			return direction;

		}

		void main() {

			vOutputDirection = getDirection( uv, faceIndex );
			gl_Position = vec4( position, 1.0 );

		}
	`
  );
}
function Qb(r) {
  let e = /* @__PURE__ */ new WeakMap(), t = null;
  function i(o) {
    if (o && o.isTexture) {
      const l = o.mapping, c = l === na || l === sa, h = l === _n || l === Un;
      if (c || h) {
        let d = e.get(o);
        const u = d !== void 0 ? d.texture.pmremVersion : 0;
        if (o.isRenderTargetTexture && o.pmremVersion !== u)
          return t === null && (t = new Wh(r)), d = c ? t.fromEquirectangular(o, d) : t.fromCubemap(o, d), d.texture.pmremVersion = o.pmremVersion, e.set(o, d), d.texture;
        if (d !== void 0)
          return d.texture;
        {
          const p = o.image;
          return c && p && p.height > 0 || h && p && n(p) ? (t === null && (t = new Wh(r)), d = c ? t.fromEquirectangular(o) : t.fromCubemap(o), d.texture.pmremVersion = o.pmremVersion, e.set(o, d), o.addEventListener("dispose", s), d.texture) : null;
        }
      }
    }
    return o;
  }
  function n(o) {
    let l = 0;
    const c = 6;
    for (let h = 0; h < c; h++)
      o[h] !== void 0 && l++;
    return l === c;
  }
  function s(o) {
    const l = o.target;
    l.removeEventListener("dispose", s);
    const c = e.get(l);
    c !== void 0 && (e.delete(l), c.dispose());
  }
  function a() {
    e = /* @__PURE__ */ new WeakMap(), t !== null && (t.dispose(), t = null);
  }
  return {
    get: i,
    dispose: a
  };
}
function eS(r) {
  const e = {};
  function t(i) {
    if (e[i] !== void 0)
      return e[i];
    let n;
    switch (i) {
      case "WEBGL_depth_texture":
        n = r.getExtension("WEBGL_depth_texture") || r.getExtension("MOZ_WEBGL_depth_texture") || r.getExtension("WEBKIT_WEBGL_depth_texture");
        break;
      case "EXT_texture_filter_anisotropic":
        n = r.getExtension("EXT_texture_filter_anisotropic") || r.getExtension("MOZ_EXT_texture_filter_anisotropic") || r.getExtension("WEBKIT_EXT_texture_filter_anisotropic");
        break;
      case "WEBGL_compressed_texture_s3tc":
        n = r.getExtension("WEBGL_compressed_texture_s3tc") || r.getExtension("MOZ_WEBGL_compressed_texture_s3tc") || r.getExtension("WEBKIT_WEBGL_compressed_texture_s3tc");
        break;
      case "WEBGL_compressed_texture_pvrtc":
        n = r.getExtension("WEBGL_compressed_texture_pvrtc") || r.getExtension("WEBKIT_WEBGL_compressed_texture_pvrtc");
        break;
      default:
        n = r.getExtension(i);
    }
    return e[i] = n, n;
  }
  return {
    has: function(i) {
      return t(i) !== null;
    },
    init: function() {
      t("EXT_color_buffer_float"), t("WEBGL_clip_cull_distance"), t("OES_texture_float_linear"), t("EXT_color_buffer_half_float"), t("WEBGL_multisampled_render_to_texture"), t("WEBGL_render_shared_exponent");
    },
    get: function(i) {
      const n = t(i);
      return n === null && pa("THREE.WebGLRenderer: " + i + " extension not supported."), n;
    }
  };
}
function tS(r, e, t, i) {
  const n = {}, s = /* @__PURE__ */ new WeakMap();
  function a(d) {
    const u = d.target;
    u.index !== null && e.remove(u.index);
    for (const m in u.attributes)
      e.remove(u.attributes[m]);
    u.removeEventListener("dispose", a), delete n[u.id];
    const p = s.get(u);
    p && (e.remove(p), s.delete(u)), i.releaseStatesOfGeometry(u), u.isInstancedBufferGeometry === !0 && delete u._maxInstanceCount, t.memory.geometries--;
  }
  function o(d, u) {
    return n[u.id] === !0 || (u.addEventListener("dispose", a), n[u.id] = !0, t.memory.geometries++), u;
  }
  function l(d) {
    const u = d.attributes;
    for (const p in u)
      e.update(u[p], r.ARRAY_BUFFER);
  }
  function c(d) {
    const u = [], p = d.index, m = d.attributes.position;
    let _ = 0;
    if (p !== null) {
      const v = p.array;
      _ = p.version;
      for (let x = 0, y = v.length; x < y; x += 3) {
        const A = v[x + 0], S = v[x + 1], C = v[x + 2];
        u.push(A, S, S, C, C, A);
      }
    } else if (m !== void 0) {
      const v = m.array;
      _ = m.version;
      for (let x = 0, y = v.length / 3 - 1; x < y; x += 3) {
        const A = x + 0, S = x + 1, C = x + 2;
        u.push(A, S, S, C, C, A);
      }
    } else
      return;
    const g = new (lm(u) ? dd : hd)(u, 1);
    g.version = _;
    const f = s.get(d);
    f && e.remove(f), s.set(d, g);
  }
  function h(d) {
    const u = s.get(d);
    if (u) {
      const p = d.index;
      p !== null && u.version < p.version && c(d);
    } else
      c(d);
    return s.get(d);
  }
  return {
    get: o,
    update: l,
    getWireframeAttribute: h
  };
}
function iS(r, e, t) {
  let i;
  function n(u) {
    i = u;
  }
  let s, a;
  function o(u) {
    s = u.type, a = u.bytesPerElement;
  }
  function l(u, p) {
    r.drawElements(i, p, s, u * a), t.update(p, i, 1);
  }
  function c(u, p, m) {
    m !== 0 && (r.drawElementsInstanced(i, p, s, u * a, m), t.update(p, i, m));
  }
  function h(u, p, m) {
    if (m === 0) return;
    e.get("WEBGL_multi_draw").multiDrawElementsWEBGL(i, p, 0, s, u, 0, m);
    let g = 0;
    for (let f = 0; f < m; f++)
      g += p[f];
    t.update(g, i, 1);
  }
  function d(u, p, m, _) {
    if (m === 0) return;
    const g = e.get("WEBGL_multi_draw");
    if (g === null)
      for (let f = 0; f < u.length; f++)
        c(u[f] / a, p[f], _[f]);
    else {
      g.multiDrawElementsInstancedWEBGL(i, p, 0, s, u, 0, _, 0, m);
      let f = 0;
      for (let v = 0; v < m; v++)
        f += p[v] * _[v];
      t.update(f, i, 1);
    }
  }
  this.setMode = n, this.setIndex = o, this.render = l, this.renderInstances = c, this.renderMultiDraw = h, this.renderMultiDrawInstances = d;
}
function nS(r) {
  const e = {
    geometries: 0,
    textures: 0
  }, t = {
    frame: 0,
    calls: 0,
    triangles: 0,
    points: 0,
    lines: 0
  };
  function i(s, a, o) {
    switch (t.calls++, a) {
      case r.TRIANGLES:
        t.triangles += o * (s / 3);
        break;
      case r.LINES:
        t.lines += o * (s / 2);
        break;
      case r.LINE_STRIP:
        t.lines += o * (s - 1);
        break;
      case r.LINE_LOOP:
        t.lines += o * s;
        break;
      case r.POINTS:
        t.points += o * s;
        break;
      default:
        console.error("THREE.WebGLInfo: Unknown draw mode:", a);
        break;
    }
  }
  function n() {
    t.calls = 0, t.triangles = 0, t.points = 0, t.lines = 0;
  }
  return {
    memory: e,
    render: t,
    programs: null,
    autoReset: !0,
    reset: n,
    update: i
  };
}
function sS(r, e, t) {
  const i = /* @__PURE__ */ new WeakMap(), n = new Ye();
  function s(a, o, l) {
    const c = a.morphTargetInfluences, h = o.morphAttributes.position || o.morphAttributes.normal || o.morphAttributes.color, d = h !== void 0 ? h.length : 0;
    let u = i.get(o);
    if (u === void 0 || u.count !== d) {
      let E = function() {
        C.dispose(), i.delete(o), o.removeEventListener("dispose", E);
      };
      u !== void 0 && u.texture.dispose();
      const p = o.morphAttributes.position !== void 0, m = o.morphAttributes.normal !== void 0, _ = o.morphAttributes.color !== void 0, g = o.morphAttributes.position || [], f = o.morphAttributes.normal || [], v = o.morphAttributes.color || [];
      let x = 0;
      p === !0 && (x = 1), m === !0 && (x = 2), _ === !0 && (x = 3);
      let y = o.attributes.position.count * x, A = 1;
      y > e.maxTextureSize && (A = Math.ceil(y / e.maxTextureSize), y = e.maxTextureSize);
      const S = new Float32Array(y * A * 4 * d), C = new Wl(S, y, A, d);
      C.type = mi, C.needsUpdate = !0;
      const P = x * 4;
      for (let w = 0; w < d; w++) {
        const L = g[w], N = f[w], B = v[w], W = y * A * 4 * w;
        for (let Z = 0; Z < L.count; Z++) {
          const X = Z * P;
          p === !0 && (n.fromBufferAttribute(L, Z), S[W + X + 0] = n.x, S[W + X + 1] = n.y, S[W + X + 2] = n.z, S[W + X + 3] = 0), m === !0 && (n.fromBufferAttribute(N, Z), S[W + X + 4] = n.x, S[W + X + 5] = n.y, S[W + X + 6] = n.z, S[W + X + 7] = 0), _ === !0 && (n.fromBufferAttribute(B, Z), S[W + X + 8] = n.x, S[W + X + 9] = n.y, S[W + X + 10] = n.z, S[W + X + 11] = B.itemSize === 4 ? n.w : 1);
        }
      }
      u = {
        count: d,
        texture: C,
        size: new H(y, A)
      }, i.set(o, u), o.addEventListener("dispose", E);
    }
    if (a.isInstancedMesh === !0 && a.morphTexture !== null)
      l.getUniforms().setValue(r, "morphTexture", a.morphTexture, t);
    else {
      let p = 0;
      for (let _ = 0; _ < c.length; _++)
        p += c[_];
      const m = o.morphTargetsRelative ? 1 : 1 - p;
      l.getUniforms().setValue(r, "morphTargetBaseInfluence", m), l.getUniforms().setValue(r, "morphTargetInfluences", c);
    }
    l.getUniforms().setValue(r, "morphTargetsTexture", u.texture, t), l.getUniforms().setValue(r, "morphTargetsTextureSize", u.size);
  }
  return {
    update: s
  };
}
function rS(r, e, t, i) {
  let n = /* @__PURE__ */ new WeakMap();
  function s(l) {
    const c = i.render.frame, h = l.geometry, d = e.get(l, h);
    if (n.get(d) !== c && (e.update(d), n.set(d, c)), l.isInstancedMesh && (l.hasEventListener("dispose", o) === !1 && l.addEventListener("dispose", o), n.get(l) !== c && (t.update(l.instanceMatrix, r.ARRAY_BUFFER), l.instanceColor !== null && t.update(l.instanceColor, r.ARRAY_BUFFER), n.set(l, c))), l.isSkinnedMesh) {
      const u = l.skeleton;
      n.get(u) !== c && (u.update(), n.set(u, c));
    }
    return d;
  }
  function a() {
    n = /* @__PURE__ */ new WeakMap();
  }
  function o(l) {
    const c = l.target;
    c.removeEventListener("dispose", o), t.remove(c.instanceMatrix), c.instanceColor !== null && t.remove(c.instanceColor);
  }
  return {
    update: s,
    dispose: a
  };
}
const cg = /* @__PURE__ */ new Et(), fp = /* @__PURE__ */ new md(1, 1), hg = /* @__PURE__ */ new Wl(), dg = /* @__PURE__ */ new Xl(), ug = /* @__PURE__ */ new Sa(), mp = [], gp = [], _p = new Float32Array(16), yp = new Float32Array(9), vp = new Float32Array(4);
function Er(r, e, t) {
  const i = r[0];
  if (i <= 0 || i > 0) return r;
  const n = e * t;
  let s = mp[n];
  if (s === void 0 && (s = new Float32Array(n), mp[n] = s), e !== 0) {
    i.toArray(s, 0);
    for (let a = 1, o = 0; a !== e; ++a)
      o += t, r[a].toArray(s, o);
  }
  return s;
}
function Ot(r, e) {
  if (r.length !== e.length) return !1;
  for (let t = 0, i = r.length; t < i; t++)
    if (r[t] !== e[t]) return !1;
  return !0;
}
function Ft(r, e) {
  for (let t = 0, i = e.length; t < i; t++)
    r[t] = e[t];
}
function gc(r, e) {
  let t = gp[e];
  t === void 0 && (t = new Int32Array(e), gp[e] = t);
  for (let i = 0; i !== e; ++i)
    t[i] = r.allocateTextureUnit();
  return t;
}
function aS(r, e) {
  const t = this.cache;
  t[0] !== e && (r.uniform1f(this.addr, e), t[0] = e);
}
function oS(r, e) {
  const t = this.cache;
  if (e.x !== void 0)
    (t[0] !== e.x || t[1] !== e.y) && (r.uniform2f(this.addr, e.x, e.y), t[0] = e.x, t[1] = e.y);
  else {
    if (Ot(t, e)) return;
    r.uniform2fv(this.addr, e), Ft(t, e);
  }
}
function lS(r, e) {
  const t = this.cache;
  if (e.x !== void 0)
    (t[0] !== e.x || t[1] !== e.y || t[2] !== e.z) && (r.uniform3f(this.addr, e.x, e.y, e.z), t[0] = e.x, t[1] = e.y, t[2] = e.z);
  else if (e.r !== void 0)
    (t[0] !== e.r || t[1] !== e.g || t[2] !== e.b) && (r.uniform3f(this.addr, e.r, e.g, e.b), t[0] = e.r, t[1] = e.g, t[2] = e.b);
  else {
    if (Ot(t, e)) return;
    r.uniform3fv(this.addr, e), Ft(t, e);
  }
}
function cS(r, e) {
  const t = this.cache;
  if (e.x !== void 0)
    (t[0] !== e.x || t[1] !== e.y || t[2] !== e.z || t[3] !== e.w) && (r.uniform4f(this.addr, e.x, e.y, e.z, e.w), t[0] = e.x, t[1] = e.y, t[2] = e.z, t[3] = e.w);
  else {
    if (Ot(t, e)) return;
    r.uniform4fv(this.addr, e), Ft(t, e);
  }
}
function hS(r, e) {
  const t = this.cache, i = e.elements;
  if (i === void 0) {
    if (Ot(t, e)) return;
    r.uniformMatrix2fv(this.addr, !1, e), Ft(t, e);
  } else {
    if (Ot(t, i)) return;
    vp.set(i), r.uniformMatrix2fv(this.addr, !1, vp), Ft(t, i);
  }
}
function dS(r, e) {
  const t = this.cache, i = e.elements;
  if (i === void 0) {
    if (Ot(t, e)) return;
    r.uniformMatrix3fv(this.addr, !1, e), Ft(t, e);
  } else {
    if (Ot(t, i)) return;
    yp.set(i), r.uniformMatrix3fv(this.addr, !1, yp), Ft(t, i);
  }
}
function uS(r, e) {
  const t = this.cache, i = e.elements;
  if (i === void 0) {
    if (Ot(t, e)) return;
    r.uniformMatrix4fv(this.addr, !1, e), Ft(t, e);
  } else {
    if (Ot(t, i)) return;
    _p.set(i), r.uniformMatrix4fv(this.addr, !1, _p), Ft(t, i);
  }
}
function pS(r, e) {
  const t = this.cache;
  t[0] !== e && (r.uniform1i(this.addr, e), t[0] = e);
}
function fS(r, e) {
  const t = this.cache;
  if (e.x !== void 0)
    (t[0] !== e.x || t[1] !== e.y) && (r.uniform2i(this.addr, e.x, e.y), t[0] = e.x, t[1] = e.y);
  else {
    if (Ot(t, e)) return;
    r.uniform2iv(this.addr, e), Ft(t, e);
  }
}
function mS(r, e) {
  const t = this.cache;
  if (e.x !== void 0)
    (t[0] !== e.x || t[1] !== e.y || t[2] !== e.z) && (r.uniform3i(this.addr, e.x, e.y, e.z), t[0] = e.x, t[1] = e.y, t[2] = e.z);
  else {
    if (Ot(t, e)) return;
    r.uniform3iv(this.addr, e), Ft(t, e);
  }
}
function gS(r, e) {
  const t = this.cache;
  if (e.x !== void 0)
    (t[0] !== e.x || t[1] !== e.y || t[2] !== e.z || t[3] !== e.w) && (r.uniform4i(this.addr, e.x, e.y, e.z, e.w), t[0] = e.x, t[1] = e.y, t[2] = e.z, t[3] = e.w);
  else {
    if (Ot(t, e)) return;
    r.uniform4iv(this.addr, e), Ft(t, e);
  }
}
function _S(r, e) {
  const t = this.cache;
  t[0] !== e && (r.uniform1ui(this.addr, e), t[0] = e);
}
function yS(r, e) {
  const t = this.cache;
  if (e.x !== void 0)
    (t[0] !== e.x || t[1] !== e.y) && (r.uniform2ui(this.addr, e.x, e.y), t[0] = e.x, t[1] = e.y);
  else {
    if (Ot(t, e)) return;
    r.uniform2uiv(this.addr, e), Ft(t, e);
  }
}
function vS(r, e) {
  const t = this.cache;
  if (e.x !== void 0)
    (t[0] !== e.x || t[1] !== e.y || t[2] !== e.z) && (r.uniform3ui(this.addr, e.x, e.y, e.z), t[0] = e.x, t[1] = e.y, t[2] = e.z);
  else {
    if (Ot(t, e)) return;
    r.uniform3uiv(this.addr, e), Ft(t, e);
  }
}
function xS(r, e) {
  const t = this.cache;
  if (e.x !== void 0)
    (t[0] !== e.x || t[1] !== e.y || t[2] !== e.z || t[3] !== e.w) && (r.uniform4ui(this.addr, e.x, e.y, e.z, e.w), t[0] = e.x, t[1] = e.y, t[2] = e.z, t[3] = e.w);
  else {
    if (Ot(t, e)) return;
    r.uniform4uiv(this.addr, e), Ft(t, e);
  }
}
function bS(r, e, t) {
  const i = this.cache, n = t.allocateTextureUnit();
  i[0] !== n && (r.uniform1i(this.addr, n), i[0] = n);
  let s;
  this.type === r.SAMPLER_2D_SHADOW ? (fp.compareFunction = od, s = fp) : s = cg, t.setTexture2D(e || s, n);
}
function SS(r, e, t) {
  const i = this.cache, n = t.allocateTextureUnit();
  i[0] !== n && (r.uniform1i(this.addr, n), i[0] = n), t.setTexture3D(e || dg, n);
}
function MS(r, e, t) {
  const i = this.cache, n = t.allocateTextureUnit();
  i[0] !== n && (r.uniform1i(this.addr, n), i[0] = n), t.setTextureCube(e || ug, n);
}
function wS(r, e, t) {
  const i = this.cache, n = t.allocateTextureUnit();
  i[0] !== n && (r.uniform1i(this.addr, n), i[0] = n), t.setTexture2DArray(e || hg, n);
}
function ES(r) {
  switch (r) {
    case 5126:
      return aS;
    case 35664:
      return oS;
    case 35665:
      return lS;
    case 35666:
      return cS;
    case 35674:
      return hS;
    case 35675:
      return dS;
    case 35676:
      return uS;
    case 5124:
    case 35670:
      return pS;
    case 35667:
    case 35671:
      return fS;
    case 35668:
    case 35672:
      return mS;
    case 35669:
    case 35673:
      return gS;
    case 5125:
      return _S;
    case 36294:
      return yS;
    case 36295:
      return vS;
    case 36296:
      return xS;
    case 35678:
    case 36198:
    case 36298:
    case 36306:
    case 35682:
      return bS;
    case 35679:
    case 36299:
    case 36307:
      return SS;
    case 35680:
    case 36300:
    case 36308:
    case 36293:
      return MS;
    case 36289:
    case 36303:
    case 36311:
    case 36292:
      return wS;
  }
}
function TS(r, e) {
  r.uniform1fv(this.addr, e);
}
function AS(r, e) {
  const t = Er(e, this.size, 2);
  r.uniform2fv(this.addr, t);
}
function CS(r, e) {
  const t = Er(e, this.size, 3);
  r.uniform3fv(this.addr, t);
}
function RS(r, e) {
  const t = Er(e, this.size, 4);
  r.uniform4fv(this.addr, t);
}
function PS(r, e) {
  const t = Er(e, this.size, 4);
  r.uniformMatrix2fv(this.addr, !1, t);
}
function LS(r, e) {
  const t = Er(e, this.size, 9);
  r.uniformMatrix3fv(this.addr, !1, t);
}
function IS(r, e) {
  const t = Er(e, this.size, 16);
  r.uniformMatrix4fv(this.addr, !1, t);
}
function DS(r, e) {
  r.uniform1iv(this.addr, e);
}
function NS(r, e) {
  r.uniform2iv(this.addr, e);
}
function US(r, e) {
  r.uniform3iv(this.addr, e);
}
function OS(r, e) {
  r.uniform4iv(this.addr, e);
}
function FS(r, e) {
  r.uniform1uiv(this.addr, e);
}
function BS(r, e) {
  r.uniform2uiv(this.addr, e);
}
function kS(r, e) {
  r.uniform3uiv(this.addr, e);
}
function zS(r, e) {
  r.uniform4uiv(this.addr, e);
}
function HS(r, e, t) {
  const i = this.cache, n = e.length, s = gc(t, n);
  Ot(i, s) || (r.uniform1iv(this.addr, s), Ft(i, s));
  for (let a = 0; a !== n; ++a)
    t.setTexture2D(e[a] || cg, s[a]);
}
function VS(r, e, t) {
  const i = this.cache, n = e.length, s = gc(t, n);
  Ot(i, s) || (r.uniform1iv(this.addr, s), Ft(i, s));
  for (let a = 0; a !== n; ++a)
    t.setTexture3D(e[a] || dg, s[a]);
}
function GS(r, e, t) {
  const i = this.cache, n = e.length, s = gc(t, n);
  Ot(i, s) || (r.uniform1iv(this.addr, s), Ft(i, s));
  for (let a = 0; a !== n; ++a)
    t.setTextureCube(e[a] || ug, s[a]);
}
function WS(r, e, t) {
  const i = this.cache, n = e.length, s = gc(t, n);
  Ot(i, s) || (r.uniform1iv(this.addr, s), Ft(i, s));
  for (let a = 0; a !== n; ++a)
    t.setTexture2DArray(e[a] || hg, s[a]);
}
function XS(r) {
  switch (r) {
    case 5126:
      return TS;
    case 35664:
      return AS;
    case 35665:
      return CS;
    case 35666:
      return RS;
    case 35674:
      return PS;
    case 35675:
      return LS;
    case 35676:
      return IS;
    case 5124:
    case 35670:
      return DS;
    case 35667:
    case 35671:
      return NS;
    case 35668:
    case 35672:
      return US;
    case 35669:
    case 35673:
      return OS;
    case 5125:
      return FS;
    case 36294:
      return BS;
    case 36295:
      return kS;
    case 36296:
      return zS;
    case 35678:
    case 36198:
    case 36298:
    case 36306:
    case 35682:
      return HS;
    case 35679:
    case 36299:
    case 36307:
      return VS;
    case 35680:
    case 36300:
    case 36308:
    case 36293:
      return GS;
    case 36289:
    case 36303:
    case 36311:
    case 36292:
      return WS;
  }
}
class qS {
  constructor(e, t, i) {
    this.id = e, this.addr = i, this.cache = [], this.type = t.type, this.setValue = ES(t.type);
  }
}
class ZS {
  constructor(e, t, i) {
    this.id = e, this.addr = i, this.cache = [], this.type = t.type, this.size = t.size, this.setValue = XS(t.type);
  }
}
class YS {
  constructor(e) {
    this.id = e, this.seq = [], this.map = {};
  }
  setValue(e, t, i) {
    const n = this.seq;
    for (let s = 0, a = n.length; s !== a; ++s) {
      const o = n[s];
      o.setValue(e, t[o.id], i);
    }
  }
}
const ch = /(\w+)(\])?(\[|\.)?/g;
function xp(r, e) {
  r.seq.push(e), r.map[e.id] = e;
}
function jS(r, e, t) {
  const i = r.name, n = i.length;
  for (ch.lastIndex = 0; ; ) {
    const s = ch.exec(i), a = ch.lastIndex;
    let o = s[1];
    const l = s[2] === "]", c = s[3];
    if (l && (o = o | 0), c === void 0 || c === "[" && a + 2 === n) {
      xp(t, c === void 0 ? new qS(o, r, e) : new ZS(o, r, e));
      break;
    } else {
      let d = t.map[o];
      d === void 0 && (d = new YS(o), xp(t, d)), t = d;
    }
  }
}
class Xo {
  constructor(e, t) {
    this.seq = [], this.map = {};
    const i = e.getProgramParameter(t, e.ACTIVE_UNIFORMS);
    for (let n = 0; n < i; ++n) {
      const s = e.getActiveUniform(t, n), a = e.getUniformLocation(t, s.name);
      jS(s, a, this);
    }
  }
  setValue(e, t, i, n) {
    const s = this.map[t];
    s !== void 0 && s.setValue(e, i, n);
  }
  setOptional(e, t, i) {
    const n = t[i];
    n !== void 0 && this.setValue(e, i, n);
  }
  static upload(e, t, i, n) {
    for (let s = 0, a = t.length; s !== a; ++s) {
      const o = t[s], l = i[o.id];
      l.needsUpdate !== !1 && o.setValue(e, l.value, n);
    }
  }
  static seqWithValue(e, t) {
    const i = [];
    for (let n = 0, s = e.length; n !== s; ++n) {
      const a = e[n];
      a.id in t && i.push(a);
    }
    return i;
  }
}
function bp(r, e, t) {
  const i = r.createShader(e);
  return r.shaderSource(i, t), r.compileShader(i), i;
}
const $S = 37297;
let KS = 0;
function JS(r, e) {
  const t = r.split(`
`), i = [], n = Math.max(e - 6, 0), s = Math.min(e + 6, t.length);
  for (let a = n; a < s; a++) {
    const o = a + 1;
    i.push(`${o === e ? ">" : " "} ${o}: ${t[a]}`);
  }
  return i.join(`
`);
}
const Sp = /* @__PURE__ */ new He();
function QS(r) {
  et._getMatrix(Sp, et.workingColorSpace, r);
  const e = `mat3( ${Sp.elements.map((t) => t.toFixed(4))} )`;
  switch (et.getTransfer(r)) {
    case la:
      return [e, "LinearTransferOETF"];
    case ut:
      return [e, "sRGBTransferOETF"];
    default:
      return console.warn("THREE.WebGLProgram: Unsupported color space: ", r), [e, "LinearTransferOETF"];
  }
}
function Mp(r, e, t) {
  const i = r.getShaderParameter(e, r.COMPILE_STATUS), s = (r.getShaderInfoLog(e) || "").trim();
  if (i && s === "") return "";
  const a = /ERROR: 0:(\d+)/.exec(s);
  if (a) {
    const o = parseInt(a[1]);
    return t.toUpperCase() + `

` + s + `

` + JS(r.getShaderSource(e), o);
  } else
    return s;
}
function eM(r, e) {
  const t = QS(e);
  return [
    `vec4 ${r}( vec4 value ) {`,
    `	return ${t[1]}( vec4( value.rgb * ${t[0]}, value.a ) );`,
    "}"
  ].join(`
`);
}
function tM(r, e) {
  let t;
  switch (e) {
    case Vf:
      t = "Linear";
      break;
    case Gf:
      t = "Reinhard";
      break;
    case Wf:
      t = "Cineon";
      break;
    case Xf:
      t = "ACESFilmic";
      break;
    case Zf:
      t = "AgX";
      break;
    case Yf:
      t = "Neutral";
      break;
    case qf:
      t = "Custom";
      break;
    default:
      console.warn("THREE.WebGLProgram: Unsupported toneMapping:", e), t = "Linear";
  }
  return "vec3 " + r + "( vec3 color ) { return " + t + "ToneMapping( color ); }";
}
const bo = /* @__PURE__ */ new b();
function iM() {
  et.getLuminanceCoefficients(bo);
  const r = bo.x.toFixed(4), e = bo.y.toFixed(4), t = bo.z.toFixed(4);
  return [
    "float luminance( const in vec3 rgb ) {",
    `	const vec3 weights = vec3( ${r}, ${e}, ${t} );`,
    "	return dot( weights, rgb );",
    "}"
  ].join(`
`);
}
function nM(r) {
  return [
    r.extensionClipCullDistance ? "#extension GL_ANGLE_clip_cull_distance : require" : "",
    r.extensionMultiDraw ? "#extension GL_ANGLE_multi_draw : require" : ""
  ].filter(Xr).join(`
`);
}
function sM(r) {
  const e = [];
  for (const t in r) {
    const i = r[t];
    i !== !1 && e.push("#define " + t + " " + i);
  }
  return e.join(`
`);
}
function rM(r, e) {
  const t = {}, i = r.getProgramParameter(e, r.ACTIVE_ATTRIBUTES);
  for (let n = 0; n < i; n++) {
    const s = r.getActiveAttrib(e, n), a = s.name;
    let o = 1;
    s.type === r.FLOAT_MAT2 && (o = 2), s.type === r.FLOAT_MAT3 && (o = 3), s.type === r.FLOAT_MAT4 && (o = 4), t[a] = {
      type: s.type,
      location: r.getAttribLocation(e, a),
      locationSize: o
    };
  }
  return t;
}
function Xr(r) {
  return r !== "";
}
function wp(r, e) {
  const t = e.numSpotLightShadows + e.numSpotLightMaps - e.numSpotLightShadowsWithMaps;
  return r.replace(/NUM_DIR_LIGHTS/g, e.numDirLights).replace(/NUM_SPOT_LIGHTS/g, e.numSpotLights).replace(/NUM_SPOT_LIGHT_MAPS/g, e.numSpotLightMaps).replace(/NUM_SPOT_LIGHT_COORDS/g, t).replace(/NUM_RECT_AREA_LIGHTS/g, e.numRectAreaLights).replace(/NUM_POINT_LIGHTS/g, e.numPointLights).replace(/NUM_HEMI_LIGHTS/g, e.numHemiLights).replace(/NUM_DIR_LIGHT_SHADOWS/g, e.numDirLightShadows).replace(/NUM_SPOT_LIGHT_SHADOWS_WITH_MAPS/g, e.numSpotLightShadowsWithMaps).replace(/NUM_SPOT_LIGHT_SHADOWS/g, e.numSpotLightShadows).replace(/NUM_POINT_LIGHT_SHADOWS/g, e.numPointLightShadows);
}
function Ep(r, e) {
  return r.replace(/NUM_CLIPPING_PLANES/g, e.numClippingPlanes).replace(/UNION_CLIPPING_PLANES/g, e.numClippingPlanes - e.numClipIntersection);
}
const aM = /^[ \t]*#include +<([\w\d./]+)>/gm;
function Xh(r) {
  return r.replace(aM, lM);
}
const oM = /* @__PURE__ */ new Map();
function lM(r, e) {
  let t = Ze[e];
  if (t === void 0) {
    const i = oM.get(e);
    if (i !== void 0)
      t = Ze[i], console.warn('THREE.WebGLRenderer: Shader chunk "%s" has been deprecated. Use "%s" instead.', e, i);
    else
      throw new Error("Can not resolve #include <" + e + ">");
  }
  return Xh(t);
}
const cM = /#pragma unroll_loop_start\s+for\s*\(\s*int\s+i\s*=\s*(\d+)\s*;\s*i\s*<\s*(\d+)\s*;\s*i\s*\+\+\s*\)\s*{([\s\S]+?)}\s+#pragma unroll_loop_end/g;
function Tp(r) {
  return r.replace(cM, hM);
}
function hM(r, e, t, i) {
  let n = "";
  for (let s = parseInt(e); s < parseInt(t); s++)
    n += i.replace(/\[\s*i\s*\]/g, "[ " + s + " ]").replace(/UNROLLED_LOOP_INDEX/g, s);
  return n;
}
function Ap(r) {
  let e = `precision ${r.precision} float;
	precision ${r.precision} int;
	precision ${r.precision} sampler2D;
	precision ${r.precision} samplerCube;
	precision ${r.precision} sampler3D;
	precision ${r.precision} sampler2DArray;
	precision ${r.precision} sampler2DShadow;
	precision ${r.precision} samplerCubeShadow;
	precision ${r.precision} sampler2DArrayShadow;
	precision ${r.precision} isampler2D;
	precision ${r.precision} isampler3D;
	precision ${r.precision} isamplerCube;
	precision ${r.precision} isampler2DArray;
	precision ${r.precision} usampler2D;
	precision ${r.precision} usampler3D;
	precision ${r.precision} usamplerCube;
	precision ${r.precision} usampler2DArray;
	`;
  return r.precision === "highp" ? e += `
#define HIGH_PRECISION` : r.precision === "mediump" ? e += `
#define MEDIUM_PRECISION` : r.precision === "lowp" && (e += `
#define LOW_PRECISION`), e;
}
function dM(r) {
  let e = "SHADOWMAP_TYPE_BASIC";
  return r.shadowMapType === jh ? e = "SHADOWMAP_TYPE_PCF" : r.shadowMapType === bf ? e = "SHADOWMAP_TYPE_PCF_SOFT" : r.shadowMapType === Yi && (e = "SHADOWMAP_TYPE_VSM"), e;
}
function uM(r) {
  let e = "ENVMAP_TYPE_CUBE";
  if (r.envMap)
    switch (r.envMapMode) {
      case _n:
      case Un:
        e = "ENVMAP_TYPE_CUBE";
        break;
      case xr:
        e = "ENVMAP_TYPE_CUBE_UV";
        break;
    }
  return e;
}
function pM(r) {
  let e = "ENVMAP_MODE_REFLECTION";
  if (r.envMap)
    switch (r.envMapMode) {
      case Un:
        e = "ENVMAP_MODE_REFRACTION";
        break;
    }
  return e;
}
function fM(r) {
  let e = "ENVMAP_BLENDING_NONE";
  if (r.envMap)
    switch (r.combine) {
      case xa:
        e = "ENVMAP_BLENDING_MULTIPLY";
        break;
      case zf:
        e = "ENVMAP_BLENDING_MIX";
        break;
      case Hf:
        e = "ENVMAP_BLENDING_ADD";
        break;
    }
  return e;
}
function mM(r) {
  const e = r.envMapCubeUVHeight;
  if (e === null) return null;
  const t = Math.log2(e) - 2, i = 1 / e;
  return { texelWidth: 1 / (3 * Math.max(Math.pow(2, t), 7 * 16)), texelHeight: i, maxMip: t };
}
function gM(r, e, t, i) {
  const n = r.getContext(), s = t.defines;
  let a = t.vertexShader, o = t.fragmentShader;
  const l = dM(t), c = uM(t), h = pM(t), d = fM(t), u = mM(t), p = nM(t), m = sM(s), _ = n.createProgram();
  let g, f, v = t.glslVersion ? "#version " + t.glslVersion + `
` : "";
  t.isRawShaderMaterial ? (g = [
    "#define SHADER_TYPE " + t.shaderType,
    "#define SHADER_NAME " + t.shaderName,
    m
  ].filter(Xr).join(`
`), g.length > 0 && (g += `
`), f = [
    "#define SHADER_TYPE " + t.shaderType,
    "#define SHADER_NAME " + t.shaderName,
    m
  ].filter(Xr).join(`
`), f.length > 0 && (f += `
`)) : (g = [
    Ap(t),
    "#define SHADER_TYPE " + t.shaderType,
    "#define SHADER_NAME " + t.shaderName,
    m,
    t.extensionClipCullDistance ? "#define USE_CLIP_DISTANCE" : "",
    t.batching ? "#define USE_BATCHING" : "",
    t.batchingColor ? "#define USE_BATCHING_COLOR" : "",
    t.instancing ? "#define USE_INSTANCING" : "",
    t.instancingColor ? "#define USE_INSTANCING_COLOR" : "",
    t.instancingMorph ? "#define USE_INSTANCING_MORPH" : "",
    t.useFog && t.fog ? "#define USE_FOG" : "",
    t.useFog && t.fogExp2 ? "#define FOG_EXP2" : "",
    t.map ? "#define USE_MAP" : "",
    t.envMap ? "#define USE_ENVMAP" : "",
    t.envMap ? "#define " + h : "",
    t.lightMap ? "#define USE_LIGHTMAP" : "",
    t.aoMap ? "#define USE_AOMAP" : "",
    t.bumpMap ? "#define USE_BUMPMAP" : "",
    t.normalMap ? "#define USE_NORMALMAP" : "",
    t.normalMapObjectSpace ? "#define USE_NORMALMAP_OBJECTSPACE" : "",
    t.normalMapTangentSpace ? "#define USE_NORMALMAP_TANGENTSPACE" : "",
    t.displacementMap ? "#define USE_DISPLACEMENTMAP" : "",
    t.emissiveMap ? "#define USE_EMISSIVEMAP" : "",
    t.anisotropy ? "#define USE_ANISOTROPY" : "",
    t.anisotropyMap ? "#define USE_ANISOTROPYMAP" : "",
    t.clearcoatMap ? "#define USE_CLEARCOATMAP" : "",
    t.clearcoatRoughnessMap ? "#define USE_CLEARCOAT_ROUGHNESSMAP" : "",
    t.clearcoatNormalMap ? "#define USE_CLEARCOAT_NORMALMAP" : "",
    t.iridescenceMap ? "#define USE_IRIDESCENCEMAP" : "",
    t.iridescenceThicknessMap ? "#define USE_IRIDESCENCE_THICKNESSMAP" : "",
    t.specularMap ? "#define USE_SPECULARMAP" : "",
    t.specularColorMap ? "#define USE_SPECULAR_COLORMAP" : "",
    t.specularIntensityMap ? "#define USE_SPECULAR_INTENSITYMAP" : "",
    t.roughnessMap ? "#define USE_ROUGHNESSMAP" : "",
    t.metalnessMap ? "#define USE_METALNESSMAP" : "",
    t.alphaMap ? "#define USE_ALPHAMAP" : "",
    t.alphaHash ? "#define USE_ALPHAHASH" : "",
    t.transmission ? "#define USE_TRANSMISSION" : "",
    t.transmissionMap ? "#define USE_TRANSMISSIONMAP" : "",
    t.thicknessMap ? "#define USE_THICKNESSMAP" : "",
    t.sheenColorMap ? "#define USE_SHEEN_COLORMAP" : "",
    t.sheenRoughnessMap ? "#define USE_SHEEN_ROUGHNESSMAP" : "",
    //
    t.mapUv ? "#define MAP_UV " + t.mapUv : "",
    t.alphaMapUv ? "#define ALPHAMAP_UV " + t.alphaMapUv : "",
    t.lightMapUv ? "#define LIGHTMAP_UV " + t.lightMapUv : "",
    t.aoMapUv ? "#define AOMAP_UV " + t.aoMapUv : "",
    t.emissiveMapUv ? "#define EMISSIVEMAP_UV " + t.emissiveMapUv : "",
    t.bumpMapUv ? "#define BUMPMAP_UV " + t.bumpMapUv : "",
    t.normalMapUv ? "#define NORMALMAP_UV " + t.normalMapUv : "",
    t.displacementMapUv ? "#define DISPLACEMENTMAP_UV " + t.displacementMapUv : "",
    t.metalnessMapUv ? "#define METALNESSMAP_UV " + t.metalnessMapUv : "",
    t.roughnessMapUv ? "#define ROUGHNESSMAP_UV " + t.roughnessMapUv : "",
    t.anisotropyMapUv ? "#define ANISOTROPYMAP_UV " + t.anisotropyMapUv : "",
    t.clearcoatMapUv ? "#define CLEARCOATMAP_UV " + t.clearcoatMapUv : "",
    t.clearcoatNormalMapUv ? "#define CLEARCOAT_NORMALMAP_UV " + t.clearcoatNormalMapUv : "",
    t.clearcoatRoughnessMapUv ? "#define CLEARCOAT_ROUGHNESSMAP_UV " + t.clearcoatRoughnessMapUv : "",
    t.iridescenceMapUv ? "#define IRIDESCENCEMAP_UV " + t.iridescenceMapUv : "",
    t.iridescenceThicknessMapUv ? "#define IRIDESCENCE_THICKNESSMAP_UV " + t.iridescenceThicknessMapUv : "",
    t.sheenColorMapUv ? "#define SHEEN_COLORMAP_UV " + t.sheenColorMapUv : "",
    t.sheenRoughnessMapUv ? "#define SHEEN_ROUGHNESSMAP_UV " + t.sheenRoughnessMapUv : "",
    t.specularMapUv ? "#define SPECULARMAP_UV " + t.specularMapUv : "",
    t.specularColorMapUv ? "#define SPECULAR_COLORMAP_UV " + t.specularColorMapUv : "",
    t.specularIntensityMapUv ? "#define SPECULAR_INTENSITYMAP_UV " + t.specularIntensityMapUv : "",
    t.transmissionMapUv ? "#define TRANSMISSIONMAP_UV " + t.transmissionMapUv : "",
    t.thicknessMapUv ? "#define THICKNESSMAP_UV " + t.thicknessMapUv : "",
    //
    t.vertexTangents && t.flatShading === !1 ? "#define USE_TANGENT" : "",
    t.vertexColors ? "#define USE_COLOR" : "",
    t.vertexAlphas ? "#define USE_COLOR_ALPHA" : "",
    t.vertexUv1s ? "#define USE_UV1" : "",
    t.vertexUv2s ? "#define USE_UV2" : "",
    t.vertexUv3s ? "#define USE_UV3" : "",
    t.pointsUvs ? "#define USE_POINTS_UV" : "",
    t.flatShading ? "#define FLAT_SHADED" : "",
    t.skinning ? "#define USE_SKINNING" : "",
    t.morphTargets ? "#define USE_MORPHTARGETS" : "",
    t.morphNormals && t.flatShading === !1 ? "#define USE_MORPHNORMALS" : "",
    t.morphColors ? "#define USE_MORPHCOLORS" : "",
    t.morphTargetsCount > 0 ? "#define MORPHTARGETS_TEXTURE_STRIDE " + t.morphTextureStride : "",
    t.morphTargetsCount > 0 ? "#define MORPHTARGETS_COUNT " + t.morphTargetsCount : "",
    t.doubleSided ? "#define DOUBLE_SIDED" : "",
    t.flipSided ? "#define FLIP_SIDED" : "",
    t.shadowMapEnabled ? "#define USE_SHADOWMAP" : "",
    t.shadowMapEnabled ? "#define " + l : "",
    t.sizeAttenuation ? "#define USE_SIZEATTENUATION" : "",
    t.numLightProbes > 0 ? "#define USE_LIGHT_PROBES" : "",
    t.logarithmicDepthBuffer ? "#define USE_LOGARITHMIC_DEPTH_BUFFER" : "",
    t.reversedDepthBuffer ? "#define USE_REVERSED_DEPTH_BUFFER" : "",
    "uniform mat4 modelMatrix;",
    "uniform mat4 modelViewMatrix;",
    "uniform mat4 projectionMatrix;",
    "uniform mat4 viewMatrix;",
    "uniform mat3 normalMatrix;",
    "uniform vec3 cameraPosition;",
    "uniform bool isOrthographic;",
    "#ifdef USE_INSTANCING",
    "	attribute mat4 instanceMatrix;",
    "#endif",
    "#ifdef USE_INSTANCING_COLOR",
    "	attribute vec3 instanceColor;",
    "#endif",
    "#ifdef USE_INSTANCING_MORPH",
    "	uniform sampler2D morphTexture;",
    "#endif",
    "attribute vec3 position;",
    "attribute vec3 normal;",
    "attribute vec2 uv;",
    "#ifdef USE_UV1",
    "	attribute vec2 uv1;",
    "#endif",
    "#ifdef USE_UV2",
    "	attribute vec2 uv2;",
    "#endif",
    "#ifdef USE_UV3",
    "	attribute vec2 uv3;",
    "#endif",
    "#ifdef USE_TANGENT",
    "	attribute vec4 tangent;",
    "#endif",
    "#if defined( USE_COLOR_ALPHA )",
    "	attribute vec4 color;",
    "#elif defined( USE_COLOR )",
    "	attribute vec3 color;",
    "#endif",
    "#ifdef USE_SKINNING",
    "	attribute vec4 skinIndex;",
    "	attribute vec4 skinWeight;",
    "#endif",
    `
`
  ].filter(Xr).join(`
`), f = [
    Ap(t),
    "#define SHADER_TYPE " + t.shaderType,
    "#define SHADER_NAME " + t.shaderName,
    m,
    t.useFog && t.fog ? "#define USE_FOG" : "",
    t.useFog && t.fogExp2 ? "#define FOG_EXP2" : "",
    t.alphaToCoverage ? "#define ALPHA_TO_COVERAGE" : "",
    t.map ? "#define USE_MAP" : "",
    t.matcap ? "#define USE_MATCAP" : "",
    t.envMap ? "#define USE_ENVMAP" : "",
    t.envMap ? "#define " + c : "",
    t.envMap ? "#define " + h : "",
    t.envMap ? "#define " + d : "",
    u ? "#define CUBEUV_TEXEL_WIDTH " + u.texelWidth : "",
    u ? "#define CUBEUV_TEXEL_HEIGHT " + u.texelHeight : "",
    u ? "#define CUBEUV_MAX_MIP " + u.maxMip + ".0" : "",
    t.lightMap ? "#define USE_LIGHTMAP" : "",
    t.aoMap ? "#define USE_AOMAP" : "",
    t.bumpMap ? "#define USE_BUMPMAP" : "",
    t.normalMap ? "#define USE_NORMALMAP" : "",
    t.normalMapObjectSpace ? "#define USE_NORMALMAP_OBJECTSPACE" : "",
    t.normalMapTangentSpace ? "#define USE_NORMALMAP_TANGENTSPACE" : "",
    t.emissiveMap ? "#define USE_EMISSIVEMAP" : "",
    t.anisotropy ? "#define USE_ANISOTROPY" : "",
    t.anisotropyMap ? "#define USE_ANISOTROPYMAP" : "",
    t.clearcoat ? "#define USE_CLEARCOAT" : "",
    t.clearcoatMap ? "#define USE_CLEARCOATMAP" : "",
    t.clearcoatRoughnessMap ? "#define USE_CLEARCOAT_ROUGHNESSMAP" : "",
    t.clearcoatNormalMap ? "#define USE_CLEARCOAT_NORMALMAP" : "",
    t.dispersion ? "#define USE_DISPERSION" : "",
    t.iridescence ? "#define USE_IRIDESCENCE" : "",
    t.iridescenceMap ? "#define USE_IRIDESCENCEMAP" : "",
    t.iridescenceThicknessMap ? "#define USE_IRIDESCENCE_THICKNESSMAP" : "",
    t.specularMap ? "#define USE_SPECULARMAP" : "",
    t.specularColorMap ? "#define USE_SPECULAR_COLORMAP" : "",
    t.specularIntensityMap ? "#define USE_SPECULAR_INTENSITYMAP" : "",
    t.roughnessMap ? "#define USE_ROUGHNESSMAP" : "",
    t.metalnessMap ? "#define USE_METALNESSMAP" : "",
    t.alphaMap ? "#define USE_ALPHAMAP" : "",
    t.alphaTest ? "#define USE_ALPHATEST" : "",
    t.alphaHash ? "#define USE_ALPHAHASH" : "",
    t.sheen ? "#define USE_SHEEN" : "",
    t.sheenColorMap ? "#define USE_SHEEN_COLORMAP" : "",
    t.sheenRoughnessMap ? "#define USE_SHEEN_ROUGHNESSMAP" : "",
    t.transmission ? "#define USE_TRANSMISSION" : "",
    t.transmissionMap ? "#define USE_TRANSMISSIONMAP" : "",
    t.thicknessMap ? "#define USE_THICKNESSMAP" : "",
    t.vertexTangents && t.flatShading === !1 ? "#define USE_TANGENT" : "",
    t.vertexColors || t.instancingColor || t.batchingColor ? "#define USE_COLOR" : "",
    t.vertexAlphas ? "#define USE_COLOR_ALPHA" : "",
    t.vertexUv1s ? "#define USE_UV1" : "",
    t.vertexUv2s ? "#define USE_UV2" : "",
    t.vertexUv3s ? "#define USE_UV3" : "",
    t.pointsUvs ? "#define USE_POINTS_UV" : "",
    t.gradientMap ? "#define USE_GRADIENTMAP" : "",
    t.flatShading ? "#define FLAT_SHADED" : "",
    t.doubleSided ? "#define DOUBLE_SIDED" : "",
    t.flipSided ? "#define FLIP_SIDED" : "",
    t.shadowMapEnabled ? "#define USE_SHADOWMAP" : "",
    t.shadowMapEnabled ? "#define " + l : "",
    t.premultipliedAlpha ? "#define PREMULTIPLIED_ALPHA" : "",
    t.numLightProbes > 0 ? "#define USE_LIGHT_PROBES" : "",
    t.decodeVideoTexture ? "#define DECODE_VIDEO_TEXTURE" : "",
    t.decodeVideoTextureEmissive ? "#define DECODE_VIDEO_TEXTURE_EMISSIVE" : "",
    t.logarithmicDepthBuffer ? "#define USE_LOGARITHMIC_DEPTH_BUFFER" : "",
    t.reversedDepthBuffer ? "#define USE_REVERSED_DEPTH_BUFFER" : "",
    "uniform mat4 viewMatrix;",
    "uniform vec3 cameraPosition;",
    "uniform bool isOrthographic;",
    t.toneMapping !== mn ? "#define TONE_MAPPING" : "",
    t.toneMapping !== mn ? Ze.tonemapping_pars_fragment : "",
    // this code is required here because it is used by the toneMapping() function defined below
    t.toneMapping !== mn ? tM("toneMapping", t.toneMapping) : "",
    t.dithering ? "#define DITHERING" : "",
    t.opaque ? "#define OPAQUE" : "",
    Ze.colorspace_pars_fragment,
    // this code is required here because it is used by the various encoding/decoding function defined below
    eM("linearToOutputTexel", t.outputColorSpace),
    iM(),
    t.useDepthPacking ? "#define DEPTH_PACKING " + t.depthPacking : "",
    `
`
  ].filter(Xr).join(`
`)), a = Xh(a), a = wp(a, t), a = Ep(a, t), o = Xh(o), o = wp(o, t), o = Ep(o, t), a = Tp(a), o = Tp(o), t.isRawShaderMaterial !== !0 && (v = `#version 300 es
`, g = [
    p,
    "#define attribute in",
    "#define varying out",
    "#define texture2D texture"
  ].join(`
`) + `
` + g, f = [
    "#define varying in",
    t.glslVersion === Uh ? "" : "layout(location = 0) out highp vec4 pc_fragColor;",
    t.glslVersion === Uh ? "" : "#define gl_FragColor pc_fragColor",
    "#define gl_FragDepthEXT gl_FragDepth",
    "#define texture2D texture",
    "#define textureCube texture",
    "#define texture2DProj textureProj",
    "#define texture2DLodEXT textureLod",
    "#define texture2DProjLodEXT textureProjLod",
    "#define textureCubeLodEXT textureLod",
    "#define texture2DGradEXT textureGrad",
    "#define texture2DProjGradEXT textureProjGrad",
    "#define textureCubeGradEXT textureGrad"
  ].join(`
`) + `
` + f);
  const x = v + g + a, y = v + f + o, A = bp(n, n.VERTEX_SHADER, x), S = bp(n, n.FRAGMENT_SHADER, y);
  n.attachShader(_, A), n.attachShader(_, S), t.index0AttributeName !== void 0 ? n.bindAttribLocation(_, 0, t.index0AttributeName) : t.morphTargets === !0 && n.bindAttribLocation(_, 0, "position"), n.linkProgram(_);
  function C(L) {
    if (r.debug.checkShaderErrors) {
      const N = n.getProgramInfoLog(_) || "", B = n.getShaderInfoLog(A) || "", W = n.getShaderInfoLog(S) || "", Z = N.trim(), X = B.trim(), ie = W.trim();
      let G = !0, he = !0;
      if (n.getProgramParameter(_, n.LINK_STATUS) === !1)
        if (G = !1, typeof r.debug.onShaderError == "function")
          r.debug.onShaderError(n, _, A, S);
        else {
          const me = Mp(n, A, "vertex"), Se = Mp(n, S, "fragment");
          console.error(
            "THREE.WebGLProgram: Shader Error " + n.getError() + " - VALIDATE_STATUS " + n.getProgramParameter(_, n.VALIDATE_STATUS) + `

Material Name: ` + L.name + `
Material Type: ` + L.type + `

Program Info Log: ` + Z + `
` + me + `
` + Se
          );
        }
      else Z !== "" ? console.warn("THREE.WebGLProgram: Program Info Log:", Z) : (X === "" || ie === "") && (he = !1);
      he && (L.diagnostics = {
        runnable: G,
        programLog: Z,
        vertexShader: {
          log: X,
          prefix: g
        },
        fragmentShader: {
          log: ie,
          prefix: f
        }
      });
    }
    n.deleteShader(A), n.deleteShader(S), P = new Xo(n, _), E = rM(n, _);
  }
  let P;
  this.getUniforms = function() {
    return P === void 0 && C(this), P;
  };
  let E;
  this.getAttributes = function() {
    return E === void 0 && C(this), E;
  };
  let w = t.rendererExtensionParallelShaderCompile === !1;
  return this.isReady = function() {
    return w === !1 && (w = n.getProgramParameter(_, $S)), w;
  }, this.destroy = function() {
    i.releaseStatesOfProgram(this), n.deleteProgram(_), this.program = void 0;
  }, this.type = t.shaderType, this.name = t.shaderName, this.id = KS++, this.cacheKey = e, this.usedTimes = 1, this.program = _, this.vertexShader = A, this.fragmentShader = S, this;
}
let _M = 0;
class yM {
  constructor() {
    this.shaderCache = /* @__PURE__ */ new Map(), this.materialCache = /* @__PURE__ */ new Map();
  }
  update(e) {
    const t = e.vertexShader, i = e.fragmentShader, n = this._getShaderStage(t), s = this._getShaderStage(i), a = this._getShaderCacheForMaterial(e);
    return a.has(n) === !1 && (a.add(n), n.usedTimes++), a.has(s) === !1 && (a.add(s), s.usedTimes++), this;
  }
  remove(e) {
    const t = this.materialCache.get(e);
    for (const i of t)
      i.usedTimes--, i.usedTimes === 0 && this.shaderCache.delete(i.code);
    return this.materialCache.delete(e), this;
  }
  getVertexShaderID(e) {
    return this._getShaderStage(e.vertexShader).id;
  }
  getFragmentShaderID(e) {
    return this._getShaderStage(e.fragmentShader).id;
  }
  dispose() {
    this.shaderCache.clear(), this.materialCache.clear();
  }
  _getShaderCacheForMaterial(e) {
    const t = this.materialCache;
    let i = t.get(e);
    return i === void 0 && (i = /* @__PURE__ */ new Set(), t.set(e, i)), i;
  }
  _getShaderStage(e) {
    const t = this.shaderCache;
    let i = t.get(e);
    return i === void 0 && (i = new vM(e), t.set(e, i)), i;
  }
}
class vM {
  constructor(e) {
    this.id = _M++, this.code = e, this.usedTimes = 0;
  }
}
function xM(r, e, t, i, n, s, a) {
  const o = new ql(), l = new yM(), c = /* @__PURE__ */ new Set(), h = [], d = n.logarithmicDepthBuffer, u = n.vertexTextures;
  let p = n.precision;
  const m = {
    MeshDepthMaterial: "depth",
    MeshDistanceMaterial: "distanceRGBA",
    MeshNormalMaterial: "normal",
    MeshBasicMaterial: "basic",
    MeshLambertMaterial: "lambert",
    MeshPhongMaterial: "phong",
    MeshToonMaterial: "toon",
    MeshStandardMaterial: "physical",
    MeshPhysicalMaterial: "physical",
    MeshMatcapMaterial: "matcap",
    LineBasicMaterial: "basic",
    LineDashedMaterial: "dashed",
    PointsMaterial: "points",
    ShadowMaterial: "shadow",
    SpriteMaterial: "sprite"
  };
  function _(E) {
    return c.add(E), E === 0 ? "uv" : `uv${E}`;
  }
  function g(E, w, L, N, B) {
    const W = N.fog, Z = B.geometry, X = E.isMeshStandardMaterial ? N.environment : null, ie = (E.isMeshStandardMaterial ? t : e).get(E.envMap || X), G = ie && ie.mapping === xr ? ie.image.height : null, he = m[E.type];
    E.precision !== null && (p = n.getMaxPrecision(E.precision), p !== E.precision && console.warn("THREE.WebGLProgram.getParameters:", E.precision, "not supported, using", p, "instead."));
    const me = Z.morphAttributes.position || Z.morphAttributes.normal || Z.morphAttributes.color, Se = me !== void 0 ? me.length : 0;
    let We = 0;
    Z.morphAttributes.position !== void 0 && (We = 1), Z.morphAttributes.normal !== void 0 && (We = 2), Z.morphAttributes.color !== void 0 && (We = 3);
    let Qe, ht, nt, Y;
    if (he) {
      const lt = si[he];
      Qe = lt.vertexShader, ht = lt.fragmentShader;
    } else
      Qe = E.vertexShader, ht = E.fragmentShader, l.update(E), nt = l.getVertexShaderID(E), Y = l.getFragmentShaderID(E);
    const te = r.getRenderTarget(), be = r.state.buffers.depth.getReversed(), Le = B.isInstancedMesh === !0, Ee = B.isBatchedMesh === !0, $e = !!E.map, yt = !!E.matcap, I = !!ie, ee = !!E.aoMap, K = !!E.lightMap, $ = !!E.bumpMap, j = !!E.normalMap, de = !!E.displacementMap, ne = !!E.emissiveMap, ue = !!E.metalnessMap, Ve = !!E.roughnessMap, ze = E.anisotropy > 0, R = E.clearcoat > 0, M = E.dispersion > 0, F = E.iridescence > 0, V = E.sheen > 0, Q = E.transmission > 0, q = ze && !!E.anisotropyMap, Re = R && !!E.clearcoatMap, ce = R && !!E.clearcoatNormalMap, Te = R && !!E.clearcoatRoughnessMap, Ae = F && !!E.iridescenceMap, se = F && !!E.iridescenceThicknessMap, ye = V && !!E.sheenColorMap, Be = V && !!E.sheenRoughnessMap, Pe = !!E.specularMap, ge = !!E.specularColorMap, qe = !!E.specularIntensityMap, D = Q && !!E.transmissionMap, le = Q && !!E.thicknessMap, fe = !!E.gradientMap, Me = !!E.alphaMap, re = E.alphaTest > 0, J = !!E.alphaHash, Ce = !!E.extensions;
    let Ge = mn;
    E.toneMapped && (te === null || te.isXRRenderTarget === !0) && (Ge = r.toneMapping);
    const vt = {
      shaderID: he,
      shaderType: E.type,
      shaderName: E.name,
      vertexShader: Qe,
      fragmentShader: ht,
      defines: E.defines,
      customVertexShaderID: nt,
      customFragmentShaderID: Y,
      isRawShaderMaterial: E.isRawShaderMaterial === !0,
      glslVersion: E.glslVersion,
      precision: p,
      batching: Ee,
      batchingColor: Ee && B._colorsTexture !== null,
      instancing: Le,
      instancingColor: Le && B.instanceColor !== null,
      instancingMorph: Le && B.morphTexture !== null,
      supportsVertexTextures: u,
      outputColorSpace: te === null ? r.outputColorSpace : te.isXRRenderTarget === !0 ? te.texture.colorSpace : On,
      alphaToCoverage: !!E.alphaToCoverage,
      map: $e,
      matcap: yt,
      envMap: I,
      envMapMode: I && ie.mapping,
      envMapCubeUVHeight: G,
      aoMap: ee,
      lightMap: K,
      bumpMap: $,
      normalMap: j,
      displacementMap: u && de,
      emissiveMap: ne,
      normalMapObjectSpace: j && E.normalMapType === Qf,
      normalMapTangentSpace: j && E.normalMapType === zn,
      metalnessMap: ue,
      roughnessMap: Ve,
      anisotropy: ze,
      anisotropyMap: q,
      clearcoat: R,
      clearcoatMap: Re,
      clearcoatNormalMap: ce,
      clearcoatRoughnessMap: Te,
      dispersion: M,
      iridescence: F,
      iridescenceMap: Ae,
      iridescenceThicknessMap: se,
      sheen: V,
      sheenColorMap: ye,
      sheenRoughnessMap: Be,
      specularMap: Pe,
      specularColorMap: ge,
      specularIntensityMap: qe,
      transmission: Q,
      transmissionMap: D,
      thicknessMap: le,
      gradientMap: fe,
      opaque: E.transparent === !1 && E.blending === Dn && E.alphaToCoverage === !1,
      alphaMap: Me,
      alphaTest: re,
      alphaHash: J,
      combine: E.combine,
      //
      mapUv: $e && _(E.map.channel),
      aoMapUv: ee && _(E.aoMap.channel),
      lightMapUv: K && _(E.lightMap.channel),
      bumpMapUv: $ && _(E.bumpMap.channel),
      normalMapUv: j && _(E.normalMap.channel),
      displacementMapUv: de && _(E.displacementMap.channel),
      emissiveMapUv: ne && _(E.emissiveMap.channel),
      metalnessMapUv: ue && _(E.metalnessMap.channel),
      roughnessMapUv: Ve && _(E.roughnessMap.channel),
      anisotropyMapUv: q && _(E.anisotropyMap.channel),
      clearcoatMapUv: Re && _(E.clearcoatMap.channel),
      clearcoatNormalMapUv: ce && _(E.clearcoatNormalMap.channel),
      clearcoatRoughnessMapUv: Te && _(E.clearcoatRoughnessMap.channel),
      iridescenceMapUv: Ae && _(E.iridescenceMap.channel),
      iridescenceThicknessMapUv: se && _(E.iridescenceThicknessMap.channel),
      sheenColorMapUv: ye && _(E.sheenColorMap.channel),
      sheenRoughnessMapUv: Be && _(E.sheenRoughnessMap.channel),
      specularMapUv: Pe && _(E.specularMap.channel),
      specularColorMapUv: ge && _(E.specularColorMap.channel),
      specularIntensityMapUv: qe && _(E.specularIntensityMap.channel),
      transmissionMapUv: D && _(E.transmissionMap.channel),
      thicknessMapUv: le && _(E.thicknessMap.channel),
      alphaMapUv: Me && _(E.alphaMap.channel),
      //
      vertexTangents: !!Z.attributes.tangent && (j || ze),
      vertexColors: E.vertexColors,
      vertexAlphas: E.vertexColors === !0 && !!Z.attributes.color && Z.attributes.color.itemSize === 4,
      pointsUvs: B.isPoints === !0 && !!Z.attributes.uv && ($e || Me),
      fog: !!W,
      useFog: E.fog === !0,
      fogExp2: !!W && W.isFogExp2,
      flatShading: E.flatShading === !0 && E.wireframe === !1,
      sizeAttenuation: E.sizeAttenuation === !0,
      logarithmicDepthBuffer: d,
      reversedDepthBuffer: be,
      skinning: B.isSkinnedMesh === !0,
      morphTargets: Z.morphAttributes.position !== void 0,
      morphNormals: Z.morphAttributes.normal !== void 0,
      morphColors: Z.morphAttributes.color !== void 0,
      morphTargetsCount: Se,
      morphTextureStride: We,
      numDirLights: w.directional.length,
      numPointLights: w.point.length,
      numSpotLights: w.spot.length,
      numSpotLightMaps: w.spotLightMap.length,
      numRectAreaLights: w.rectArea.length,
      numHemiLights: w.hemi.length,
      numDirLightShadows: w.directionalShadowMap.length,
      numPointLightShadows: w.pointShadowMap.length,
      numSpotLightShadows: w.spotShadowMap.length,
      numSpotLightShadowsWithMaps: w.numSpotLightShadowsWithMaps,
      numLightProbes: w.numLightProbes,
      numClippingPlanes: a.numPlanes,
      numClipIntersection: a.numIntersection,
      dithering: E.dithering,
      shadowMapEnabled: r.shadowMap.enabled && L.length > 0,
      shadowMapType: r.shadowMap.type,
      toneMapping: Ge,
      decodeVideoTexture: $e && E.map.isVideoTexture === !0 && et.getTransfer(E.map.colorSpace) === ut,
      decodeVideoTextureEmissive: ne && E.emissiveMap.isVideoTexture === !0 && et.getTransfer(E.emissiveMap.colorSpace) === ut,
      premultipliedAlpha: E.premultipliedAlpha,
      doubleSided: E.side === ri,
      flipSided: E.side === zt,
      useDepthPacking: E.depthPacking >= 0,
      depthPacking: E.depthPacking || 0,
      index0AttributeName: E.index0AttributeName,
      extensionClipCullDistance: Ce && E.extensions.clipCullDistance === !0 && i.has("WEBGL_clip_cull_distance"),
      extensionMultiDraw: (Ce && E.extensions.multiDraw === !0 || Ee) && i.has("WEBGL_multi_draw"),
      rendererExtensionParallelShaderCompile: i.has("KHR_parallel_shader_compile"),
      customProgramCacheKey: E.customProgramCacheKey()
    };
    return vt.vertexUv1s = c.has(1), vt.vertexUv2s = c.has(2), vt.vertexUv3s = c.has(3), c.clear(), vt;
  }
  function f(E) {
    const w = [];
    if (E.shaderID ? w.push(E.shaderID) : (w.push(E.customVertexShaderID), w.push(E.customFragmentShaderID)), E.defines !== void 0)
      for (const L in E.defines)
        w.push(L), w.push(E.defines[L]);
    return E.isRawShaderMaterial === !1 && (v(w, E), x(w, E), w.push(r.outputColorSpace)), w.push(E.customProgramCacheKey), w.join();
  }
  function v(E, w) {
    E.push(w.precision), E.push(w.outputColorSpace), E.push(w.envMapMode), E.push(w.envMapCubeUVHeight), E.push(w.mapUv), E.push(w.alphaMapUv), E.push(w.lightMapUv), E.push(w.aoMapUv), E.push(w.bumpMapUv), E.push(w.normalMapUv), E.push(w.displacementMapUv), E.push(w.emissiveMapUv), E.push(w.metalnessMapUv), E.push(w.roughnessMapUv), E.push(w.anisotropyMapUv), E.push(w.clearcoatMapUv), E.push(w.clearcoatNormalMapUv), E.push(w.clearcoatRoughnessMapUv), E.push(w.iridescenceMapUv), E.push(w.iridescenceThicknessMapUv), E.push(w.sheenColorMapUv), E.push(w.sheenRoughnessMapUv), E.push(w.specularMapUv), E.push(w.specularColorMapUv), E.push(w.specularIntensityMapUv), E.push(w.transmissionMapUv), E.push(w.thicknessMapUv), E.push(w.combine), E.push(w.fogExp2), E.push(w.sizeAttenuation), E.push(w.morphTargetsCount), E.push(w.morphAttributeCount), E.push(w.numDirLights), E.push(w.numPointLights), E.push(w.numSpotLights), E.push(w.numSpotLightMaps), E.push(w.numHemiLights), E.push(w.numRectAreaLights), E.push(w.numDirLightShadows), E.push(w.numPointLightShadows), E.push(w.numSpotLightShadows), E.push(w.numSpotLightShadowsWithMaps), E.push(w.numLightProbes), E.push(w.shadowMapType), E.push(w.toneMapping), E.push(w.numClippingPlanes), E.push(w.numClipIntersection), E.push(w.depthPacking);
  }
  function x(E, w) {
    o.disableAll(), w.supportsVertexTextures && o.enable(0), w.instancing && o.enable(1), w.instancingColor && o.enable(2), w.instancingMorph && o.enable(3), w.matcap && o.enable(4), w.envMap && o.enable(5), w.normalMapObjectSpace && o.enable(6), w.normalMapTangentSpace && o.enable(7), w.clearcoat && o.enable(8), w.iridescence && o.enable(9), w.alphaTest && o.enable(10), w.vertexColors && o.enable(11), w.vertexAlphas && o.enable(12), w.vertexUv1s && o.enable(13), w.vertexUv2s && o.enable(14), w.vertexUv3s && o.enable(15), w.vertexTangents && o.enable(16), w.anisotropy && o.enable(17), w.alphaHash && o.enable(18), w.batching && o.enable(19), w.dispersion && o.enable(20), w.batchingColor && o.enable(21), w.gradientMap && o.enable(22), E.push(o.mask), o.disableAll(), w.fog && o.enable(0), w.useFog && o.enable(1), w.flatShading && o.enable(2), w.logarithmicDepthBuffer && o.enable(3), w.reversedDepthBuffer && o.enable(4), w.skinning && o.enable(5), w.morphTargets && o.enable(6), w.morphNormals && o.enable(7), w.morphColors && o.enable(8), w.premultipliedAlpha && o.enable(9), w.shadowMapEnabled && o.enable(10), w.doubleSided && o.enable(11), w.flipSided && o.enable(12), w.useDepthPacking && o.enable(13), w.dithering && o.enable(14), w.transmission && o.enable(15), w.sheen && o.enable(16), w.opaque && o.enable(17), w.pointsUvs && o.enable(18), w.decodeVideoTexture && o.enable(19), w.decodeVideoTextureEmissive && o.enable(20), w.alphaToCoverage && o.enable(21), E.push(o.mask);
  }
  function y(E) {
    const w = m[E.type];
    let L;
    if (w) {
      const N = si[w];
      L = Zl.clone(N.uniforms);
    } else
      L = E.uniforms;
    return L;
  }
  function A(E, w) {
    let L;
    for (let N = 0, B = h.length; N < B; N++) {
      const W = h[N];
      if (W.cacheKey === w) {
        L = W, ++L.usedTimes;
        break;
      }
    }
    return L === void 0 && (L = new gM(r, w, E, s), h.push(L)), L;
  }
  function S(E) {
    if (--E.usedTimes === 0) {
      const w = h.indexOf(E);
      h[w] = h[h.length - 1], h.pop(), E.destroy();
    }
  }
  function C(E) {
    l.remove(E);
  }
  function P() {
    l.dispose();
  }
  return {
    getParameters: g,
    getProgramCacheKey: f,
    getUniforms: y,
    acquireProgram: A,
    releaseProgram: S,
    releaseShaderCache: C,
    // Exposed for resource monitoring & error feedback via renderer.info:
    programs: h,
    dispose: P
  };
}
function bM() {
  let r = /* @__PURE__ */ new WeakMap();
  function e(a) {
    return r.has(a);
  }
  function t(a) {
    let o = r.get(a);
    return o === void 0 && (o = {}, r.set(a, o)), o;
  }
  function i(a) {
    r.delete(a);
  }
  function n(a, o, l) {
    r.get(a)[o] = l;
  }
  function s() {
    r = /* @__PURE__ */ new WeakMap();
  }
  return {
    has: e,
    get: t,
    remove: i,
    update: n,
    dispose: s
  };
}
function SM(r, e) {
  return r.groupOrder !== e.groupOrder ? r.groupOrder - e.groupOrder : r.renderOrder !== e.renderOrder ? r.renderOrder - e.renderOrder : r.material.id !== e.material.id ? r.material.id - e.material.id : r.z !== e.z ? r.z - e.z : r.id - e.id;
}
function Cp(r, e) {
  return r.groupOrder !== e.groupOrder ? r.groupOrder - e.groupOrder : r.renderOrder !== e.renderOrder ? r.renderOrder - e.renderOrder : r.z !== e.z ? e.z - r.z : r.id - e.id;
}
function Rp() {
  const r = [];
  let e = 0;
  const t = [], i = [], n = [];
  function s() {
    e = 0, t.length = 0, i.length = 0, n.length = 0;
  }
  function a(d, u, p, m, _, g) {
    let f = r[e];
    return f === void 0 ? (f = {
      id: d.id,
      object: d,
      geometry: u,
      material: p,
      groupOrder: m,
      renderOrder: d.renderOrder,
      z: _,
      group: g
    }, r[e] = f) : (f.id = d.id, f.object = d, f.geometry = u, f.material = p, f.groupOrder = m, f.renderOrder = d.renderOrder, f.z = _, f.group = g), e++, f;
  }
  function o(d, u, p, m, _, g) {
    const f = a(d, u, p, m, _, g);
    p.transmission > 0 ? i.push(f) : p.transparent === !0 ? n.push(f) : t.push(f);
  }
  function l(d, u, p, m, _, g) {
    const f = a(d, u, p, m, _, g);
    p.transmission > 0 ? i.unshift(f) : p.transparent === !0 ? n.unshift(f) : t.unshift(f);
  }
  function c(d, u) {
    t.length > 1 && t.sort(d || SM), i.length > 1 && i.sort(u || Cp), n.length > 1 && n.sort(u || Cp);
  }
  function h() {
    for (let d = e, u = r.length; d < u; d++) {
      const p = r[d];
      if (p.id === null) break;
      p.id = null, p.object = null, p.geometry = null, p.material = null, p.group = null;
    }
  }
  return {
    opaque: t,
    transmissive: i,
    transparent: n,
    init: s,
    push: o,
    unshift: l,
    finish: h,
    sort: c
  };
}
function MM() {
  let r = /* @__PURE__ */ new WeakMap();
  function e(i, n) {
    const s = r.get(i);
    let a;
    return s === void 0 ? (a = new Rp(), r.set(i, [a])) : n >= s.length ? (a = new Rp(), s.push(a)) : a = s[n], a;
  }
  function t() {
    r = /* @__PURE__ */ new WeakMap();
  }
  return {
    get: e,
    dispose: t
  };
}
function wM() {
  const r = {};
  return {
    get: function(e) {
      if (r[e.id] !== void 0)
        return r[e.id];
      let t;
      switch (e.type) {
        case "DirectionalLight":
          t = {
            direction: new b(),
            color: new oe()
          };
          break;
        case "SpotLight":
          t = {
            position: new b(),
            direction: new b(),
            color: new oe(),
            distance: 0,
            coneCos: 0,
            penumbraCos: 0,
            decay: 0
          };
          break;
        case "PointLight":
          t = {
            position: new b(),
            color: new oe(),
            distance: 0,
            decay: 0
          };
          break;
        case "HemisphereLight":
          t = {
            direction: new b(),
            skyColor: new oe(),
            groundColor: new oe()
          };
          break;
        case "RectAreaLight":
          t = {
            color: new oe(),
            position: new b(),
            halfWidth: new b(),
            halfHeight: new b()
          };
          break;
      }
      return r[e.id] = t, t;
    }
  };
}
function EM() {
  const r = {};
  return {
    get: function(e) {
      if (r[e.id] !== void 0)
        return r[e.id];
      let t;
      switch (e.type) {
        case "DirectionalLight":
          t = {
            shadowIntensity: 1,
            shadowBias: 0,
            shadowNormalBias: 0,
            shadowRadius: 1,
            shadowMapSize: new H()
          };
          break;
        case "SpotLight":
          t = {
            shadowIntensity: 1,
            shadowBias: 0,
            shadowNormalBias: 0,
            shadowRadius: 1,
            shadowMapSize: new H()
          };
          break;
        case "PointLight":
          t = {
            shadowIntensity: 1,
            shadowBias: 0,
            shadowNormalBias: 0,
            shadowRadius: 1,
            shadowMapSize: new H(),
            shadowCameraNear: 1,
            shadowCameraFar: 1e3
          };
          break;
      }
      return r[e.id] = t, t;
    }
  };
}
let TM = 0;
function AM(r, e) {
  return (e.castShadow ? 2 : 0) - (r.castShadow ? 2 : 0) + (e.map ? 1 : 0) - (r.map ? 1 : 0);
}
function CM(r) {
  const e = new wM(), t = EM(), i = {
    version: 0,
    hash: {
      directionalLength: -1,
      pointLength: -1,
      spotLength: -1,
      rectAreaLength: -1,
      hemiLength: -1,
      numDirectionalShadows: -1,
      numPointShadows: -1,
      numSpotShadows: -1,
      numSpotMaps: -1,
      numLightProbes: -1
    },
    ambient: [0, 0, 0],
    probe: [],
    directional: [],
    directionalShadow: [],
    directionalShadowMap: [],
    directionalShadowMatrix: [],
    spot: [],
    spotLightMap: [],
    spotShadow: [],
    spotShadowMap: [],
    spotLightMatrix: [],
    rectArea: [],
    rectAreaLTC1: null,
    rectAreaLTC2: null,
    point: [],
    pointShadow: [],
    pointShadowMap: [],
    pointShadowMatrix: [],
    hemi: [],
    numSpotLightShadowsWithMaps: 0,
    numLightProbes: 0
  };
  for (let c = 0; c < 9; c++) i.probe.push(new b());
  const n = new b(), s = new Ne(), a = new Ne();
  function o(c) {
    let h = 0, d = 0, u = 0;
    for (let E = 0; E < 9; E++) i.probe[E].set(0, 0, 0);
    let p = 0, m = 0, _ = 0, g = 0, f = 0, v = 0, x = 0, y = 0, A = 0, S = 0, C = 0;
    c.sort(AM);
    for (let E = 0, w = c.length; E < w; E++) {
      const L = c[E], N = L.color, B = L.intensity, W = L.distance, Z = L.shadow && L.shadow.map ? L.shadow.map.texture : null;
      if (L.isAmbientLight)
        h += N.r * B, d += N.g * B, u += N.b * B;
      else if (L.isLightProbe) {
        for (let X = 0; X < 9; X++)
          i.probe[X].addScaledVector(L.sh.coefficients[X], B);
        C++;
      } else if (L.isDirectionalLight) {
        const X = e.get(L);
        if (X.color.copy(L.color).multiplyScalar(L.intensity), L.castShadow) {
          const ie = L.shadow, G = t.get(L);
          G.shadowIntensity = ie.intensity, G.shadowBias = ie.bias, G.shadowNormalBias = ie.normalBias, G.shadowRadius = ie.radius, G.shadowMapSize = ie.mapSize, i.directionalShadow[p] = G, i.directionalShadowMap[p] = Z, i.directionalShadowMatrix[p] = L.shadow.matrix, v++;
        }
        i.directional[p] = X, p++;
      } else if (L.isSpotLight) {
        const X = e.get(L);
        X.position.setFromMatrixPosition(L.matrixWorld), X.color.copy(N).multiplyScalar(B), X.distance = W, X.coneCos = Math.cos(L.angle), X.penumbraCos = Math.cos(L.angle * (1 - L.penumbra)), X.decay = L.decay, i.spot[_] = X;
        const ie = L.shadow;
        if (L.map && (i.spotLightMap[A] = L.map, A++, ie.updateMatrices(L), L.castShadow && S++), i.spotLightMatrix[_] = ie.matrix, L.castShadow) {
          const G = t.get(L);
          G.shadowIntensity = ie.intensity, G.shadowBias = ie.bias, G.shadowNormalBias = ie.normalBias, G.shadowRadius = ie.radius, G.shadowMapSize = ie.mapSize, i.spotShadow[_] = G, i.spotShadowMap[_] = Z, y++;
        }
        _++;
      } else if (L.isRectAreaLight) {
        const X = e.get(L);
        X.color.copy(N).multiplyScalar(B), X.halfWidth.set(L.width * 0.5, 0, 0), X.halfHeight.set(0, L.height * 0.5, 0), i.rectArea[g] = X, g++;
      } else if (L.isPointLight) {
        const X = e.get(L);
        if (X.color.copy(L.color).multiplyScalar(L.intensity), X.distance = L.distance, X.decay = L.decay, L.castShadow) {
          const ie = L.shadow, G = t.get(L);
          G.shadowIntensity = ie.intensity, G.shadowBias = ie.bias, G.shadowNormalBias = ie.normalBias, G.shadowRadius = ie.radius, G.shadowMapSize = ie.mapSize, G.shadowCameraNear = ie.camera.near, G.shadowCameraFar = ie.camera.far, i.pointShadow[m] = G, i.pointShadowMap[m] = Z, i.pointShadowMatrix[m] = L.shadow.matrix, x++;
        }
        i.point[m] = X, m++;
      } else if (L.isHemisphereLight) {
        const X = e.get(L);
        X.skyColor.copy(L.color).multiplyScalar(B), X.groundColor.copy(L.groundColor).multiplyScalar(B), i.hemi[f] = X, f++;
      }
    }
    g > 0 && (r.has("OES_texture_float_linear") === !0 ? (i.rectAreaLTC1 = pe.LTC_FLOAT_1, i.rectAreaLTC2 = pe.LTC_FLOAT_2) : (i.rectAreaLTC1 = pe.LTC_HALF_1, i.rectAreaLTC2 = pe.LTC_HALF_2)), i.ambient[0] = h, i.ambient[1] = d, i.ambient[2] = u;
    const P = i.hash;
    (P.directionalLength !== p || P.pointLength !== m || P.spotLength !== _ || P.rectAreaLength !== g || P.hemiLength !== f || P.numDirectionalShadows !== v || P.numPointShadows !== x || P.numSpotShadows !== y || P.numSpotMaps !== A || P.numLightProbes !== C) && (i.directional.length = p, i.spot.length = _, i.rectArea.length = g, i.point.length = m, i.hemi.length = f, i.directionalShadow.length = v, i.directionalShadowMap.length = v, i.pointShadow.length = x, i.pointShadowMap.length = x, i.spotShadow.length = y, i.spotShadowMap.length = y, i.directionalShadowMatrix.length = v, i.pointShadowMatrix.length = x, i.spotLightMatrix.length = y + A - S, i.spotLightMap.length = A, i.numSpotLightShadowsWithMaps = S, i.numLightProbes = C, P.directionalLength = p, P.pointLength = m, P.spotLength = _, P.rectAreaLength = g, P.hemiLength = f, P.numDirectionalShadows = v, P.numPointShadows = x, P.numSpotShadows = y, P.numSpotMaps = A, P.numLightProbes = C, i.version = TM++);
  }
  function l(c, h) {
    let d = 0, u = 0, p = 0, m = 0, _ = 0;
    const g = h.matrixWorldInverse;
    for (let f = 0, v = c.length; f < v; f++) {
      const x = c[f];
      if (x.isDirectionalLight) {
        const y = i.directional[d];
        y.direction.setFromMatrixPosition(x.matrixWorld), n.setFromMatrixPosition(x.target.matrixWorld), y.direction.sub(n), y.direction.transformDirection(g), d++;
      } else if (x.isSpotLight) {
        const y = i.spot[p];
        y.position.setFromMatrixPosition(x.matrixWorld), y.position.applyMatrix4(g), y.direction.setFromMatrixPosition(x.matrixWorld), n.setFromMatrixPosition(x.target.matrixWorld), y.direction.sub(n), y.direction.transformDirection(g), p++;
      } else if (x.isRectAreaLight) {
        const y = i.rectArea[m];
        y.position.setFromMatrixPosition(x.matrixWorld), y.position.applyMatrix4(g), a.identity(), s.copy(x.matrixWorld), s.premultiply(g), a.extractRotation(s), y.halfWidth.set(x.width * 0.5, 0, 0), y.halfHeight.set(0, x.height * 0.5, 0), y.halfWidth.applyMatrix4(a), y.halfHeight.applyMatrix4(a), m++;
      } else if (x.isPointLight) {
        const y = i.point[u];
        y.position.setFromMatrixPosition(x.matrixWorld), y.position.applyMatrix4(g), u++;
      } else if (x.isHemisphereLight) {
        const y = i.hemi[_];
        y.direction.setFromMatrixPosition(x.matrixWorld), y.direction.transformDirection(g), _++;
      }
    }
  }
  return {
    setup: o,
    setupView: l,
    state: i
  };
}
function Pp(r) {
  const e = new CM(r), t = [], i = [];
  function n(h) {
    c.camera = h, t.length = 0, i.length = 0;
  }
  function s(h) {
    t.push(h);
  }
  function a(h) {
    i.push(h);
  }
  function o() {
    e.setup(t);
  }
  function l(h) {
    e.setupView(t, h);
  }
  const c = {
    lightsArray: t,
    shadowsArray: i,
    camera: null,
    lights: e,
    transmissionRenderTarget: {}
  };
  return {
    init: n,
    state: c,
    setupLights: o,
    setupLightsView: l,
    pushLight: s,
    pushShadow: a
  };
}
function RM(r) {
  let e = /* @__PURE__ */ new WeakMap();
  function t(n, s = 0) {
    const a = e.get(n);
    let o;
    return a === void 0 ? (o = new Pp(r), e.set(n, [o])) : s >= a.length ? (o = new Pp(r), a.push(o)) : o = a[s], o;
  }
  function i() {
    e = /* @__PURE__ */ new WeakMap();
  }
  return {
    get: t,
    dispose: i
  };
}
const PM = `void main() {
	gl_Position = vec4( position, 1.0 );
}`, LM = `uniform sampler2D shadow_pass;
uniform vec2 resolution;
uniform float radius;
#include <packing>
void main() {
	const float samples = float( VSM_SAMPLES );
	float mean = 0.0;
	float squared_mean = 0.0;
	float uvStride = samples <= 1.0 ? 0.0 : 2.0 / ( samples - 1.0 );
	float uvStart = samples <= 1.0 ? 0.0 : - 1.0;
	for ( float i = 0.0; i < samples; i ++ ) {
		float uvOffset = uvStart + i * uvStride;
		#ifdef HORIZONTAL_PASS
			vec2 distribution = unpackRGBATo2Half( texture2D( shadow_pass, ( gl_FragCoord.xy + vec2( uvOffset, 0.0 ) * radius ) / resolution ) );
			mean += distribution.x;
			squared_mean += distribution.y * distribution.y + distribution.x * distribution.x;
		#else
			float depth = unpackRGBAToDepth( texture2D( shadow_pass, ( gl_FragCoord.xy + vec2( 0.0, uvOffset ) * radius ) / resolution ) );
			mean += depth;
			squared_mean += depth * depth;
		#endif
	}
	mean = mean / samples;
	squared_mean = squared_mean / samples;
	float std_dev = sqrt( squared_mean - mean * mean );
	gl_FragColor = pack2HalfToRGBA( vec2( mean, std_dev ) );
}`;
function IM(r, e, t) {
  let i = new Sr();
  const n = new H(), s = new H(), a = new Ye(), o = new wd({ depthPacking: Jf }), l = new Ed(), c = {}, h = t.maxTextureSize, d = { [Di]: zt, [zt]: Di, [ri]: ri }, u = new Ci({
    defines: {
      VSM_SAMPLES: 8
    },
    uniforms: {
      shadow_pass: { value: null },
      resolution: { value: new H() },
      radius: { value: 4 }
    },
    vertexShader: PM,
    fragmentShader: LM
  }), p = u.clone();
  p.defines.HORIZONTAL_PASS = 1;
  const m = new Ue();
  m.setAttribute(
    "position",
    new it(
      new Float32Array([-1, -1, 0.5, 3, -1, 0.5, -1, 3, 0.5]),
      3
    )
  );
  const _ = new Je(m, u), g = this;
  this.enabled = !1, this.autoUpdate = !0, this.needsUpdate = !1, this.type = jh;
  let f = this.type;
  this.render = function(S, C, P) {
    if (g.enabled === !1 || g.autoUpdate === !1 && g.needsUpdate === !1 || S.length === 0) return;
    const E = r.getRenderTarget(), w = r.getActiveCubeFace(), L = r.getActiveMipmapLevel(), N = r.state;
    N.setBlending(fn), N.buffers.depth.getReversed() === !0 ? N.buffers.color.setClear(0, 0, 0, 0) : N.buffers.color.setClear(1, 1, 1, 1), N.buffers.depth.setTest(!0), N.setScissorTest(!1);
    const B = f !== Yi && this.type === Yi, W = f === Yi && this.type !== Yi;
    for (let Z = 0, X = S.length; Z < X; Z++) {
      const ie = S[Z], G = ie.shadow;
      if (G === void 0) {
        console.warn("THREE.WebGLShadowMap:", ie, "has no shadow.");
        continue;
      }
      if (G.autoUpdate === !1 && G.needsUpdate === !1) continue;
      n.copy(G.mapSize);
      const he = G.getFrameExtents();
      if (n.multiply(he), s.copy(G.mapSize), (n.x > h || n.y > h) && (n.x > h && (s.x = Math.floor(h / he.x), n.x = s.x * he.x, G.mapSize.x = s.x), n.y > h && (s.y = Math.floor(h / he.y), n.y = s.y * he.y, G.mapSize.y = s.y)), G.map === null || B === !0 || W === !0) {
        const Se = this.type !== Yi ? { minFilter: Xt, magFilter: Xt } : {};
        G.map !== null && G.map.dispose(), G.map = new nn(n.x, n.y, Se), G.map.texture.name = ie.name + ".shadowMap", G.camera.updateProjectionMatrix();
      }
      r.setRenderTarget(G.map), r.clear();
      const me = G.getViewportCount();
      for (let Se = 0; Se < me; Se++) {
        const We = G.getViewport(Se);
        a.set(
          s.x * We.x,
          s.y * We.y,
          s.x * We.z,
          s.y * We.w
        ), N.viewport(a), G.updateMatrices(ie, Se), i = G.getFrustum(), y(C, P, G.camera, ie, this.type);
      }
      G.isPointLightShadow !== !0 && this.type === Yi && v(G, P), G.needsUpdate = !1;
    }
    f = this.type, g.needsUpdate = !1, r.setRenderTarget(E, w, L);
  };
  function v(S, C) {
    const P = e.update(_);
    u.defines.VSM_SAMPLES !== S.blurSamples && (u.defines.VSM_SAMPLES = S.blurSamples, p.defines.VSM_SAMPLES = S.blurSamples, u.needsUpdate = !0, p.needsUpdate = !0), S.mapPass === null && (S.mapPass = new nn(n.x, n.y)), u.uniforms.shadow_pass.value = S.map.texture, u.uniforms.resolution.value = S.mapSize, u.uniforms.radius.value = S.radius, r.setRenderTarget(S.mapPass), r.clear(), r.renderBufferDirect(C, null, P, u, _, null), p.uniforms.shadow_pass.value = S.mapPass.texture, p.uniforms.resolution.value = S.mapSize, p.uniforms.radius.value = S.radius, r.setRenderTarget(S.map), r.clear(), r.renderBufferDirect(C, null, P, p, _, null);
  }
  function x(S, C, P, E) {
    let w = null;
    const L = P.isPointLight === !0 ? S.customDistanceMaterial : S.customDepthMaterial;
    if (L !== void 0)
      w = L;
    else if (w = P.isPointLight === !0 ? l : o, r.localClippingEnabled && C.clipShadows === !0 && Array.isArray(C.clippingPlanes) && C.clippingPlanes.length !== 0 || C.displacementMap && C.displacementScale !== 0 || C.alphaMap && C.alphaTest > 0 || C.map && C.alphaTest > 0 || C.alphaToCoverage === !0) {
      const N = w.uuid, B = C.uuid;
      let W = c[N];
      W === void 0 && (W = {}, c[N] = W);
      let Z = W[B];
      Z === void 0 && (Z = w.clone(), W[B] = Z, C.addEventListener("dispose", A)), w = Z;
    }
    if (w.visible = C.visible, w.wireframe = C.wireframe, E === Yi ? w.side = C.shadowSide !== null ? C.shadowSide : C.side : w.side = C.shadowSide !== null ? C.shadowSide : d[C.side], w.alphaMap = C.alphaMap, w.alphaTest = C.alphaToCoverage === !0 ? 0.5 : C.alphaTest, w.map = C.map, w.clipShadows = C.clipShadows, w.clippingPlanes = C.clippingPlanes, w.clipIntersection = C.clipIntersection, w.displacementMap = C.displacementMap, w.displacementScale = C.displacementScale, w.displacementBias = C.displacementBias, w.wireframeLinewidth = C.wireframeLinewidth, w.linewidth = C.linewidth, P.isPointLight === !0 && w.isMeshDistanceMaterial === !0) {
      const N = r.properties.get(w);
      N.light = P;
    }
    return w;
  }
  function y(S, C, P, E, w) {
    if (S.visible === !1) return;
    if (S.layers.test(C.layers) && (S.isMesh || S.isLine || S.isPoints) && (S.castShadow || S.receiveShadow && w === Yi) && (!S.frustumCulled || i.intersectsObject(S))) {
      S.modelViewMatrix.multiplyMatrices(P.matrixWorldInverse, S.matrixWorld);
      const B = e.update(S), W = S.material;
      if (Array.isArray(W)) {
        const Z = B.groups;
        for (let X = 0, ie = Z.length; X < ie; X++) {
          const G = Z[X], he = W[G.materialIndex];
          if (he && he.visible) {
            const me = x(S, he, E, w);
            S.onBeforeShadow(r, S, C, P, B, me, G), r.renderBufferDirect(P, null, B, me, S, G), S.onAfterShadow(r, S, C, P, B, me, G);
          }
        }
      } else if (W.visible) {
        const Z = x(S, W, E, w);
        S.onBeforeShadow(r, S, C, P, B, Z, null), r.renderBufferDirect(P, null, B, Z, S, null), S.onAfterShadow(r, S, C, P, B, Z, null);
      }
    }
    const N = S.children;
    for (let B = 0, W = N.length; B < W; B++)
      y(N[B], C, P, E, w);
  }
  function A(S) {
    S.target.removeEventListener("dispose", A);
    for (const P in c) {
      const E = c[P], w = S.target.uuid;
      w in E && (E[w].dispose(), delete E[w]);
    }
  }
}
const DM = {
  [Yo]: jo,
  [$o]: Qo,
  [Ko]: el,
  [vs]: Jo,
  [jo]: Yo,
  [Qo]: $o,
  [el]: Ko,
  [Jo]: vs
};
function NM(r, e) {
  function t() {
    let D = !1;
    const le = new Ye();
    let fe = null;
    const Me = new Ye(0, 0, 0, 0);
    return {
      setMask: function(re) {
        fe !== re && !D && (r.colorMask(re, re, re, re), fe = re);
      },
      setLocked: function(re) {
        D = re;
      },
      setClear: function(re, J, Ce, Ge, vt) {
        vt === !0 && (re *= Ge, J *= Ge, Ce *= Ge), le.set(re, J, Ce, Ge), Me.equals(le) === !1 && (r.clearColor(re, J, Ce, Ge), Me.copy(le));
      },
      reset: function() {
        D = !1, fe = null, Me.set(-1, 0, 0, 0);
      }
    };
  }
  function i() {
    let D = !1, le = !1, fe = null, Me = null, re = null;
    return {
      setReversed: function(J) {
        if (le !== J) {
          const Ce = e.get("EXT_clip_control");
          J ? Ce.clipControlEXT(Ce.LOWER_LEFT_EXT, Ce.ZERO_TO_ONE_EXT) : Ce.clipControlEXT(Ce.LOWER_LEFT_EXT, Ce.NEGATIVE_ONE_TO_ONE_EXT), le = J;
          const Ge = re;
          re = null, this.setClear(Ge);
        }
      },
      getReversed: function() {
        return le;
      },
      setTest: function(J) {
        J ? te(r.DEPTH_TEST) : be(r.DEPTH_TEST);
      },
      setMask: function(J) {
        fe !== J && !D && (r.depthMask(J), fe = J);
      },
      setFunc: function(J) {
        if (le && (J = DM[J]), Me !== J) {
          switch (J) {
            case Yo:
              r.depthFunc(r.NEVER);
              break;
            case jo:
              r.depthFunc(r.ALWAYS);
              break;
            case $o:
              r.depthFunc(r.LESS);
              break;
            case vs:
              r.depthFunc(r.LEQUAL);
              break;
            case Ko:
              r.depthFunc(r.EQUAL);
              break;
            case Jo:
              r.depthFunc(r.GEQUAL);
              break;
            case Qo:
              r.depthFunc(r.GREATER);
              break;
            case el:
              r.depthFunc(r.NOTEQUAL);
              break;
            default:
              r.depthFunc(r.LEQUAL);
          }
          Me = J;
        }
      },
      setLocked: function(J) {
        D = J;
      },
      setClear: function(J) {
        re !== J && (le && (J = 1 - J), r.clearDepth(J), re = J);
      },
      reset: function() {
        D = !1, fe = null, Me = null, re = null, le = !1;
      }
    };
  }
  function n() {
    let D = !1, le = null, fe = null, Me = null, re = null, J = null, Ce = null, Ge = null, vt = null;
    return {
      setTest: function(lt) {
        D || (lt ? te(r.STENCIL_TEST) : be(r.STENCIL_TEST));
      },
      setMask: function(lt) {
        le !== lt && !D && (r.stencilMask(lt), le = lt);
      },
      setFunc: function(lt, rn, Gi) {
        (fe !== lt || Me !== rn || re !== Gi) && (r.stencilFunc(lt, rn, Gi), fe = lt, Me = rn, re = Gi);
      },
      setOp: function(lt, rn, Gi) {
        (J !== lt || Ce !== rn || Ge !== Gi) && (r.stencilOp(lt, rn, Gi), J = lt, Ce = rn, Ge = Gi);
      },
      setLocked: function(lt) {
        D = lt;
      },
      setClear: function(lt) {
        vt !== lt && (r.clearStencil(lt), vt = lt);
      },
      reset: function() {
        D = !1, le = null, fe = null, Me = null, re = null, J = null, Ce = null, Ge = null, vt = null;
      }
    };
  }
  const s = new t(), a = new i(), o = new n(), l = /* @__PURE__ */ new WeakMap(), c = /* @__PURE__ */ new WeakMap();
  let h = {}, d = {}, u = /* @__PURE__ */ new WeakMap(), p = [], m = null, _ = !1, g = null, f = null, v = null, x = null, y = null, A = null, S = null, C = new oe(0, 0, 0), P = 0, E = !1, w = null, L = null, N = null, B = null, W = null;
  const Z = r.getParameter(r.MAX_COMBINED_TEXTURE_IMAGE_UNITS);
  let X = !1, ie = 0;
  const G = r.getParameter(r.VERSION);
  G.indexOf("WebGL") !== -1 ? (ie = parseFloat(/^WebGL (\d)/.exec(G)[1]), X = ie >= 1) : G.indexOf("OpenGL ES") !== -1 && (ie = parseFloat(/^OpenGL ES (\d)/.exec(G)[1]), X = ie >= 2);
  let he = null, me = {};
  const Se = r.getParameter(r.SCISSOR_BOX), We = r.getParameter(r.VIEWPORT), Qe = new Ye().fromArray(Se), ht = new Ye().fromArray(We);
  function nt(D, le, fe, Me) {
    const re = new Uint8Array(4), J = r.createTexture();
    r.bindTexture(D, J), r.texParameteri(D, r.TEXTURE_MIN_FILTER, r.NEAREST), r.texParameteri(D, r.TEXTURE_MAG_FILTER, r.NEAREST);
    for (let Ce = 0; Ce < fe; Ce++)
      D === r.TEXTURE_3D || D === r.TEXTURE_2D_ARRAY ? r.texImage3D(le, 0, r.RGBA, 1, 1, Me, 0, r.RGBA, r.UNSIGNED_BYTE, re) : r.texImage2D(le + Ce, 0, r.RGBA, 1, 1, 0, r.RGBA, r.UNSIGNED_BYTE, re);
    return J;
  }
  const Y = {};
  Y[r.TEXTURE_2D] = nt(r.TEXTURE_2D, r.TEXTURE_2D, 1), Y[r.TEXTURE_CUBE_MAP] = nt(r.TEXTURE_CUBE_MAP, r.TEXTURE_CUBE_MAP_POSITIVE_X, 6), Y[r.TEXTURE_2D_ARRAY] = nt(r.TEXTURE_2D_ARRAY, r.TEXTURE_2D_ARRAY, 1, 1), Y[r.TEXTURE_3D] = nt(r.TEXTURE_3D, r.TEXTURE_3D, 1, 1), s.setClear(0, 0, 0, 1), a.setClear(1), o.setClear(0), te(r.DEPTH_TEST), a.setFunc(vs), $(!1), j(Ph), te(r.CULL_FACE), ee(fn);
  function te(D) {
    h[D] !== !0 && (r.enable(D), h[D] = !0);
  }
  function be(D) {
    h[D] !== !1 && (r.disable(D), h[D] = !1);
  }
  function Le(D, le) {
    return d[D] !== le ? (r.bindFramebuffer(D, le), d[D] = le, D === r.DRAW_FRAMEBUFFER && (d[r.FRAMEBUFFER] = le), D === r.FRAMEBUFFER && (d[r.DRAW_FRAMEBUFFER] = le), !0) : !1;
  }
  function Ee(D, le) {
    let fe = p, Me = !1;
    if (D) {
      fe = u.get(le), fe === void 0 && (fe = [], u.set(le, fe));
      const re = D.textures;
      if (fe.length !== re.length || fe[0] !== r.COLOR_ATTACHMENT0) {
        for (let J = 0, Ce = re.length; J < Ce; J++)
          fe[J] = r.COLOR_ATTACHMENT0 + J;
        fe.length = re.length, Me = !0;
      }
    } else
      fe[0] !== r.BACK && (fe[0] = r.BACK, Me = !0);
    Me && r.drawBuffers(fe);
  }
  function $e(D) {
    return m !== D ? (r.useProgram(D), m = D, !0) : !1;
  }
  const yt = {
    [Ln]: r.FUNC_ADD,
    [Mf]: r.FUNC_SUBTRACT,
    [wf]: r.FUNC_REVERSE_SUBTRACT
  };
  yt[Ef] = r.MIN, yt[Tf] = r.MAX;
  const I = {
    [Af]: r.ZERO,
    [Cf]: r.ONE,
    [Rf]: r.SRC_COLOR,
    [qo]: r.SRC_ALPHA,
    [Uf]: r.SRC_ALPHA_SATURATE,
    [Df]: r.DST_COLOR,
    [Lf]: r.DST_ALPHA,
    [Pf]: r.ONE_MINUS_SRC_COLOR,
    [Zo]: r.ONE_MINUS_SRC_ALPHA,
    [Nf]: r.ONE_MINUS_DST_COLOR,
    [If]: r.ONE_MINUS_DST_ALPHA,
    [Of]: r.CONSTANT_COLOR,
    [Ff]: r.ONE_MINUS_CONSTANT_COLOR,
    [Bf]: r.CONSTANT_ALPHA,
    [kf]: r.ONE_MINUS_CONSTANT_ALPHA
  };
  function ee(D, le, fe, Me, re, J, Ce, Ge, vt, lt) {
    if (D === fn) {
      _ === !0 && (be(r.BLEND), _ = !1);
      return;
    }
    if (_ === !1 && (te(r.BLEND), _ = !0), D !== Sf) {
      if (D !== g || lt !== E) {
        if ((f !== Ln || y !== Ln) && (r.blendEquation(r.FUNC_ADD), f = Ln, y = Ln), lt)
          switch (D) {
            case Dn:
              r.blendFuncSeparate(r.ONE, r.ONE_MINUS_SRC_ALPHA, r.ONE, r.ONE_MINUS_SRC_ALPHA);
              break;
            case Lh:
              r.blendFunc(r.ONE, r.ONE);
              break;
            case Ih:
              r.blendFuncSeparate(r.ZERO, r.ONE_MINUS_SRC_COLOR, r.ZERO, r.ONE);
              break;
            case Dh:
              r.blendFuncSeparate(r.DST_COLOR, r.ONE_MINUS_SRC_ALPHA, r.ZERO, r.ONE);
              break;
            default:
              console.error("THREE.WebGLState: Invalid blending: ", D);
              break;
          }
        else
          switch (D) {
            case Dn:
              r.blendFuncSeparate(r.SRC_ALPHA, r.ONE_MINUS_SRC_ALPHA, r.ONE, r.ONE_MINUS_SRC_ALPHA);
              break;
            case Lh:
              r.blendFuncSeparate(r.SRC_ALPHA, r.ONE, r.ONE, r.ONE);
              break;
            case Ih:
              console.error("THREE.WebGLState: SubtractiveBlending requires material.premultipliedAlpha = true");
              break;
            case Dh:
              console.error("THREE.WebGLState: MultiplyBlending requires material.premultipliedAlpha = true");
              break;
            default:
              console.error("THREE.WebGLState: Invalid blending: ", D);
              break;
          }
        v = null, x = null, A = null, S = null, C.set(0, 0, 0), P = 0, g = D, E = lt;
      }
      return;
    }
    re = re || le, J = J || fe, Ce = Ce || Me, (le !== f || re !== y) && (r.blendEquationSeparate(yt[le], yt[re]), f = le, y = re), (fe !== v || Me !== x || J !== A || Ce !== S) && (r.blendFuncSeparate(I[fe], I[Me], I[J], I[Ce]), v = fe, x = Me, A = J, S = Ce), (Ge.equals(C) === !1 || vt !== P) && (r.blendColor(Ge.r, Ge.g, Ge.b, vt), C.copy(Ge), P = vt), g = D, E = !1;
  }
  function K(D, le) {
    D.side === ri ? be(r.CULL_FACE) : te(r.CULL_FACE);
    let fe = D.side === zt;
    le && (fe = !fe), $(fe), D.blending === Dn && D.transparent === !1 ? ee(fn) : ee(D.blending, D.blendEquation, D.blendSrc, D.blendDst, D.blendEquationAlpha, D.blendSrcAlpha, D.blendDstAlpha, D.blendColor, D.blendAlpha, D.premultipliedAlpha), a.setFunc(D.depthFunc), a.setTest(D.depthTest), a.setMask(D.depthWrite), s.setMask(D.colorWrite);
    const Me = D.stencilWrite;
    o.setTest(Me), Me && (o.setMask(D.stencilWriteMask), o.setFunc(D.stencilFunc, D.stencilRef, D.stencilFuncMask), o.setOp(D.stencilFail, D.stencilZFail, D.stencilZPass)), ne(D.polygonOffset, D.polygonOffsetFactor, D.polygonOffsetUnits), D.alphaToCoverage === !0 ? te(r.SAMPLE_ALPHA_TO_COVERAGE) : be(r.SAMPLE_ALPHA_TO_COVERAGE);
  }
  function $(D) {
    w !== D && (D ? r.frontFace(r.CW) : r.frontFace(r.CCW), w = D);
  }
  function j(D) {
    D !== vf ? (te(r.CULL_FACE), D !== L && (D === Ph ? r.cullFace(r.BACK) : D === xf ? r.cullFace(r.FRONT) : r.cullFace(r.FRONT_AND_BACK))) : be(r.CULL_FACE), L = D;
  }
  function de(D) {
    D !== N && (X && r.lineWidth(D), N = D);
  }
  function ne(D, le, fe) {
    D ? (te(r.POLYGON_OFFSET_FILL), (B !== le || W !== fe) && (r.polygonOffset(le, fe), B = le, W = fe)) : be(r.POLYGON_OFFSET_FILL);
  }
  function ue(D) {
    D ? te(r.SCISSOR_TEST) : be(r.SCISSOR_TEST);
  }
  function Ve(D) {
    D === void 0 && (D = r.TEXTURE0 + Z - 1), he !== D && (r.activeTexture(D), he = D);
  }
  function ze(D, le, fe) {
    fe === void 0 && (he === null ? fe = r.TEXTURE0 + Z - 1 : fe = he);
    let Me = me[fe];
    Me === void 0 && (Me = { type: void 0, texture: void 0 }, me[fe] = Me), (Me.type !== D || Me.texture !== le) && (he !== fe && (r.activeTexture(fe), he = fe), r.bindTexture(D, le || Y[D]), Me.type = D, Me.texture = le);
  }
  function R() {
    const D = me[he];
    D !== void 0 && D.type !== void 0 && (r.bindTexture(D.type, null), D.type = void 0, D.texture = void 0);
  }
  function M() {
    try {
      r.compressedTexImage2D(...arguments);
    } catch (D) {
      console.error("THREE.WebGLState:", D);
    }
  }
  function F() {
    try {
      r.compressedTexImage3D(...arguments);
    } catch (D) {
      console.error("THREE.WebGLState:", D);
    }
  }
  function V() {
    try {
      r.texSubImage2D(...arguments);
    } catch (D) {
      console.error("THREE.WebGLState:", D);
    }
  }
  function Q() {
    try {
      r.texSubImage3D(...arguments);
    } catch (D) {
      console.error("THREE.WebGLState:", D);
    }
  }
  function q() {
    try {
      r.compressedTexSubImage2D(...arguments);
    } catch (D) {
      console.error("THREE.WebGLState:", D);
    }
  }
  function Re() {
    try {
      r.compressedTexSubImage3D(...arguments);
    } catch (D) {
      console.error("THREE.WebGLState:", D);
    }
  }
  function ce() {
    try {
      r.texStorage2D(...arguments);
    } catch (D) {
      console.error("THREE.WebGLState:", D);
    }
  }
  function Te() {
    try {
      r.texStorage3D(...arguments);
    } catch (D) {
      console.error("THREE.WebGLState:", D);
    }
  }
  function Ae() {
    try {
      r.texImage2D(...arguments);
    } catch (D) {
      console.error("THREE.WebGLState:", D);
    }
  }
  function se() {
    try {
      r.texImage3D(...arguments);
    } catch (D) {
      console.error("THREE.WebGLState:", D);
    }
  }
  function ye(D) {
    Qe.equals(D) === !1 && (r.scissor(D.x, D.y, D.z, D.w), Qe.copy(D));
  }
  function Be(D) {
    ht.equals(D) === !1 && (r.viewport(D.x, D.y, D.z, D.w), ht.copy(D));
  }
  function Pe(D, le) {
    let fe = c.get(le);
    fe === void 0 && (fe = /* @__PURE__ */ new WeakMap(), c.set(le, fe));
    let Me = fe.get(D);
    Me === void 0 && (Me = r.getUniformBlockIndex(le, D.name), fe.set(D, Me));
  }
  function ge(D, le) {
    const Me = c.get(le).get(D);
    l.get(le) !== Me && (r.uniformBlockBinding(le, Me, D.__bindingPointIndex), l.set(le, Me));
  }
  function qe() {
    r.disable(r.BLEND), r.disable(r.CULL_FACE), r.disable(r.DEPTH_TEST), r.disable(r.POLYGON_OFFSET_FILL), r.disable(r.SCISSOR_TEST), r.disable(r.STENCIL_TEST), r.disable(r.SAMPLE_ALPHA_TO_COVERAGE), r.blendEquation(r.FUNC_ADD), r.blendFunc(r.ONE, r.ZERO), r.blendFuncSeparate(r.ONE, r.ZERO, r.ONE, r.ZERO), r.blendColor(0, 0, 0, 0), r.colorMask(!0, !0, !0, !0), r.clearColor(0, 0, 0, 0), r.depthMask(!0), r.depthFunc(r.LESS), a.setReversed(!1), r.clearDepth(1), r.stencilMask(4294967295), r.stencilFunc(r.ALWAYS, 0, 4294967295), r.stencilOp(r.KEEP, r.KEEP, r.KEEP), r.clearStencil(0), r.cullFace(r.BACK), r.frontFace(r.CCW), r.polygonOffset(0, 0), r.activeTexture(r.TEXTURE0), r.bindFramebuffer(r.FRAMEBUFFER, null), r.bindFramebuffer(r.DRAW_FRAMEBUFFER, null), r.bindFramebuffer(r.READ_FRAMEBUFFER, null), r.useProgram(null), r.lineWidth(1), r.scissor(0, 0, r.canvas.width, r.canvas.height), r.viewport(0, 0, r.canvas.width, r.canvas.height), h = {}, he = null, me = {}, d = {}, u = /* @__PURE__ */ new WeakMap(), p = [], m = null, _ = !1, g = null, f = null, v = null, x = null, y = null, A = null, S = null, C = new oe(0, 0, 0), P = 0, E = !1, w = null, L = null, N = null, B = null, W = null, Qe.set(0, 0, r.canvas.width, r.canvas.height), ht.set(0, 0, r.canvas.width, r.canvas.height), s.reset(), a.reset(), o.reset();
  }
  return {
    buffers: {
      color: s,
      depth: a,
      stencil: o
    },
    enable: te,
    disable: be,
    bindFramebuffer: Le,
    drawBuffers: Ee,
    useProgram: $e,
    setBlending: ee,
    setMaterial: K,
    setFlipSided: $,
    setCullFace: j,
    setLineWidth: de,
    setPolygonOffset: ne,
    setScissorTest: ue,
    activeTexture: Ve,
    bindTexture: ze,
    unbindTexture: R,
    compressedTexImage2D: M,
    compressedTexImage3D: F,
    texImage2D: Ae,
    texImage3D: se,
    updateUBOMapping: Pe,
    uniformBlockBinding: ge,
    texStorage2D: ce,
    texStorage3D: Te,
    texSubImage2D: V,
    texSubImage3D: Q,
    compressedTexSubImage2D: q,
    compressedTexSubImage3D: Re,
    scissor: ye,
    viewport: Be,
    reset: qe
  };
}
function UM(r, e, t, i, n, s, a) {
  const o = e.has("WEBGL_multisampled_render_to_texture") ? e.get("WEBGL_multisampled_render_to_texture") : null, l = typeof navigator > "u" ? !1 : /OculusBrowser/g.test(navigator.userAgent), c = new H(), h = /* @__PURE__ */ new WeakMap();
  let d;
  const u = /* @__PURE__ */ new WeakMap();
  let p = !1;
  try {
    p = typeof OffscreenCanvas < "u" && new OffscreenCanvas(1, 1).getContext("2d") !== null;
  } catch {
  }
  function m(R, M) {
    return p ? (
      // eslint-disable-next-line compat/compat
      new OffscreenCanvas(R, M)
    ) : ua("canvas");
  }
  function _(R, M, F) {
    let V = 1;
    const Q = ze(R);
    if ((Q.width > F || Q.height > F) && (V = F / Math.max(Q.width, Q.height)), V < 1)
      if (typeof HTMLImageElement < "u" && R instanceof HTMLImageElement || typeof HTMLCanvasElement < "u" && R instanceof HTMLCanvasElement || typeof ImageBitmap < "u" && R instanceof ImageBitmap || typeof VideoFrame < "u" && R instanceof VideoFrame) {
        const q = Math.floor(V * Q.width), Re = Math.floor(V * Q.height);
        d === void 0 && (d = m(q, Re));
        const ce = M ? m(q, Re) : d;
        return ce.width = q, ce.height = Re, ce.getContext("2d").drawImage(R, 0, 0, q, Re), console.warn("THREE.WebGLRenderer: Texture has been resized from (" + Q.width + "x" + Q.height + ") to (" + q + "x" + Re + ")."), ce;
      } else
        return "data" in R && console.warn("THREE.WebGLRenderer: Image in DataTexture is too big (" + Q.width + "x" + Q.height + ")."), R;
    return R;
  }
  function g(R) {
    return R.generateMipmaps;
  }
  function f(R) {
    r.generateMipmap(R);
  }
  function v(R) {
    return R.isWebGLCubeRenderTarget ? r.TEXTURE_CUBE_MAP : R.isWebGL3DRenderTarget ? r.TEXTURE_3D : R.isWebGLArrayRenderTarget || R.isCompressedArrayTexture ? r.TEXTURE_2D_ARRAY : r.TEXTURE_2D;
  }
  function x(R, M, F, V, Q = !1) {
    if (R !== null) {
      if (r[R] !== void 0) return r[R];
      console.warn("THREE.WebGLRenderer: Attempt to use non-existing WebGL internal format '" + R + "'");
    }
    let q = M;
    if (M === r.RED && (F === r.FLOAT && (q = r.R32F), F === r.HALF_FLOAT && (q = r.R16F), F === r.UNSIGNED_BYTE && (q = r.R8)), M === r.RED_INTEGER && (F === r.UNSIGNED_BYTE && (q = r.R8UI), F === r.UNSIGNED_SHORT && (q = r.R16UI), F === r.UNSIGNED_INT && (q = r.R32UI), F === r.BYTE && (q = r.R8I), F === r.SHORT && (q = r.R16I), F === r.INT && (q = r.R32I)), M === r.RG && (F === r.FLOAT && (q = r.RG32F), F === r.HALF_FLOAT && (q = r.RG16F), F === r.UNSIGNED_BYTE && (q = r.RG8)), M === r.RG_INTEGER && (F === r.UNSIGNED_BYTE && (q = r.RG8UI), F === r.UNSIGNED_SHORT && (q = r.RG16UI), F === r.UNSIGNED_INT && (q = r.RG32UI), F === r.BYTE && (q = r.RG8I), F === r.SHORT && (q = r.RG16I), F === r.INT && (q = r.RG32I)), M === r.RGB_INTEGER && (F === r.UNSIGNED_BYTE && (q = r.RGB8UI), F === r.UNSIGNED_SHORT && (q = r.RGB16UI), F === r.UNSIGNED_INT && (q = r.RGB32UI), F === r.BYTE && (q = r.RGB8I), F === r.SHORT && (q = r.RGB16I), F === r.INT && (q = r.RGB32I)), M === r.RGBA_INTEGER && (F === r.UNSIGNED_BYTE && (q = r.RGBA8UI), F === r.UNSIGNED_SHORT && (q = r.RGBA16UI), F === r.UNSIGNED_INT && (q = r.RGBA32UI), F === r.BYTE && (q = r.RGBA8I), F === r.SHORT && (q = r.RGBA16I), F === r.INT && (q = r.RGBA32I)), M === r.RGB && (F === r.UNSIGNED_INT_5_9_9_9_REV && (q = r.RGB9_E5), F === r.UNSIGNED_INT_10F_11F_11F_REV && (q = r.R11F_G11F_B10F)), M === r.RGBA) {
      const Re = Q ? la : et.getTransfer(V);
      F === r.FLOAT && (q = r.RGBA32F), F === r.HALF_FLOAT && (q = r.RGBA16F), F === r.UNSIGNED_BYTE && (q = Re === ut ? r.SRGB8_ALPHA8 : r.RGBA8), F === r.UNSIGNED_SHORT_4_4_4_4 && (q = r.RGBA4), F === r.UNSIGNED_SHORT_5_5_5_1 && (q = r.RGB5_A1);
    }
    return (q === r.R16F || q === r.R32F || q === r.RG16F || q === r.RG32F || q === r.RGBA16F || q === r.RGBA32F) && e.get("EXT_color_buffer_float"), q;
  }
  function y(R, M) {
    let F;
    return R ? M === null || M === yn || M === hr ? F = r.DEPTH24_STENCIL8 : M === mi ? F = r.DEPTH32F_STENCIL8 : M === cr && (F = r.DEPTH24_STENCIL8, console.warn("DepthTexture: 16 bit depth attachment is not supported with stencil. Using 24-bit attachment.")) : M === null || M === yn || M === hr ? F = r.DEPTH_COMPONENT24 : M === mi ? F = r.DEPTH_COMPONENT32F : M === cr && (F = r.DEPTH_COMPONENT16), F;
  }
  function A(R, M) {
    return g(R) === !0 || R.isFramebufferTexture && R.minFilter !== Xt && R.minFilter !== Pt ? Math.log2(Math.max(M.width, M.height)) + 1 : R.mipmaps !== void 0 && R.mipmaps.length > 0 ? R.mipmaps.length : R.isCompressedTexture && Array.isArray(R.image) ? M.mipmaps.length : 1;
  }
  function S(R) {
    const M = R.target;
    M.removeEventListener("dispose", S), P(M), M.isVideoTexture && h.delete(M);
  }
  function C(R) {
    const M = R.target;
    M.removeEventListener("dispose", C), w(M);
  }
  function P(R) {
    const M = i.get(R);
    if (M.__webglInit === void 0) return;
    const F = R.source, V = u.get(F);
    if (V) {
      const Q = V[M.__cacheKey];
      Q.usedTimes--, Q.usedTimes === 0 && E(R), Object.keys(V).length === 0 && u.delete(F);
    }
    i.remove(R);
  }
  function E(R) {
    const M = i.get(R);
    r.deleteTexture(M.__webglTexture);
    const F = R.source, V = u.get(F);
    delete V[M.__cacheKey], a.memory.textures--;
  }
  function w(R) {
    const M = i.get(R);
    if (R.depthTexture && (R.depthTexture.dispose(), i.remove(R.depthTexture)), R.isWebGLCubeRenderTarget)
      for (let V = 0; V < 6; V++) {
        if (Array.isArray(M.__webglFramebuffer[V]))
          for (let Q = 0; Q < M.__webglFramebuffer[V].length; Q++) r.deleteFramebuffer(M.__webglFramebuffer[V][Q]);
        else
          r.deleteFramebuffer(M.__webglFramebuffer[V]);
        M.__webglDepthbuffer && r.deleteRenderbuffer(M.__webglDepthbuffer[V]);
      }
    else {
      if (Array.isArray(M.__webglFramebuffer))
        for (let V = 0; V < M.__webglFramebuffer.length; V++) r.deleteFramebuffer(M.__webglFramebuffer[V]);
      else
        r.deleteFramebuffer(M.__webglFramebuffer);
      if (M.__webglDepthbuffer && r.deleteRenderbuffer(M.__webglDepthbuffer), M.__webglMultisampledFramebuffer && r.deleteFramebuffer(M.__webglMultisampledFramebuffer), M.__webglColorRenderbuffer)
        for (let V = 0; V < M.__webglColorRenderbuffer.length; V++)
          M.__webglColorRenderbuffer[V] && r.deleteRenderbuffer(M.__webglColorRenderbuffer[V]);
      M.__webglDepthRenderbuffer && r.deleteRenderbuffer(M.__webglDepthRenderbuffer);
    }
    const F = R.textures;
    for (let V = 0, Q = F.length; V < Q; V++) {
      const q = i.get(F[V]);
      q.__webglTexture && (r.deleteTexture(q.__webglTexture), a.memory.textures--), i.remove(F[V]);
    }
    i.remove(R);
  }
  let L = 0;
  function N() {
    L = 0;
  }
  function B() {
    const R = L;
    return R >= n.maxTextures && console.warn("THREE.WebGLTextures: Trying to use " + R + " texture units while this GPU supports only " + n.maxTextures), L += 1, R;
  }
  function W(R) {
    const M = [];
    return M.push(R.wrapS), M.push(R.wrapT), M.push(R.wrapR || 0), M.push(R.magFilter), M.push(R.minFilter), M.push(R.anisotropy), M.push(R.internalFormat), M.push(R.format), M.push(R.type), M.push(R.generateMipmaps), M.push(R.premultiplyAlpha), M.push(R.flipY), M.push(R.unpackAlignment), M.push(R.colorSpace), M.join();
  }
  function Z(R, M) {
    const F = i.get(R);
    if (R.isVideoTexture && ue(R), R.isRenderTargetTexture === !1 && R.isExternalTexture !== !0 && R.version > 0 && F.__version !== R.version) {
      const V = R.image;
      if (V === null)
        console.warn("THREE.WebGLRenderer: Texture marked for update but no image data found.");
      else if (V.complete === !1)
        console.warn("THREE.WebGLRenderer: Texture marked for update but image is incomplete");
      else {
        Y(F, R, M);
        return;
      }
    } else R.isExternalTexture && (F.__webglTexture = R.sourceTexture ? R.sourceTexture : null);
    t.bindTexture(r.TEXTURE_2D, F.__webglTexture, r.TEXTURE0 + M);
  }
  function X(R, M) {
    const F = i.get(R);
    if (R.isRenderTargetTexture === !1 && R.version > 0 && F.__version !== R.version) {
      Y(F, R, M);
      return;
    }
    t.bindTexture(r.TEXTURE_2D_ARRAY, F.__webglTexture, r.TEXTURE0 + M);
  }
  function ie(R, M) {
    const F = i.get(R);
    if (R.isRenderTargetTexture === !1 && R.version > 0 && F.__version !== R.version) {
      Y(F, R, M);
      return;
    }
    t.bindTexture(r.TEXTURE_3D, F.__webglTexture, r.TEXTURE0 + M);
  }
  function G(R, M) {
    const F = i.get(R);
    if (R.version > 0 && F.__version !== R.version) {
      te(F, R, M);
      return;
    }
    t.bindTexture(r.TEXTURE_CUBE_MAP, F.__webglTexture, r.TEXTURE0 + M);
  }
  const he = {
    [xs]: r.REPEAT,
    [fi]: r.CLAMP_TO_EDGE,
    [ra]: r.MIRRORED_REPEAT
  }, me = {
    [Xt]: r.NEAREST,
    [$h]: r.NEAREST_MIPMAP_NEAREST,
    [nr]: r.NEAREST_MIPMAP_LINEAR,
    [Pt]: r.LINEAR,
    [Zr]: r.LINEAR_MIPMAP_NEAREST,
    [Ji]: r.LINEAR_MIPMAP_LINEAR
  }, Se = {
    [tm]: r.NEVER,
    [om]: r.ALWAYS,
    [im]: r.LESS,
    [od]: r.LEQUAL,
    [nm]: r.EQUAL,
    [am]: r.GEQUAL,
    [sm]: r.GREATER,
    [rm]: r.NOTEQUAL
  };
  function We(R, M) {
    if (M.type === mi && e.has("OES_texture_float_linear") === !1 && (M.magFilter === Pt || M.magFilter === Zr || M.magFilter === nr || M.magFilter === Ji || M.minFilter === Pt || M.minFilter === Zr || M.minFilter === nr || M.minFilter === Ji) && console.warn("THREE.WebGLRenderer: Unable to use linear filtering with floating point textures. OES_texture_float_linear not supported on this device."), r.texParameteri(R, r.TEXTURE_WRAP_S, he[M.wrapS]), r.texParameteri(R, r.TEXTURE_WRAP_T, he[M.wrapT]), (R === r.TEXTURE_3D || R === r.TEXTURE_2D_ARRAY) && r.texParameteri(R, r.TEXTURE_WRAP_R, he[M.wrapR]), r.texParameteri(R, r.TEXTURE_MAG_FILTER, me[M.magFilter]), r.texParameteri(R, r.TEXTURE_MIN_FILTER, me[M.minFilter]), M.compareFunction && (r.texParameteri(R, r.TEXTURE_COMPARE_MODE, r.COMPARE_REF_TO_TEXTURE), r.texParameteri(R, r.TEXTURE_COMPARE_FUNC, Se[M.compareFunction])), e.has("EXT_texture_filter_anisotropic") === !0) {
      if (M.magFilter === Xt || M.minFilter !== nr && M.minFilter !== Ji || M.type === mi && e.has("OES_texture_float_linear") === !1) return;
      if (M.anisotropy > 1 || i.get(M).__currentAnisotropy) {
        const F = e.get("EXT_texture_filter_anisotropic");
        r.texParameterf(R, F.TEXTURE_MAX_ANISOTROPY_EXT, Math.min(M.anisotropy, n.getMaxAnisotropy())), i.get(M).__currentAnisotropy = M.anisotropy;
      }
    }
  }
  function Qe(R, M) {
    let F = !1;
    R.__webglInit === void 0 && (R.__webglInit = !0, M.addEventListener("dispose", S));
    const V = M.source;
    let Q = u.get(V);
    Q === void 0 && (Q = {}, u.set(V, Q));
    const q = W(M);
    if (q !== R.__cacheKey) {
      Q[q] === void 0 && (Q[q] = {
        texture: r.createTexture(),
        usedTimes: 0
      }, a.memory.textures++, F = !0), Q[q].usedTimes++;
      const Re = Q[R.__cacheKey];
      Re !== void 0 && (Q[R.__cacheKey].usedTimes--, Re.usedTimes === 0 && E(M)), R.__cacheKey = q, R.__webglTexture = Q[q].texture;
    }
    return F;
  }
  function ht(R, M, F) {
    return Math.floor(Math.floor(R / F) / M);
  }
  function nt(R, M, F, V) {
    const q = R.updateRanges;
    if (q.length === 0)
      t.texSubImage2D(r.TEXTURE_2D, 0, 0, 0, M.width, M.height, F, V, M.data);
    else {
      q.sort((se, ye) => se.start - ye.start);
      let Re = 0;
      for (let se = 1; se < q.length; se++) {
        const ye = q[Re], Be = q[se], Pe = ye.start + ye.count, ge = ht(Be.start, M.width, 4), qe = ht(ye.start, M.width, 4);
        Be.start <= Pe + 1 && ge === qe && ht(Be.start + Be.count - 1, M.width, 4) === ge ? ye.count = Math.max(
          ye.count,
          Be.start + Be.count - ye.start
        ) : (++Re, q[Re] = Be);
      }
      q.length = Re + 1;
      const ce = r.getParameter(r.UNPACK_ROW_LENGTH), Te = r.getParameter(r.UNPACK_SKIP_PIXELS), Ae = r.getParameter(r.UNPACK_SKIP_ROWS);
      r.pixelStorei(r.UNPACK_ROW_LENGTH, M.width);
      for (let se = 0, ye = q.length; se < ye; se++) {
        const Be = q[se], Pe = Math.floor(Be.start / 4), ge = Math.ceil(Be.count / 4), qe = Pe % M.width, D = Math.floor(Pe / M.width), le = ge, fe = 1;
        r.pixelStorei(r.UNPACK_SKIP_PIXELS, qe), r.pixelStorei(r.UNPACK_SKIP_ROWS, D), t.texSubImage2D(r.TEXTURE_2D, 0, qe, D, le, fe, F, V, M.data);
      }
      R.clearUpdateRanges(), r.pixelStorei(r.UNPACK_ROW_LENGTH, ce), r.pixelStorei(r.UNPACK_SKIP_PIXELS, Te), r.pixelStorei(r.UNPACK_SKIP_ROWS, Ae);
    }
  }
  function Y(R, M, F) {
    let V = r.TEXTURE_2D;
    (M.isDataArrayTexture || M.isCompressedArrayTexture) && (V = r.TEXTURE_2D_ARRAY), M.isData3DTexture && (V = r.TEXTURE_3D);
    const Q = Qe(R, M), q = M.source;
    t.bindTexture(V, R.__webglTexture, r.TEXTURE0 + F);
    const Re = i.get(q);
    if (q.version !== Re.__version || Q === !0) {
      t.activeTexture(r.TEXTURE0 + F);
      const ce = et.getPrimaries(et.workingColorSpace), Te = M.colorSpace === un ? null : et.getPrimaries(M.colorSpace), Ae = M.colorSpace === un || ce === Te ? r.NONE : r.BROWSER_DEFAULT_WEBGL;
      r.pixelStorei(r.UNPACK_FLIP_Y_WEBGL, M.flipY), r.pixelStorei(r.UNPACK_PREMULTIPLY_ALPHA_WEBGL, M.premultiplyAlpha), r.pixelStorei(r.UNPACK_ALIGNMENT, M.unpackAlignment), r.pixelStorei(r.UNPACK_COLORSPACE_CONVERSION_WEBGL, Ae);
      let se = _(M.image, !1, n.maxTextureSize);
      se = Ve(M, se);
      const ye = s.convert(M.format, M.colorSpace), Be = s.convert(M.type);
      let Pe = x(M.internalFormat, ye, Be, M.colorSpace, M.isVideoTexture);
      We(V, M);
      let ge;
      const qe = M.mipmaps, D = M.isVideoTexture !== !0, le = Re.__version === void 0 || Q === !0, fe = q.dataReady, Me = A(M, se);
      if (M.isDepthTexture)
        Pe = y(M.format === ur, M.type), le && (D ? t.texStorage2D(r.TEXTURE_2D, 1, Pe, se.width, se.height) : t.texImage2D(r.TEXTURE_2D, 0, Pe, se.width, se.height, 0, ye, Be, null));
      else if (M.isDataTexture)
        if (qe.length > 0) {
          D && le && t.texStorage2D(r.TEXTURE_2D, Me, Pe, qe[0].width, qe[0].height);
          for (let re = 0, J = qe.length; re < J; re++)
            ge = qe[re], D ? fe && t.texSubImage2D(r.TEXTURE_2D, re, 0, 0, ge.width, ge.height, ye, Be, ge.data) : t.texImage2D(r.TEXTURE_2D, re, Pe, ge.width, ge.height, 0, ye, Be, ge.data);
          M.generateMipmaps = !1;
        } else
          D ? (le && t.texStorage2D(r.TEXTURE_2D, Me, Pe, se.width, se.height), fe && nt(M, se, ye, Be)) : t.texImage2D(r.TEXTURE_2D, 0, Pe, se.width, se.height, 0, ye, Be, se.data);
      else if (M.isCompressedTexture)
        if (M.isCompressedArrayTexture) {
          D && le && t.texStorage3D(r.TEXTURE_2D_ARRAY, Me, Pe, qe[0].width, qe[0].height, se.depth);
          for (let re = 0, J = qe.length; re < J; re++)
            if (ge = qe[re], M.format !== oi)
              if (ye !== null)
                if (D) {
                  if (fe)
                    if (M.layerUpdates.size > 0) {
                      const Ce = Gh(ge.width, ge.height, M.format, M.type);
                      for (const Ge of M.layerUpdates) {
                        const vt = ge.data.subarray(
                          Ge * Ce / ge.data.BYTES_PER_ELEMENT,
                          (Ge + 1) * Ce / ge.data.BYTES_PER_ELEMENT
                        );
                        t.compressedTexSubImage3D(r.TEXTURE_2D_ARRAY, re, 0, 0, Ge, ge.width, ge.height, 1, ye, vt);
                      }
                      M.clearLayerUpdates();
                    } else
                      t.compressedTexSubImage3D(r.TEXTURE_2D_ARRAY, re, 0, 0, 0, ge.width, ge.height, se.depth, ye, ge.data);
                } else
                  t.compressedTexImage3D(r.TEXTURE_2D_ARRAY, re, Pe, ge.width, ge.height, se.depth, 0, ge.data, 0, 0);
              else
                console.warn("THREE.WebGLRenderer: Attempt to load unsupported compressed texture format in .uploadTexture()");
            else
              D ? fe && t.texSubImage3D(r.TEXTURE_2D_ARRAY, re, 0, 0, 0, ge.width, ge.height, se.depth, ye, Be, ge.data) : t.texImage3D(r.TEXTURE_2D_ARRAY, re, Pe, ge.width, ge.height, se.depth, 0, ye, Be, ge.data);
        } else {
          D && le && t.texStorage2D(r.TEXTURE_2D, Me, Pe, qe[0].width, qe[0].height);
          for (let re = 0, J = qe.length; re < J; re++)
            ge = qe[re], M.format !== oi ? ye !== null ? D ? fe && t.compressedTexSubImage2D(r.TEXTURE_2D, re, 0, 0, ge.width, ge.height, ye, ge.data) : t.compressedTexImage2D(r.TEXTURE_2D, re, Pe, ge.width, ge.height, 0, ge.data) : console.warn("THREE.WebGLRenderer: Attempt to load unsupported compressed texture format in .uploadTexture()") : D ? fe && t.texSubImage2D(r.TEXTURE_2D, re, 0, 0, ge.width, ge.height, ye, Be, ge.data) : t.texImage2D(r.TEXTURE_2D, re, Pe, ge.width, ge.height, 0, ye, Be, ge.data);
        }
      else if (M.isDataArrayTexture)
        if (D) {
          if (le && t.texStorage3D(r.TEXTURE_2D_ARRAY, Me, Pe, se.width, se.height, se.depth), fe)
            if (M.layerUpdates.size > 0) {
              const re = Gh(se.width, se.height, M.format, M.type);
              for (const J of M.layerUpdates) {
                const Ce = se.data.subarray(
                  J * re / se.data.BYTES_PER_ELEMENT,
                  (J + 1) * re / se.data.BYTES_PER_ELEMENT
                );
                t.texSubImage3D(r.TEXTURE_2D_ARRAY, 0, 0, 0, J, se.width, se.height, 1, ye, Be, Ce);
              }
              M.clearLayerUpdates();
            } else
              t.texSubImage3D(r.TEXTURE_2D_ARRAY, 0, 0, 0, 0, se.width, se.height, se.depth, ye, Be, se.data);
        } else
          t.texImage3D(r.TEXTURE_2D_ARRAY, 0, Pe, se.width, se.height, se.depth, 0, ye, Be, se.data);
      else if (M.isData3DTexture)
        D ? (le && t.texStorage3D(r.TEXTURE_3D, Me, Pe, se.width, se.height, se.depth), fe && t.texSubImage3D(r.TEXTURE_3D, 0, 0, 0, 0, se.width, se.height, se.depth, ye, Be, se.data)) : t.texImage3D(r.TEXTURE_3D, 0, Pe, se.width, se.height, se.depth, 0, ye, Be, se.data);
      else if (M.isFramebufferTexture) {
        if (le)
          if (D)
            t.texStorage2D(r.TEXTURE_2D, Me, Pe, se.width, se.height);
          else {
            let re = se.width, J = se.height;
            for (let Ce = 0; Ce < Me; Ce++)
              t.texImage2D(r.TEXTURE_2D, Ce, Pe, re, J, 0, ye, Be, null), re >>= 1, J >>= 1;
          }
      } else if (qe.length > 0) {
        if (D && le) {
          const re = ze(qe[0]);
          t.texStorage2D(r.TEXTURE_2D, Me, Pe, re.width, re.height);
        }
        for (let re = 0, J = qe.length; re < J; re++)
          ge = qe[re], D ? fe && t.texSubImage2D(r.TEXTURE_2D, re, 0, 0, ye, Be, ge) : t.texImage2D(r.TEXTURE_2D, re, Pe, ye, Be, ge);
        M.generateMipmaps = !1;
      } else if (D) {
        if (le) {
          const re = ze(se);
          t.texStorage2D(r.TEXTURE_2D, Me, Pe, re.width, re.height);
        }
        fe && t.texSubImage2D(r.TEXTURE_2D, 0, 0, 0, ye, Be, se);
      } else
        t.texImage2D(r.TEXTURE_2D, 0, Pe, ye, Be, se);
      g(M) && f(V), Re.__version = q.version, M.onUpdate && M.onUpdate(M);
    }
    R.__version = M.version;
  }
  function te(R, M, F) {
    if (M.image.length !== 6) return;
    const V = Qe(R, M), Q = M.source;
    t.bindTexture(r.TEXTURE_CUBE_MAP, R.__webglTexture, r.TEXTURE0 + F);
    const q = i.get(Q);
    if (Q.version !== q.__version || V === !0) {
      t.activeTexture(r.TEXTURE0 + F);
      const Re = et.getPrimaries(et.workingColorSpace), ce = M.colorSpace === un ? null : et.getPrimaries(M.colorSpace), Te = M.colorSpace === un || Re === ce ? r.NONE : r.BROWSER_DEFAULT_WEBGL;
      r.pixelStorei(r.UNPACK_FLIP_Y_WEBGL, M.flipY), r.pixelStorei(r.UNPACK_PREMULTIPLY_ALPHA_WEBGL, M.premultiplyAlpha), r.pixelStorei(r.UNPACK_ALIGNMENT, M.unpackAlignment), r.pixelStorei(r.UNPACK_COLORSPACE_CONVERSION_WEBGL, Te);
      const Ae = M.isCompressedTexture || M.image[0].isCompressedTexture, se = M.image[0] && M.image[0].isDataTexture, ye = [];
      for (let J = 0; J < 6; J++)
        !Ae && !se ? ye[J] = _(M.image[J], !0, n.maxCubemapSize) : ye[J] = se ? M.image[J].image : M.image[J], ye[J] = Ve(M, ye[J]);
      const Be = ye[0], Pe = s.convert(M.format, M.colorSpace), ge = s.convert(M.type), qe = x(M.internalFormat, Pe, ge, M.colorSpace), D = M.isVideoTexture !== !0, le = q.__version === void 0 || V === !0, fe = Q.dataReady;
      let Me = A(M, Be);
      We(r.TEXTURE_CUBE_MAP, M);
      let re;
      if (Ae) {
        D && le && t.texStorage2D(r.TEXTURE_CUBE_MAP, Me, qe, Be.width, Be.height);
        for (let J = 0; J < 6; J++) {
          re = ye[J].mipmaps;
          for (let Ce = 0; Ce < re.length; Ce++) {
            const Ge = re[Ce];
            M.format !== oi ? Pe !== null ? D ? fe && t.compressedTexSubImage2D(r.TEXTURE_CUBE_MAP_POSITIVE_X + J, Ce, 0, 0, Ge.width, Ge.height, Pe, Ge.data) : t.compressedTexImage2D(r.TEXTURE_CUBE_MAP_POSITIVE_X + J, Ce, qe, Ge.width, Ge.height, 0, Ge.data) : console.warn("THREE.WebGLRenderer: Attempt to load unsupported compressed texture format in .setTextureCube()") : D ? fe && t.texSubImage2D(r.TEXTURE_CUBE_MAP_POSITIVE_X + J, Ce, 0, 0, Ge.width, Ge.height, Pe, ge, Ge.data) : t.texImage2D(r.TEXTURE_CUBE_MAP_POSITIVE_X + J, Ce, qe, Ge.width, Ge.height, 0, Pe, ge, Ge.data);
          }
        }
      } else {
        if (re = M.mipmaps, D && le) {
          re.length > 0 && Me++;
          const J = ze(ye[0]);
          t.texStorage2D(r.TEXTURE_CUBE_MAP, Me, qe, J.width, J.height);
        }
        for (let J = 0; J < 6; J++)
          if (se) {
            D ? fe && t.texSubImage2D(r.TEXTURE_CUBE_MAP_POSITIVE_X + J, 0, 0, 0, ye[J].width, ye[J].height, Pe, ge, ye[J].data) : t.texImage2D(r.TEXTURE_CUBE_MAP_POSITIVE_X + J, 0, qe, ye[J].width, ye[J].height, 0, Pe, ge, ye[J].data);
            for (let Ce = 0; Ce < re.length; Ce++) {
              const vt = re[Ce].image[J].image;
              D ? fe && t.texSubImage2D(r.TEXTURE_CUBE_MAP_POSITIVE_X + J, Ce + 1, 0, 0, vt.width, vt.height, Pe, ge, vt.data) : t.texImage2D(r.TEXTURE_CUBE_MAP_POSITIVE_X + J, Ce + 1, qe, vt.width, vt.height, 0, Pe, ge, vt.data);
            }
          } else {
            D ? fe && t.texSubImage2D(r.TEXTURE_CUBE_MAP_POSITIVE_X + J, 0, 0, 0, Pe, ge, ye[J]) : t.texImage2D(r.TEXTURE_CUBE_MAP_POSITIVE_X + J, 0, qe, Pe, ge, ye[J]);
            for (let Ce = 0; Ce < re.length; Ce++) {
              const Ge = re[Ce];
              D ? fe && t.texSubImage2D(r.TEXTURE_CUBE_MAP_POSITIVE_X + J, Ce + 1, 0, 0, Pe, ge, Ge.image[J]) : t.texImage2D(r.TEXTURE_CUBE_MAP_POSITIVE_X + J, Ce + 1, qe, Pe, ge, Ge.image[J]);
            }
          }
      }
      g(M) && f(r.TEXTURE_CUBE_MAP), q.__version = Q.version, M.onUpdate && M.onUpdate(M);
    }
    R.__version = M.version;
  }
  function be(R, M, F, V, Q, q) {
    const Re = s.convert(F.format, F.colorSpace), ce = s.convert(F.type), Te = x(F.internalFormat, Re, ce, F.colorSpace), Ae = i.get(M), se = i.get(F);
    if (se.__renderTarget = M, !Ae.__hasExternalTextures) {
      const ye = Math.max(1, M.width >> q), Be = Math.max(1, M.height >> q);
      Q === r.TEXTURE_3D || Q === r.TEXTURE_2D_ARRAY ? t.texImage3D(Q, q, Te, ye, Be, M.depth, 0, Re, ce, null) : t.texImage2D(Q, q, Te, ye, Be, 0, Re, ce, null);
    }
    t.bindFramebuffer(r.FRAMEBUFFER, R), ne(M) ? o.framebufferTexture2DMultisampleEXT(r.FRAMEBUFFER, V, Q, se.__webglTexture, 0, de(M)) : (Q === r.TEXTURE_2D || Q >= r.TEXTURE_CUBE_MAP_POSITIVE_X && Q <= r.TEXTURE_CUBE_MAP_NEGATIVE_Z) && r.framebufferTexture2D(r.FRAMEBUFFER, V, Q, se.__webglTexture, q), t.bindFramebuffer(r.FRAMEBUFFER, null);
  }
  function Le(R, M, F) {
    if (r.bindRenderbuffer(r.RENDERBUFFER, R), M.depthBuffer) {
      const V = M.depthTexture, Q = V && V.isDepthTexture ? V.type : null, q = y(M.stencilBuffer, Q), Re = M.stencilBuffer ? r.DEPTH_STENCIL_ATTACHMENT : r.DEPTH_ATTACHMENT, ce = de(M);
      ne(M) ? o.renderbufferStorageMultisampleEXT(r.RENDERBUFFER, ce, q, M.width, M.height) : F ? r.renderbufferStorageMultisample(r.RENDERBUFFER, ce, q, M.width, M.height) : r.renderbufferStorage(r.RENDERBUFFER, q, M.width, M.height), r.framebufferRenderbuffer(r.FRAMEBUFFER, Re, r.RENDERBUFFER, R);
    } else {
      const V = M.textures;
      for (let Q = 0; Q < V.length; Q++) {
        const q = V[Q], Re = s.convert(q.format, q.colorSpace), ce = s.convert(q.type), Te = x(q.internalFormat, Re, ce, q.colorSpace), Ae = de(M);
        F && ne(M) === !1 ? r.renderbufferStorageMultisample(r.RENDERBUFFER, Ae, Te, M.width, M.height) : ne(M) ? o.renderbufferStorageMultisampleEXT(r.RENDERBUFFER, Ae, Te, M.width, M.height) : r.renderbufferStorage(r.RENDERBUFFER, Te, M.width, M.height);
      }
    }
    r.bindRenderbuffer(r.RENDERBUFFER, null);
  }
  function Ee(R, M) {
    if (M && M.isWebGLCubeRenderTarget) throw new Error("Depth Texture with cube render targets is not supported");
    if (t.bindFramebuffer(r.FRAMEBUFFER, R), !(M.depthTexture && M.depthTexture.isDepthTexture))
      throw new Error("renderTarget.depthTexture must be an instance of THREE.DepthTexture");
    const V = i.get(M.depthTexture);
    V.__renderTarget = M, (!V.__webglTexture || M.depthTexture.image.width !== M.width || M.depthTexture.image.height !== M.height) && (M.depthTexture.image.width = M.width, M.depthTexture.image.height = M.height, M.depthTexture.needsUpdate = !0), Z(M.depthTexture, 0);
    const Q = V.__webglTexture, q = de(M);
    if (M.depthTexture.format === dr)
      ne(M) ? o.framebufferTexture2DMultisampleEXT(r.FRAMEBUFFER, r.DEPTH_ATTACHMENT, r.TEXTURE_2D, Q, 0, q) : r.framebufferTexture2D(r.FRAMEBUFFER, r.DEPTH_ATTACHMENT, r.TEXTURE_2D, Q, 0);
    else if (M.depthTexture.format === ur)
      ne(M) ? o.framebufferTexture2DMultisampleEXT(r.FRAMEBUFFER, r.DEPTH_STENCIL_ATTACHMENT, r.TEXTURE_2D, Q, 0, q) : r.framebufferTexture2D(r.FRAMEBUFFER, r.DEPTH_STENCIL_ATTACHMENT, r.TEXTURE_2D, Q, 0);
    else
      throw new Error("Unknown depthTexture format");
  }
  function $e(R) {
    const M = i.get(R), F = R.isWebGLCubeRenderTarget === !0;
    if (M.__boundDepthTexture !== R.depthTexture) {
      const V = R.depthTexture;
      if (M.__depthDisposeCallback && M.__depthDisposeCallback(), V) {
        const Q = () => {
          delete M.__boundDepthTexture, delete M.__depthDisposeCallback, V.removeEventListener("dispose", Q);
        };
        V.addEventListener("dispose", Q), M.__depthDisposeCallback = Q;
      }
      M.__boundDepthTexture = V;
    }
    if (R.depthTexture && !M.__autoAllocateDepthBuffer) {
      if (F) throw new Error("target.depthTexture not supported in Cube render targets");
      const V = R.texture.mipmaps;
      V && V.length > 0 ? Ee(M.__webglFramebuffer[0], R) : Ee(M.__webglFramebuffer, R);
    } else if (F) {
      M.__webglDepthbuffer = [];
      for (let V = 0; V < 6; V++)
        if (t.bindFramebuffer(r.FRAMEBUFFER, M.__webglFramebuffer[V]), M.__webglDepthbuffer[V] === void 0)
          M.__webglDepthbuffer[V] = r.createRenderbuffer(), Le(M.__webglDepthbuffer[V], R, !1);
        else {
          const Q = R.stencilBuffer ? r.DEPTH_STENCIL_ATTACHMENT : r.DEPTH_ATTACHMENT, q = M.__webglDepthbuffer[V];
          r.bindRenderbuffer(r.RENDERBUFFER, q), r.framebufferRenderbuffer(r.FRAMEBUFFER, Q, r.RENDERBUFFER, q);
        }
    } else {
      const V = R.texture.mipmaps;
      if (V && V.length > 0 ? t.bindFramebuffer(r.FRAMEBUFFER, M.__webglFramebuffer[0]) : t.bindFramebuffer(r.FRAMEBUFFER, M.__webglFramebuffer), M.__webglDepthbuffer === void 0)
        M.__webglDepthbuffer = r.createRenderbuffer(), Le(M.__webglDepthbuffer, R, !1);
      else {
        const Q = R.stencilBuffer ? r.DEPTH_STENCIL_ATTACHMENT : r.DEPTH_ATTACHMENT, q = M.__webglDepthbuffer;
        r.bindRenderbuffer(r.RENDERBUFFER, q), r.framebufferRenderbuffer(r.FRAMEBUFFER, Q, r.RENDERBUFFER, q);
      }
    }
    t.bindFramebuffer(r.FRAMEBUFFER, null);
  }
  function yt(R, M, F) {
    const V = i.get(R);
    M !== void 0 && be(V.__webglFramebuffer, R, R.texture, r.COLOR_ATTACHMENT0, r.TEXTURE_2D, 0), F !== void 0 && $e(R);
  }
  function I(R) {
    const M = R.texture, F = i.get(R), V = i.get(M);
    R.addEventListener("dispose", C);
    const Q = R.textures, q = R.isWebGLCubeRenderTarget === !0, Re = Q.length > 1;
    if (Re || (V.__webglTexture === void 0 && (V.__webglTexture = r.createTexture()), V.__version = M.version, a.memory.textures++), q) {
      F.__webglFramebuffer = [];
      for (let ce = 0; ce < 6; ce++)
        if (M.mipmaps && M.mipmaps.length > 0) {
          F.__webglFramebuffer[ce] = [];
          for (let Te = 0; Te < M.mipmaps.length; Te++)
            F.__webglFramebuffer[ce][Te] = r.createFramebuffer();
        } else
          F.__webglFramebuffer[ce] = r.createFramebuffer();
    } else {
      if (M.mipmaps && M.mipmaps.length > 0) {
        F.__webglFramebuffer = [];
        for (let ce = 0; ce < M.mipmaps.length; ce++)
          F.__webglFramebuffer[ce] = r.createFramebuffer();
      } else
        F.__webglFramebuffer = r.createFramebuffer();
      if (Re)
        for (let ce = 0, Te = Q.length; ce < Te; ce++) {
          const Ae = i.get(Q[ce]);
          Ae.__webglTexture === void 0 && (Ae.__webglTexture = r.createTexture(), a.memory.textures++);
        }
      if (R.samples > 0 && ne(R) === !1) {
        F.__webglMultisampledFramebuffer = r.createFramebuffer(), F.__webglColorRenderbuffer = [], t.bindFramebuffer(r.FRAMEBUFFER, F.__webglMultisampledFramebuffer);
        for (let ce = 0; ce < Q.length; ce++) {
          const Te = Q[ce];
          F.__webglColorRenderbuffer[ce] = r.createRenderbuffer(), r.bindRenderbuffer(r.RENDERBUFFER, F.__webglColorRenderbuffer[ce]);
          const Ae = s.convert(Te.format, Te.colorSpace), se = s.convert(Te.type), ye = x(Te.internalFormat, Ae, se, Te.colorSpace, R.isXRRenderTarget === !0), Be = de(R);
          r.renderbufferStorageMultisample(r.RENDERBUFFER, Be, ye, R.width, R.height), r.framebufferRenderbuffer(r.FRAMEBUFFER, r.COLOR_ATTACHMENT0 + ce, r.RENDERBUFFER, F.__webglColorRenderbuffer[ce]);
        }
        r.bindRenderbuffer(r.RENDERBUFFER, null), R.depthBuffer && (F.__webglDepthRenderbuffer = r.createRenderbuffer(), Le(F.__webglDepthRenderbuffer, R, !0)), t.bindFramebuffer(r.FRAMEBUFFER, null);
      }
    }
    if (q) {
      t.bindTexture(r.TEXTURE_CUBE_MAP, V.__webglTexture), We(r.TEXTURE_CUBE_MAP, M);
      for (let ce = 0; ce < 6; ce++)
        if (M.mipmaps && M.mipmaps.length > 0)
          for (let Te = 0; Te < M.mipmaps.length; Te++)
            be(F.__webglFramebuffer[ce][Te], R, M, r.COLOR_ATTACHMENT0, r.TEXTURE_CUBE_MAP_POSITIVE_X + ce, Te);
        else
          be(F.__webglFramebuffer[ce], R, M, r.COLOR_ATTACHMENT0, r.TEXTURE_CUBE_MAP_POSITIVE_X + ce, 0);
      g(M) && f(r.TEXTURE_CUBE_MAP), t.unbindTexture();
    } else if (Re) {
      for (let ce = 0, Te = Q.length; ce < Te; ce++) {
        const Ae = Q[ce], se = i.get(Ae);
        let ye = r.TEXTURE_2D;
        (R.isWebGL3DRenderTarget || R.isWebGLArrayRenderTarget) && (ye = R.isWebGL3DRenderTarget ? r.TEXTURE_3D : r.TEXTURE_2D_ARRAY), t.bindTexture(ye, se.__webglTexture), We(ye, Ae), be(F.__webglFramebuffer, R, Ae, r.COLOR_ATTACHMENT0 + ce, ye, 0), g(Ae) && f(ye);
      }
      t.unbindTexture();
    } else {
      let ce = r.TEXTURE_2D;
      if ((R.isWebGL3DRenderTarget || R.isWebGLArrayRenderTarget) && (ce = R.isWebGL3DRenderTarget ? r.TEXTURE_3D : r.TEXTURE_2D_ARRAY), t.bindTexture(ce, V.__webglTexture), We(ce, M), M.mipmaps && M.mipmaps.length > 0)
        for (let Te = 0; Te < M.mipmaps.length; Te++)
          be(F.__webglFramebuffer[Te], R, M, r.COLOR_ATTACHMENT0, ce, Te);
      else
        be(F.__webglFramebuffer, R, M, r.COLOR_ATTACHMENT0, ce, 0);
      g(M) && f(ce), t.unbindTexture();
    }
    R.depthBuffer && $e(R);
  }
  function ee(R) {
    const M = R.textures;
    for (let F = 0, V = M.length; F < V; F++) {
      const Q = M[F];
      if (g(Q)) {
        const q = v(R), Re = i.get(Q).__webglTexture;
        t.bindTexture(q, Re), f(q), t.unbindTexture();
      }
    }
  }
  const K = [], $ = [];
  function j(R) {
    if (R.samples > 0) {
      if (ne(R) === !1) {
        const M = R.textures, F = R.width, V = R.height;
        let Q = r.COLOR_BUFFER_BIT;
        const q = R.stencilBuffer ? r.DEPTH_STENCIL_ATTACHMENT : r.DEPTH_ATTACHMENT, Re = i.get(R), ce = M.length > 1;
        if (ce)
          for (let Ae = 0; Ae < M.length; Ae++)
            t.bindFramebuffer(r.FRAMEBUFFER, Re.__webglMultisampledFramebuffer), r.framebufferRenderbuffer(r.FRAMEBUFFER, r.COLOR_ATTACHMENT0 + Ae, r.RENDERBUFFER, null), t.bindFramebuffer(r.FRAMEBUFFER, Re.__webglFramebuffer), r.framebufferTexture2D(r.DRAW_FRAMEBUFFER, r.COLOR_ATTACHMENT0 + Ae, r.TEXTURE_2D, null, 0);
        t.bindFramebuffer(r.READ_FRAMEBUFFER, Re.__webglMultisampledFramebuffer);
        const Te = R.texture.mipmaps;
        Te && Te.length > 0 ? t.bindFramebuffer(r.DRAW_FRAMEBUFFER, Re.__webglFramebuffer[0]) : t.bindFramebuffer(r.DRAW_FRAMEBUFFER, Re.__webglFramebuffer);
        for (let Ae = 0; Ae < M.length; Ae++) {
          if (R.resolveDepthBuffer && (R.depthBuffer && (Q |= r.DEPTH_BUFFER_BIT), R.stencilBuffer && R.resolveStencilBuffer && (Q |= r.STENCIL_BUFFER_BIT)), ce) {
            r.framebufferRenderbuffer(r.READ_FRAMEBUFFER, r.COLOR_ATTACHMENT0, r.RENDERBUFFER, Re.__webglColorRenderbuffer[Ae]);
            const se = i.get(M[Ae]).__webglTexture;
            r.framebufferTexture2D(r.DRAW_FRAMEBUFFER, r.COLOR_ATTACHMENT0, r.TEXTURE_2D, se, 0);
          }
          r.blitFramebuffer(0, 0, F, V, 0, 0, F, V, Q, r.NEAREST), l === !0 && (K.length = 0, $.length = 0, K.push(r.COLOR_ATTACHMENT0 + Ae), R.depthBuffer && R.resolveDepthBuffer === !1 && (K.push(q), $.push(q), r.invalidateFramebuffer(r.DRAW_FRAMEBUFFER, $)), r.invalidateFramebuffer(r.READ_FRAMEBUFFER, K));
        }
        if (t.bindFramebuffer(r.READ_FRAMEBUFFER, null), t.bindFramebuffer(r.DRAW_FRAMEBUFFER, null), ce)
          for (let Ae = 0; Ae < M.length; Ae++) {
            t.bindFramebuffer(r.FRAMEBUFFER, Re.__webglMultisampledFramebuffer), r.framebufferRenderbuffer(r.FRAMEBUFFER, r.COLOR_ATTACHMENT0 + Ae, r.RENDERBUFFER, Re.__webglColorRenderbuffer[Ae]);
            const se = i.get(M[Ae]).__webglTexture;
            t.bindFramebuffer(r.FRAMEBUFFER, Re.__webglFramebuffer), r.framebufferTexture2D(r.DRAW_FRAMEBUFFER, r.COLOR_ATTACHMENT0 + Ae, r.TEXTURE_2D, se, 0);
          }
        t.bindFramebuffer(r.DRAW_FRAMEBUFFER, Re.__webglMultisampledFramebuffer);
      } else if (R.depthBuffer && R.resolveDepthBuffer === !1 && l) {
        const M = R.stencilBuffer ? r.DEPTH_STENCIL_ATTACHMENT : r.DEPTH_ATTACHMENT;
        r.invalidateFramebuffer(r.DRAW_FRAMEBUFFER, [M]);
      }
    }
  }
  function de(R) {
    return Math.min(n.maxSamples, R.samples);
  }
  function ne(R) {
    const M = i.get(R);
    return R.samples > 0 && e.has("WEBGL_multisampled_render_to_texture") === !0 && M.__useRenderToTexture !== !1;
  }
  function ue(R) {
    const M = a.render.frame;
    h.get(R) !== M && (h.set(R, M), R.update());
  }
  function Ve(R, M) {
    const F = R.colorSpace, V = R.format, Q = R.type;
    return R.isCompressedTexture === !0 || R.isVideoTexture === !0 || F !== On && F !== un && (et.getTransfer(F) === ut ? (V !== oi || Q !== Hi) && console.warn("THREE.WebGLTextures: sRGB encoded textures have to use RGBAFormat and UnsignedByteType.") : console.error("THREE.WebGLTextures: Unsupported texture color space:", F)), M;
  }
  function ze(R) {
    return typeof HTMLImageElement < "u" && R instanceof HTMLImageElement ? (c.width = R.naturalWidth || R.width, c.height = R.naturalHeight || R.height) : typeof VideoFrame < "u" && R instanceof VideoFrame ? (c.width = R.displayWidth, c.height = R.displayHeight) : (c.width = R.width, c.height = R.height), c;
  }
  this.allocateTextureUnit = B, this.resetTextureUnits = N, this.setTexture2D = Z, this.setTexture2DArray = X, this.setTexture3D = ie, this.setTextureCube = G, this.rebindTextures = yt, this.setupRenderTarget = I, this.updateRenderTargetMipmap = ee, this.updateMultisampleRenderTarget = j, this.setupDepthRenderbuffer = $e, this.setupFrameBufferTexture = be, this.useMultisampledRTT = ne;
}
function pg(r, e) {
  function t(i, n = un) {
    let s;
    const a = et.getTransfer(n);
    if (i === Hi) return r.UNSIGNED_BYTE;
    if (i === Bl) return r.UNSIGNED_SHORT_4_4_4_4;
    if (i === kl) return r.UNSIGNED_SHORT_5_5_5_1;
    if (i === Qh) return r.UNSIGNED_INT_5_9_9_9_REV;
    if (i === ed) return r.UNSIGNED_INT_10F_11F_11F_REV;
    if (i === Kh) return r.BYTE;
    if (i === Jh) return r.SHORT;
    if (i === cr) return r.UNSIGNED_SHORT;
    if (i === Fl) return r.INT;
    if (i === yn) return r.UNSIGNED_INT;
    if (i === mi) return r.FLOAT;
    if (i === br) return r.HALF_FLOAT;
    if (i === td) return r.ALPHA;
    if (i === id) return r.RGB;
    if (i === oi) return r.RGBA;
    if (i === dr) return r.DEPTH_COMPONENT;
    if (i === ur) return r.DEPTH_STENCIL;
    if (i === zl) return r.RED;
    if (i === ba) return r.RED_INTEGER;
    if (i === nd) return r.RG;
    if (i === Hl) return r.RG_INTEGER;
    if (i === Vl) return r.RGBA_INTEGER;
    if (i === Yr || i === jr || i === $r || i === Kr)
      if (a === ut)
        if (s = e.get("WEBGL_compressed_texture_s3tc_srgb"), s !== null) {
          if (i === Yr) return s.COMPRESSED_SRGB_S3TC_DXT1_EXT;
          if (i === jr) return s.COMPRESSED_SRGB_ALPHA_S3TC_DXT1_EXT;
          if (i === $r) return s.COMPRESSED_SRGB_ALPHA_S3TC_DXT3_EXT;
          if (i === Kr) return s.COMPRESSED_SRGB_ALPHA_S3TC_DXT5_EXT;
        } else
          return null;
      else if (s = e.get("WEBGL_compressed_texture_s3tc"), s !== null) {
        if (i === Yr) return s.COMPRESSED_RGB_S3TC_DXT1_EXT;
        if (i === jr) return s.COMPRESSED_RGBA_S3TC_DXT1_EXT;
        if (i === $r) return s.COMPRESSED_RGBA_S3TC_DXT3_EXT;
        if (i === Kr) return s.COMPRESSED_RGBA_S3TC_DXT5_EXT;
      } else
        return null;
    if (i === tl || i === il || i === nl || i === sl)
      if (s = e.get("WEBGL_compressed_texture_pvrtc"), s !== null) {
        if (i === tl) return s.COMPRESSED_RGB_PVRTC_4BPPV1_IMG;
        if (i === il) return s.COMPRESSED_RGB_PVRTC_2BPPV1_IMG;
        if (i === nl) return s.COMPRESSED_RGBA_PVRTC_4BPPV1_IMG;
        if (i === sl) return s.COMPRESSED_RGBA_PVRTC_2BPPV1_IMG;
      } else
        return null;
    if (i === rl || i === al || i === ol)
      if (s = e.get("WEBGL_compressed_texture_etc"), s !== null) {
        if (i === rl || i === al) return a === ut ? s.COMPRESSED_SRGB8_ETC2 : s.COMPRESSED_RGB8_ETC2;
        if (i === ol) return a === ut ? s.COMPRESSED_SRGB8_ALPHA8_ETC2_EAC : s.COMPRESSED_RGBA8_ETC2_EAC;
      } else
        return null;
    if (i === ll || i === cl || i === hl || i === dl || i === ul || i === pl || i === fl || i === ml || i === gl || i === _l || i === yl || i === vl || i === xl || i === bl)
      if (s = e.get("WEBGL_compressed_texture_astc"), s !== null) {
        if (i === ll) return a === ut ? s.COMPRESSED_SRGB8_ALPHA8_ASTC_4x4_KHR : s.COMPRESSED_RGBA_ASTC_4x4_KHR;
        if (i === cl) return a === ut ? s.COMPRESSED_SRGB8_ALPHA8_ASTC_5x4_KHR : s.COMPRESSED_RGBA_ASTC_5x4_KHR;
        if (i === hl) return a === ut ? s.COMPRESSED_SRGB8_ALPHA8_ASTC_5x5_KHR : s.COMPRESSED_RGBA_ASTC_5x5_KHR;
        if (i === dl) return a === ut ? s.COMPRESSED_SRGB8_ALPHA8_ASTC_6x5_KHR : s.COMPRESSED_RGBA_ASTC_6x5_KHR;
        if (i === ul) return a === ut ? s.COMPRESSED_SRGB8_ALPHA8_ASTC_6x6_KHR : s.COMPRESSED_RGBA_ASTC_6x6_KHR;
        if (i === pl) return a === ut ? s.COMPRESSED_SRGB8_ALPHA8_ASTC_8x5_KHR : s.COMPRESSED_RGBA_ASTC_8x5_KHR;
        if (i === fl) return a === ut ? s.COMPRESSED_SRGB8_ALPHA8_ASTC_8x6_KHR : s.COMPRESSED_RGBA_ASTC_8x6_KHR;
        if (i === ml) return a === ut ? s.COMPRESSED_SRGB8_ALPHA8_ASTC_8x8_KHR : s.COMPRESSED_RGBA_ASTC_8x8_KHR;
        if (i === gl) return a === ut ? s.COMPRESSED_SRGB8_ALPHA8_ASTC_10x5_KHR : s.COMPRESSED_RGBA_ASTC_10x5_KHR;
        if (i === _l) return a === ut ? s.COMPRESSED_SRGB8_ALPHA8_ASTC_10x6_KHR : s.COMPRESSED_RGBA_ASTC_10x6_KHR;
        if (i === yl) return a === ut ? s.COMPRESSED_SRGB8_ALPHA8_ASTC_10x8_KHR : s.COMPRESSED_RGBA_ASTC_10x8_KHR;
        if (i === vl) return a === ut ? s.COMPRESSED_SRGB8_ALPHA8_ASTC_10x10_KHR : s.COMPRESSED_RGBA_ASTC_10x10_KHR;
        if (i === xl) return a === ut ? s.COMPRESSED_SRGB8_ALPHA8_ASTC_12x10_KHR : s.COMPRESSED_RGBA_ASTC_12x10_KHR;
        if (i === bl) return a === ut ? s.COMPRESSED_SRGB8_ALPHA8_ASTC_12x12_KHR : s.COMPRESSED_RGBA_ASTC_12x12_KHR;
      } else
        return null;
    if (i === Sl || i === Ml || i === wl)
      if (s = e.get("EXT_texture_compression_bptc"), s !== null) {
        if (i === Sl) return a === ut ? s.COMPRESSED_SRGB_ALPHA_BPTC_UNORM_EXT : s.COMPRESSED_RGBA_BPTC_UNORM_EXT;
        if (i === Ml) return s.COMPRESSED_RGB_BPTC_SIGNED_FLOAT_EXT;
        if (i === wl) return s.COMPRESSED_RGB_BPTC_UNSIGNED_FLOAT_EXT;
      } else
        return null;
    if (i === El || i === Tl || i === Al || i === Cl)
      if (s = e.get("EXT_texture_compression_rgtc"), s !== null) {
        if (i === El) return s.COMPRESSED_RED_RGTC1_EXT;
        if (i === Tl) return s.COMPRESSED_SIGNED_RED_RGTC1_EXT;
        if (i === Al) return s.COMPRESSED_RED_GREEN_RGTC2_EXT;
        if (i === Cl) return s.COMPRESSED_SIGNED_RED_GREEN_RGTC2_EXT;
      } else
        return null;
    return i === hr ? r.UNSIGNED_INT_24_8 : r[i] !== void 0 ? r[i] : null;
  }
  return { convert: t };
}
const OM = `
void main() {

	gl_Position = vec4( position, 1.0 );

}`, FM = `
uniform sampler2DArray depthColor;
uniform float depthWidth;
uniform float depthHeight;

void main() {

	vec2 coord = vec2( gl_FragCoord.x / depthWidth, gl_FragCoord.y / depthHeight );

	if ( coord.x >= 1.0 ) {

		gl_FragDepth = texture( depthColor, vec3( coord.x - 1.0, coord.y, 1 ) ).r;

	} else {

		gl_FragDepth = texture( depthColor, vec3( coord.x, coord.y, 0 ) ).r;

	}

}`;
class BM {
  /**
   * Constructs a new depth sensing module.
   */
  constructor() {
    this.texture = null, this.mesh = null, this.depthNear = 0, this.depthFar = 0;
  }
  /**
   * Inits the depth sensing module
   *
   * @param {XRWebGLDepthInformation} depthData - The XR depth data.
   * @param {XRRenderState} renderState - The XR render state.
   */
  init(e, t) {
    if (this.texture === null) {
      const i = new gd(e.texture);
      (e.depthNear !== t.depthNear || e.depthFar !== t.depthFar) && (this.depthNear = e.depthNear, this.depthFar = e.depthFar), this.texture = i;
    }
  }
  /**
   * Returns a plane mesh that visualizes the depth texture.
   *
   * @param {ArrayCamera} cameraXR - The XR camera.
   * @return {?Mesh} The plane mesh.
   */
  getMesh(e) {
    if (this.texture !== null && this.mesh === null) {
      const t = e.cameras[0].viewport, i = new Ci({
        vertexShader: OM,
        fragmentShader: FM,
        uniforms: {
          depthColor: { value: this.texture },
          depthWidth: { value: t.z },
          depthHeight: { value: t.w }
        }
      });
      this.mesh = new Je(new Vn(20, 20), i);
    }
    return this.mesh;
  }
  /**
   * Resets the module
   */
  reset() {
    this.texture = null, this.mesh = null;
  }
  /**
   * Returns a texture representing the depth of the user's environment.
   *
   * @return {?ExternalTexture} The depth texture.
   */
  getDepthTexture() {
    return this.texture;
  }
}
class kM extends sn {
  /**
   * Constructs a new WebGL renderer.
   *
   * @param {WebGLRenderer} renderer - The renderer.
   * @param {WebGL2RenderingContext} gl - The rendering context.
   */
  constructor(e, t) {
    super();
    const i = this;
    let n = null, s = 1, a = null, o = "local-floor", l = 1, c = null, h = null, d = null, u = null, p = null, m = null;
    const _ = typeof XRWebGLBinding < "u", g = new BM(), f = {}, v = t.getContextAttributes();
    let x = null, y = null;
    const A = [], S = [], C = new H();
    let P = null;
    const E = new kt();
    E.viewport = new Ye();
    const w = new kt();
    w.viewport = new Ye();
    const L = [E, w], N = new Qm();
    let B = null, W = null;
    this.cameraAutoUpdate = !0, this.enabled = !1, this.isPresenting = !1, this.getController = function(Y) {
      let te = A[Y];
      return te === void 0 && (te = new Wo(), A[Y] = te), te.getTargetRaySpace();
    }, this.getControllerGrip = function(Y) {
      let te = A[Y];
      return te === void 0 && (te = new Wo(), A[Y] = te), te.getGripSpace();
    }, this.getHand = function(Y) {
      let te = A[Y];
      return te === void 0 && (te = new Wo(), A[Y] = te), te.getHandSpace();
    };
    function Z(Y) {
      const te = S.indexOf(Y.inputSource);
      if (te === -1)
        return;
      const be = A[te];
      be !== void 0 && (be.update(Y.inputSource, Y.frame, c || a), be.dispatchEvent({ type: Y.type, data: Y.inputSource }));
    }
    function X() {
      n.removeEventListener("select", Z), n.removeEventListener("selectstart", Z), n.removeEventListener("selectend", Z), n.removeEventListener("squeeze", Z), n.removeEventListener("squeezestart", Z), n.removeEventListener("squeezeend", Z), n.removeEventListener("end", X), n.removeEventListener("inputsourceschange", ie);
      for (let Y = 0; Y < A.length; Y++) {
        const te = S[Y];
        te !== null && (S[Y] = null, A[Y].disconnect(te));
      }
      B = null, W = null, g.reset();
      for (const Y in f)
        delete f[Y];
      e.setRenderTarget(x), p = null, u = null, d = null, n = null, y = null, nt.stop(), i.isPresenting = !1, e.setPixelRatio(P), e.setSize(C.width, C.height, !1), i.dispatchEvent({ type: "sessionend" });
    }
    this.setFramebufferScaleFactor = function(Y) {
      s = Y, i.isPresenting === !0 && console.warn("THREE.WebXRManager: Cannot change framebuffer scale while presenting.");
    }, this.setReferenceSpaceType = function(Y) {
      o = Y, i.isPresenting === !0 && console.warn("THREE.WebXRManager: Cannot change reference space type while presenting.");
    }, this.getReferenceSpace = function() {
      return c || a;
    }, this.setReferenceSpace = function(Y) {
      c = Y;
    }, this.getBaseLayer = function() {
      return u !== null ? u : p;
    }, this.getBinding = function() {
      return d === null && _ && (d = new XRWebGLBinding(n, t)), d;
    }, this.getFrame = function() {
      return m;
    }, this.getSession = function() {
      return n;
    }, this.setSession = async function(Y) {
      if (n = Y, n !== null) {
        if (x = e.getRenderTarget(), n.addEventListener("select", Z), n.addEventListener("selectstart", Z), n.addEventListener("selectend", Z), n.addEventListener("squeeze", Z), n.addEventListener("squeezestart", Z), n.addEventListener("squeezeend", Z), n.addEventListener("end", X), n.addEventListener("inputsourceschange", ie), v.xrCompatible !== !0 && await t.makeXRCompatible(), P = e.getPixelRatio(), e.getSize(C), _ && "createProjectionLayer" in XRWebGLBinding.prototype) {
          let be = null, Le = null, Ee = null;
          v.depth && (Ee = v.stencil ? t.DEPTH24_STENCIL8 : t.DEPTH_COMPONENT24, be = v.stencil ? ur : dr, Le = v.stencil ? hr : yn);
          const $e = {
            colorFormat: t.RGBA8,
            depthFormat: Ee,
            scaleFactor: s
          };
          d = this.getBinding(), u = d.createProjectionLayer($e), n.updateRenderState({ layers: [u] }), e.setPixelRatio(1), e.setSize(u.textureWidth, u.textureHeight, !1), y = new nn(
            u.textureWidth,
            u.textureHeight,
            {
              format: oi,
              type: Hi,
              depthTexture: new md(u.textureWidth, u.textureHeight, Le, void 0, void 0, void 0, void 0, void 0, void 0, be),
              stencilBuffer: v.stencil,
              colorSpace: e.outputColorSpace,
              samples: v.antialias ? 4 : 0,
              resolveDepthBuffer: u.ignoreDepthValues === !1,
              resolveStencilBuffer: u.ignoreDepthValues === !1
            }
          );
        } else {
          const be = {
            antialias: v.antialias,
            alpha: !0,
            depth: v.depth,
            stencil: v.stencil,
            framebufferScaleFactor: s
          };
          p = new XRWebGLLayer(n, t, be), n.updateRenderState({ baseLayer: p }), e.setPixelRatio(1), e.setSize(p.framebufferWidth, p.framebufferHeight, !1), y = new nn(
            p.framebufferWidth,
            p.framebufferHeight,
            {
              format: oi,
              type: Hi,
              colorSpace: e.outputColorSpace,
              stencilBuffer: v.stencil,
              resolveDepthBuffer: p.ignoreDepthValues === !1,
              resolveStencilBuffer: p.ignoreDepthValues === !1
            }
          );
        }
        y.isXRRenderTarget = !0, this.setFoveation(l), c = null, a = await n.requestReferenceSpace(o), nt.setContext(n), nt.start(), i.isPresenting = !0, i.dispatchEvent({ type: "sessionstart" });
      }
    }, this.getEnvironmentBlendMode = function() {
      if (n !== null)
        return n.environmentBlendMode;
    }, this.getDepthTexture = function() {
      return g.getDepthTexture();
    };
    function ie(Y) {
      for (let te = 0; te < Y.removed.length; te++) {
        const be = Y.removed[te], Le = S.indexOf(be);
        Le >= 0 && (S[Le] = null, A[Le].disconnect(be));
      }
      for (let te = 0; te < Y.added.length; te++) {
        const be = Y.added[te];
        let Le = S.indexOf(be);
        if (Le === -1) {
          for (let $e = 0; $e < A.length; $e++)
            if ($e >= S.length) {
              S.push(be), Le = $e;
              break;
            } else if (S[$e] === null) {
              S[$e] = be, Le = $e;
              break;
            }
          if (Le === -1) break;
        }
        const Ee = A[Le];
        Ee && Ee.connect(be);
      }
    }
    const G = new b(), he = new b();
    function me(Y, te, be) {
      G.setFromMatrixPosition(te.matrixWorld), he.setFromMatrixPosition(be.matrixWorld);
      const Le = G.distanceTo(he), Ee = te.projectionMatrix.elements, $e = be.projectionMatrix.elements, yt = Ee[14] / (Ee[10] - 1), I = Ee[14] / (Ee[10] + 1), ee = (Ee[9] + 1) / Ee[5], K = (Ee[9] - 1) / Ee[5], $ = (Ee[8] - 1) / Ee[0], j = ($e[8] + 1) / $e[0], de = yt * $, ne = yt * j, ue = Le / (-$ + j), Ve = ue * -$;
      if (te.matrixWorld.decompose(Y.position, Y.quaternion, Y.scale), Y.translateX(Ve), Y.translateZ(ue), Y.matrixWorld.compose(Y.position, Y.quaternion, Y.scale), Y.matrixWorldInverse.copy(Y.matrixWorld).invert(), Ee[10] === -1)
        Y.projectionMatrix.copy(te.projectionMatrix), Y.projectionMatrixInverse.copy(te.projectionMatrixInverse);
      else {
        const ze = yt + ue, R = I + ue, M = de - Ve, F = ne + (Le - Ve), V = ee * I / R * ze, Q = K * I / R * ze;
        Y.projectionMatrix.makePerspective(M, F, V, Q, ze, R), Y.projectionMatrixInverse.copy(Y.projectionMatrix).invert();
      }
    }
    function Se(Y, te) {
      te === null ? Y.matrixWorld.copy(Y.matrix) : Y.matrixWorld.multiplyMatrices(te.matrixWorld, Y.matrix), Y.matrixWorldInverse.copy(Y.matrixWorld).invert();
    }
    this.updateCamera = function(Y) {
      if (n === null) return;
      let te = Y.near, be = Y.far;
      g.texture !== null && (g.depthNear > 0 && (te = g.depthNear), g.depthFar > 0 && (be = g.depthFar)), N.near = w.near = E.near = te, N.far = w.far = E.far = be, (B !== N.near || W !== N.far) && (n.updateRenderState({
        depthNear: N.near,
        depthFar: N.far
      }), B = N.near, W = N.far), N.layers.mask = Y.layers.mask | 6, E.layers.mask = N.layers.mask & 3, w.layers.mask = N.layers.mask & 5;
      const Le = Y.parent, Ee = N.cameras;
      Se(N, Le);
      for (let $e = 0; $e < Ee.length; $e++)
        Se(Ee[$e], Le);
      Ee.length === 2 ? me(N, E, w) : N.projectionMatrix.copy(E.projectionMatrix), We(Y, N, Le);
    };
    function We(Y, te, be) {
      be === null ? Y.matrix.copy(te.matrixWorld) : (Y.matrix.copy(be.matrixWorld), Y.matrix.invert(), Y.matrix.multiply(te.matrixWorld)), Y.matrix.decompose(Y.position, Y.quaternion, Y.scale), Y.updateMatrixWorld(!0), Y.projectionMatrix.copy(te.projectionMatrix), Y.projectionMatrixInverse.copy(te.projectionMatrixInverse), Y.isPerspectiveCamera && (Y.fov = fr * 2 * Math.atan(1 / Y.projectionMatrix.elements[5]), Y.zoom = 1);
    }
    this.getCamera = function() {
      return N;
    }, this.getFoveation = function() {
      if (!(u === null && p === null))
        return l;
    }, this.setFoveation = function(Y) {
      l = Y, u !== null && (u.fixedFoveation = Y), p !== null && p.fixedFoveation !== void 0 && (p.fixedFoveation = Y);
    }, this.hasDepthSensing = function() {
      return g.texture !== null;
    }, this.getDepthSensingMesh = function() {
      return g.getMesh(N);
    }, this.getCameraTexture = function(Y) {
      return f[Y];
    };
    let Qe = null;
    function ht(Y, te) {
      if (h = te.getViewerPose(c || a), m = te, h !== null) {
        const be = h.views;
        p !== null && (e.setRenderTargetFramebuffer(y, p.framebuffer), e.setRenderTarget(y));
        let Le = !1;
        be.length !== N.cameras.length && (N.cameras.length = 0, Le = !0);
        for (let I = 0; I < be.length; I++) {
          const ee = be[I];
          let K = null;
          if (p !== null)
            K = p.getViewport(ee);
          else {
            const j = d.getViewSubImage(u, ee);
            K = j.viewport, I === 0 && (e.setRenderTargetTextures(
              y,
              j.colorTexture,
              j.depthStencilTexture
            ), e.setRenderTarget(y));
          }
          let $ = L[I];
          $ === void 0 && ($ = new kt(), $.layers.enable(I), $.viewport = new Ye(), L[I] = $), $.matrix.fromArray(ee.transform.matrix), $.matrix.decompose($.position, $.quaternion, $.scale), $.projectionMatrix.fromArray(ee.projectionMatrix), $.projectionMatrixInverse.copy($.projectionMatrix).invert(), $.viewport.set(K.x, K.y, K.width, K.height), I === 0 && (N.matrix.copy($.matrix), N.matrix.decompose(N.position, N.quaternion, N.scale)), Le === !0 && N.cameras.push($);
        }
        const Ee = n.enabledFeatures;
        if (Ee && Ee.includes("depth-sensing") && n.depthUsage == "gpu-optimized" && _) {
          d = i.getBinding();
          const I = d.getDepthInformation(be[0]);
          I && I.isValid && I.texture && g.init(I, n.renderState);
        }
        if (Ee && Ee.includes("camera-access") && _) {
          e.state.unbindTexture(), d = i.getBinding();
          for (let I = 0; I < be.length; I++) {
            const ee = be[I].camera;
            if (ee) {
              let K = f[ee];
              K || (K = new gd(), f[ee] = K);
              const $ = d.getCameraImage(ee);
              K.sourceTexture = $;
            }
          }
        }
      }
      for (let be = 0; be < A.length; be++) {
        const Le = S[be], Ee = A[be];
        Le !== null && Ee !== void 0 && Ee.update(Le, te, c || a);
      }
      Qe && Qe(Y, te), te.detectedPlanes && i.dispatchEvent({ type: "planesdetected", data: te }), m = null;
    }
    const nt = new lg();
    nt.setAnimationLoop(ht), this.setAnimationLoop = function(Y) {
      Qe = Y;
    }, this.dispose = function() {
    };
  }
}
const rs = /* @__PURE__ */ new Ai(), zM = /* @__PURE__ */ new Ne();
function HM(r, e) {
  function t(g, f) {
    g.matrixAutoUpdate === !0 && g.updateMatrix(), f.value.copy(g.matrix);
  }
  function i(g, f) {
    f.color.getRGB(g.fogColor.value, um(r)), f.isFog ? (g.fogNear.value = f.near, g.fogFar.value = f.far) : f.isFogExp2 && (g.fogDensity.value = f.density);
  }
  function n(g, f, v, x, y) {
    f.isMeshBasicMaterial || f.isMeshLambertMaterial ? s(g, f) : f.isMeshToonMaterial ? (s(g, f), d(g, f)) : f.isMeshPhongMaterial ? (s(g, f), h(g, f)) : f.isMeshStandardMaterial ? (s(g, f), u(g, f), f.isMeshPhysicalMaterial && p(g, f, y)) : f.isMeshMatcapMaterial ? (s(g, f), m(g, f)) : f.isMeshDepthMaterial ? s(g, f) : f.isMeshDistanceMaterial ? (s(g, f), _(g, f)) : f.isMeshNormalMaterial ? s(g, f) : f.isLineBasicMaterial ? (a(g, f), f.isLineDashedMaterial && o(g, f)) : f.isPointsMaterial ? l(g, f, v, x) : f.isSpriteMaterial ? c(g, f) : f.isShadowMaterial ? (g.color.value.copy(f.color), g.opacity.value = f.opacity) : f.isShaderMaterial && (f.uniformsNeedUpdate = !1);
  }
  function s(g, f) {
    g.opacity.value = f.opacity, f.color && g.diffuse.value.copy(f.color), f.emissive && g.emissive.value.copy(f.emissive).multiplyScalar(f.emissiveIntensity), f.map && (g.map.value = f.map, t(f.map, g.mapTransform)), f.alphaMap && (g.alphaMap.value = f.alphaMap, t(f.alphaMap, g.alphaMapTransform)), f.bumpMap && (g.bumpMap.value = f.bumpMap, t(f.bumpMap, g.bumpMapTransform), g.bumpScale.value = f.bumpScale, f.side === zt && (g.bumpScale.value *= -1)), f.normalMap && (g.normalMap.value = f.normalMap, t(f.normalMap, g.normalMapTransform), g.normalScale.value.copy(f.normalScale), f.side === zt && g.normalScale.value.negate()), f.displacementMap && (g.displacementMap.value = f.displacementMap, t(f.displacementMap, g.displacementMapTransform), g.displacementScale.value = f.displacementScale, g.displacementBias.value = f.displacementBias), f.emissiveMap && (g.emissiveMap.value = f.emissiveMap, t(f.emissiveMap, g.emissiveMapTransform)), f.specularMap && (g.specularMap.value = f.specularMap, t(f.specularMap, g.specularMapTransform)), f.alphaTest > 0 && (g.alphaTest.value = f.alphaTest);
    const v = e.get(f), x = v.envMap, y = v.envMapRotation;
    x && (g.envMap.value = x, rs.copy(y), rs.x *= -1, rs.y *= -1, rs.z *= -1, x.isCubeTexture && x.isRenderTargetTexture === !1 && (rs.y *= -1, rs.z *= -1), g.envMapRotation.value.setFromMatrix4(zM.makeRotationFromEuler(rs)), g.flipEnvMap.value = x.isCubeTexture && x.isRenderTargetTexture === !1 ? -1 : 1, g.reflectivity.value = f.reflectivity, g.ior.value = f.ior, g.refractionRatio.value = f.refractionRatio), f.lightMap && (g.lightMap.value = f.lightMap, g.lightMapIntensity.value = f.lightMapIntensity, t(f.lightMap, g.lightMapTransform)), f.aoMap && (g.aoMap.value = f.aoMap, g.aoMapIntensity.value = f.aoMapIntensity, t(f.aoMap, g.aoMapTransform));
  }
  function a(g, f) {
    g.diffuse.value.copy(f.color), g.opacity.value = f.opacity, f.map && (g.map.value = f.map, t(f.map, g.mapTransform));
  }
  function o(g, f) {
    g.dashSize.value = f.dashSize, g.totalSize.value = f.dashSize + f.gapSize, g.scale.value = f.scale;
  }
  function l(g, f, v, x) {
    g.diffuse.value.copy(f.color), g.opacity.value = f.opacity, g.size.value = f.size * v, g.scale.value = x * 0.5, f.map && (g.map.value = f.map, t(f.map, g.uvTransform)), f.alphaMap && (g.alphaMap.value = f.alphaMap, t(f.alphaMap, g.alphaMapTransform)), f.alphaTest > 0 && (g.alphaTest.value = f.alphaTest);
  }
  function c(g, f) {
    g.diffuse.value.copy(f.color), g.opacity.value = f.opacity, g.rotation.value = f.rotation, f.map && (g.map.value = f.map, t(f.map, g.mapTransform)), f.alphaMap && (g.alphaMap.value = f.alphaMap, t(f.alphaMap, g.alphaMapTransform)), f.alphaTest > 0 && (g.alphaTest.value = f.alphaTest);
  }
  function h(g, f) {
    g.specular.value.copy(f.specular), g.shininess.value = Math.max(f.shininess, 1e-4);
  }
  function d(g, f) {
    f.gradientMap && (g.gradientMap.value = f.gradientMap);
  }
  function u(g, f) {
    g.metalness.value = f.metalness, f.metalnessMap && (g.metalnessMap.value = f.metalnessMap, t(f.metalnessMap, g.metalnessMapTransform)), g.roughness.value = f.roughness, f.roughnessMap && (g.roughnessMap.value = f.roughnessMap, t(f.roughnessMap, g.roughnessMapTransform)), f.envMap && (g.envMapIntensity.value = f.envMapIntensity);
  }
  function p(g, f, v) {
    g.ior.value = f.ior, f.sheen > 0 && (g.sheenColor.value.copy(f.sheenColor).multiplyScalar(f.sheen), g.sheenRoughness.value = f.sheenRoughness, f.sheenColorMap && (g.sheenColorMap.value = f.sheenColorMap, t(f.sheenColorMap, g.sheenColorMapTransform)), f.sheenRoughnessMap && (g.sheenRoughnessMap.value = f.sheenRoughnessMap, t(f.sheenRoughnessMap, g.sheenRoughnessMapTransform))), f.clearcoat > 0 && (g.clearcoat.value = f.clearcoat, g.clearcoatRoughness.value = f.clearcoatRoughness, f.clearcoatMap && (g.clearcoatMap.value = f.clearcoatMap, t(f.clearcoatMap, g.clearcoatMapTransform)), f.clearcoatRoughnessMap && (g.clearcoatRoughnessMap.value = f.clearcoatRoughnessMap, t(f.clearcoatRoughnessMap, g.clearcoatRoughnessMapTransform)), f.clearcoatNormalMap && (g.clearcoatNormalMap.value = f.clearcoatNormalMap, t(f.clearcoatNormalMap, g.clearcoatNormalMapTransform), g.clearcoatNormalScale.value.copy(f.clearcoatNormalScale), f.side === zt && g.clearcoatNormalScale.value.negate())), f.dispersion > 0 && (g.dispersion.value = f.dispersion), f.iridescence > 0 && (g.iridescence.value = f.iridescence, g.iridescenceIOR.value = f.iridescenceIOR, g.iridescenceThicknessMinimum.value = f.iridescenceThicknessRange[0], g.iridescenceThicknessMaximum.value = f.iridescenceThicknessRange[1], f.iridescenceMap && (g.iridescenceMap.value = f.iridescenceMap, t(f.iridescenceMap, g.iridescenceMapTransform)), f.iridescenceThicknessMap && (g.iridescenceThicknessMap.value = f.iridescenceThicknessMap, t(f.iridescenceThicknessMap, g.iridescenceThicknessMapTransform))), f.transmission > 0 && (g.transmission.value = f.transmission, g.transmissionSamplerMap.value = v.texture, g.transmissionSamplerSize.value.set(v.width, v.height), f.transmissionMap && (g.transmissionMap.value = f.transmissionMap, t(f.transmissionMap, g.transmissionMapTransform)), g.thickness.value = f.thickness, f.thicknessMap && (g.thicknessMap.value = f.thicknessMap, t(f.thicknessMap, g.thicknessMapTransform)), g.attenuationDistance.value = f.attenuationDistance, g.attenuationColor.value.copy(f.attenuationColor)), f.anisotropy > 0 && (g.anisotropyVector.value.set(f.anisotropy * Math.cos(f.anisotropyRotation), f.anisotropy * Math.sin(f.anisotropyRotation)), f.anisotropyMap && (g.anisotropyMap.value = f.anisotropyMap, t(f.anisotropyMap, g.anisotropyMapTransform))), g.specularIntensity.value = f.specularIntensity, g.specularColor.value.copy(f.specularColor), f.specularColorMap && (g.specularColorMap.value = f.specularColorMap, t(f.specularColorMap, g.specularColorMapTransform)), f.specularIntensityMap && (g.specularIntensityMap.value = f.specularIntensityMap, t(f.specularIntensityMap, g.specularIntensityMapTransform));
  }
  function m(g, f) {
    f.matcap && (g.matcap.value = f.matcap);
  }
  function _(g, f) {
    const v = e.get(f).light;
    g.referencePosition.value.setFromMatrixPosition(v.matrixWorld), g.nearDistance.value = v.shadow.camera.near, g.farDistance.value = v.shadow.camera.far;
  }
  return {
    refreshFogUniforms: i,
    refreshMaterialUniforms: n
  };
}
function VM(r, e, t, i) {
  let n = {}, s = {}, a = [];
  const o = r.getParameter(r.MAX_UNIFORM_BUFFER_BINDINGS);
  function l(v, x) {
    const y = x.program;
    i.uniformBlockBinding(v, y);
  }
  function c(v, x) {
    let y = n[v.id];
    y === void 0 && (m(v), y = h(v), n[v.id] = y, v.addEventListener("dispose", g));
    const A = x.program;
    i.updateUBOMapping(v, A);
    const S = e.render.frame;
    s[v.id] !== S && (u(v), s[v.id] = S);
  }
  function h(v) {
    const x = d();
    v.__bindingPointIndex = x;
    const y = r.createBuffer(), A = v.__size, S = v.usage;
    return r.bindBuffer(r.UNIFORM_BUFFER, y), r.bufferData(r.UNIFORM_BUFFER, A, S), r.bindBuffer(r.UNIFORM_BUFFER, null), r.bindBufferBase(r.UNIFORM_BUFFER, x, y), y;
  }
  function d() {
    for (let v = 0; v < o; v++)
      if (a.indexOf(v) === -1)
        return a.push(v), v;
    return console.error("THREE.WebGLRenderer: Maximum number of simultaneously usable uniforms groups reached."), 0;
  }
  function u(v) {
    const x = n[v.id], y = v.uniforms, A = v.__cache;
    r.bindBuffer(r.UNIFORM_BUFFER, x);
    for (let S = 0, C = y.length; S < C; S++) {
      const P = Array.isArray(y[S]) ? y[S] : [y[S]];
      for (let E = 0, w = P.length; E < w; E++) {
        const L = P[E];
        if (p(L, S, E, A) === !0) {
          const N = L.__offset, B = Array.isArray(L.value) ? L.value : [L.value];
          let W = 0;
          for (let Z = 0; Z < B.length; Z++) {
            const X = B[Z], ie = _(X);
            typeof X == "number" || typeof X == "boolean" ? (L.__data[0] = X, r.bufferSubData(r.UNIFORM_BUFFER, N + W, L.__data)) : X.isMatrix3 ? (L.__data[0] = X.elements[0], L.__data[1] = X.elements[1], L.__data[2] = X.elements[2], L.__data[3] = 0, L.__data[4] = X.elements[3], L.__data[5] = X.elements[4], L.__data[6] = X.elements[5], L.__data[7] = 0, L.__data[8] = X.elements[6], L.__data[9] = X.elements[7], L.__data[10] = X.elements[8], L.__data[11] = 0) : (X.toArray(L.__data, W), W += ie.storage / Float32Array.BYTES_PER_ELEMENT);
          }
          r.bufferSubData(r.UNIFORM_BUFFER, N, L.__data);
        }
      }
    }
    r.bindBuffer(r.UNIFORM_BUFFER, null);
  }
  function p(v, x, y, A) {
    const S = v.value, C = x + "_" + y;
    if (A[C] === void 0)
      return typeof S == "number" || typeof S == "boolean" ? A[C] = S : A[C] = S.clone(), !0;
    {
      const P = A[C];
      if (typeof S == "number" || typeof S == "boolean") {
        if (P !== S)
          return A[C] = S, !0;
      } else if (P.equals(S) === !1)
        return P.copy(S), !0;
    }
    return !1;
  }
  function m(v) {
    const x = v.uniforms;
    let y = 0;
    const A = 16;
    for (let C = 0, P = x.length; C < P; C++) {
      const E = Array.isArray(x[C]) ? x[C] : [x[C]];
      for (let w = 0, L = E.length; w < L; w++) {
        const N = E[w], B = Array.isArray(N.value) ? N.value : [N.value];
        for (let W = 0, Z = B.length; W < Z; W++) {
          const X = B[W], ie = _(X), G = y % A, he = G % ie.boundary, me = G + he;
          y += he, me !== 0 && A - me < ie.storage && (y += A - me), N.__data = new Float32Array(ie.storage / Float32Array.BYTES_PER_ELEMENT), N.__offset = y, y += ie.storage;
        }
      }
    }
    const S = y % A;
    return S > 0 && (y += A - S), v.__size = y, v.__cache = {}, this;
  }
  function _(v) {
    const x = {
      boundary: 0,
      // bytes
      storage: 0
      // bytes
    };
    return typeof v == "number" || typeof v == "boolean" ? (x.boundary = 4, x.storage = 4) : v.isVector2 ? (x.boundary = 8, x.storage = 8) : v.isVector3 || v.isColor ? (x.boundary = 16, x.storage = 12) : v.isVector4 ? (x.boundary = 16, x.storage = 16) : v.isMatrix3 ? (x.boundary = 48, x.storage = 48) : v.isMatrix4 ? (x.boundary = 64, x.storage = 64) : v.isTexture ? console.warn("THREE.WebGLRenderer: Texture samplers can not be part of an uniforms group.") : console.warn("THREE.WebGLRenderer: Unsupported uniform value type.", v), x;
  }
  function g(v) {
    const x = v.target;
    x.removeEventListener("dispose", g);
    const y = a.indexOf(x.__bindingPointIndex);
    a.splice(y, 1), r.deleteBuffer(n[x.id]), delete n[x.id], delete s[x.id];
  }
  function f() {
    for (const v in n)
      r.deleteBuffer(n[v]);
    a = [], n = {}, s = {};
  }
  return {
    bind: l,
    update: c,
    dispose: f
  };
}
class fg {
  /**
   * Constructs a new WebGL renderer.
   *
   * @param {WebGLRenderer~Options} [parameters] - The configuration parameter.
   */
  constructor(e = {}) {
    const {
      canvas: t = cm(),
      context: i = null,
      depth: n = !0,
      stencil: s = !1,
      alpha: a = !1,
      antialias: o = !1,
      premultipliedAlpha: l = !0,
      preserveDrawingBuffer: c = !1,
      powerPreference: h = "default",
      failIfMajorPerformanceCaveat: d = !1,
      reversedDepthBuffer: u = !1
    } = e;
    this.isWebGLRenderer = !0;
    let p;
    if (i !== null) {
      if (typeof WebGLRenderingContext < "u" && i instanceof WebGLRenderingContext)
        throw new Error("THREE.WebGLRenderer: WebGL 1 is not supported since r163.");
      p = i.getContextAttributes().alpha;
    } else
      p = a;
    const m = new Uint32Array(4), _ = new Int32Array(4);
    let g = null, f = null;
    const v = [], x = [];
    this.domElement = t, this.debug = {
      /**
       * Enables error checking and reporting when shader programs are being compiled.
       * @type {boolean}
       */
      checkShaderErrors: !0,
      /**
       * Callback for custom error reporting.
       * @type {?Function}
       */
      onShaderError: null
    }, this.autoClear = !0, this.autoClearColor = !0, this.autoClearDepth = !0, this.autoClearStencil = !0, this.sortObjects = !0, this.clippingPlanes = [], this.localClippingEnabled = !1, this.toneMapping = mn, this.toneMappingExposure = 1, this.transmissionResolutionScale = 1;
    const y = this;
    let A = !1;
    this._outputColorSpace = Qt;
    let S = 0, C = 0, P = null, E = -1, w = null;
    const L = new Ye(), N = new Ye();
    let B = null;
    const W = new oe(0);
    let Z = 0, X = t.width, ie = t.height, G = 1, he = null, me = null;
    const Se = new Ye(0, 0, X, ie), We = new Ye(0, 0, X, ie);
    let Qe = !1;
    const ht = new Sr();
    let nt = !1, Y = !1;
    const te = new Ne(), be = new b(), Le = new Ye(), Ee = { background: null, fog: null, environment: null, overrideMaterial: null, isScene: !0 };
    let $e = !1;
    function yt() {
      return P === null ? G : 1;
    }
    let I = i;
    function ee(T, U) {
      return t.getContext(T, U);
    }
    try {
      const T = {
        alpha: !0,
        depth: n,
        stencil: s,
        antialias: o,
        premultipliedAlpha: l,
        preserveDrawingBuffer: c,
        powerPreference: h,
        failIfMajorPerformanceCaveat: d
      };
      if ("setAttribute" in t && t.setAttribute("data-engine", `three.js r${Ul}`), t.addEventListener("webglcontextlost", fe, !1), t.addEventListener("webglcontextrestored", Me, !1), t.addEventListener("webglcontextcreationerror", re, !1), I === null) {
        const U = "webgl2";
        if (I = ee(U, T), I === null)
          throw ee(U) ? new Error("Error creating WebGL context with your selected attributes.") : new Error("Error creating WebGL context.");
      }
    } catch (T) {
      throw console.error("THREE.WebGLRenderer: " + T.message), T;
    }
    let K, $, j, de, ne, ue, Ve, ze, R, M, F, V, Q, q, Re, ce, Te, Ae, se, ye, Be, Pe, ge, qe;
    function D() {
      K = new eS(I), K.init(), Pe = new pg(I, K), $ = new Zb(I, K, e, Pe), j = new NM(I, K), $.reversedDepthBuffer && u && j.buffers.depth.setReversed(!0), de = new nS(I), ne = new bM(), ue = new UM(I, K, j, ne, $, Pe, de), Ve = new jb(y), ze = new Qb(y), R = new cv(I), ge = new Xb(I, R), M = new tS(I, R, de, ge), F = new rS(I, M, R, de), se = new sS(I, $, ue), ce = new Yb(ne), V = new xM(y, Ve, ze, K, $, ge, ce), Q = new HM(y, ne), q = new MM(), Re = new RM(K), Ae = new Wb(y, Ve, ze, j, F, p, l), Te = new IM(y, F, $), qe = new VM(I, de, $, j), ye = new qb(I, K, de), Be = new iS(I, K, de), de.programs = V.programs, y.capabilities = $, y.extensions = K, y.properties = ne, y.renderLists = q, y.shadowMap = Te, y.state = j, y.info = de;
    }
    D();
    const le = new kM(y, I);
    this.xr = le, this.getContext = function() {
      return I;
    }, this.getContextAttributes = function() {
      return I.getContextAttributes();
    }, this.forceContextLoss = function() {
      const T = K.get("WEBGL_lose_context");
      T && T.loseContext();
    }, this.forceContextRestore = function() {
      const T = K.get("WEBGL_lose_context");
      T && T.restoreContext();
    }, this.getPixelRatio = function() {
      return G;
    }, this.setPixelRatio = function(T) {
      T !== void 0 && (G = T, this.setSize(X, ie, !1));
    }, this.getSize = function(T) {
      return T.set(X, ie);
    }, this.setSize = function(T, U, k = !0) {
      if (le.isPresenting) {
        console.warn("THREE.WebGLRenderer: Can't change size while VR device is presenting.");
        return;
      }
      X = T, ie = U, t.width = Math.floor(T * G), t.height = Math.floor(U * G), k === !0 && (t.style.width = T + "px", t.style.height = U + "px"), this.setViewport(0, 0, T, U);
    }, this.getDrawingBufferSize = function(T) {
      return T.set(X * G, ie * G).floor();
    }, this.setDrawingBufferSize = function(T, U, k) {
      X = T, ie = U, G = k, t.width = Math.floor(T * k), t.height = Math.floor(U * k), this.setViewport(0, 0, T, U);
    }, this.getCurrentViewport = function(T) {
      return T.copy(L);
    }, this.getViewport = function(T) {
      return T.copy(Se);
    }, this.setViewport = function(T, U, k, z) {
      T.isVector4 ? Se.set(T.x, T.y, T.z, T.w) : Se.set(T, U, k, z), j.viewport(L.copy(Se).multiplyScalar(G).round());
    }, this.getScissor = function(T) {
      return T.copy(We);
    }, this.setScissor = function(T, U, k, z) {
      T.isVector4 ? We.set(T.x, T.y, T.z, T.w) : We.set(T, U, k, z), j.scissor(N.copy(We).multiplyScalar(G).round());
    }, this.getScissorTest = function() {
      return Qe;
    }, this.setScissorTest = function(T) {
      j.setScissorTest(Qe = T);
    }, this.setOpaqueSort = function(T) {
      he = T;
    }, this.setTransparentSort = function(T) {
      me = T;
    }, this.getClearColor = function(T) {
      return T.copy(Ae.getClearColor());
    }, this.setClearColor = function() {
      Ae.setClearColor(...arguments);
    }, this.getClearAlpha = function() {
      return Ae.getClearAlpha();
    }, this.setClearAlpha = function() {
      Ae.setClearAlpha(...arguments);
    }, this.clear = function(T = !0, U = !0, k = !0) {
      let z = 0;
      if (T) {
        let O = !1;
        if (P !== null) {
          const ae = P.texture.format;
          O = ae === Vl || ae === Hl || ae === ba;
        }
        if (O) {
          const ae = P.texture.type, _e = ae === Hi || ae === yn || ae === cr || ae === hr || ae === Bl || ae === kl, we = Ae.getClearColor(), xe = Ae.getClearAlpha(), Oe = we.r, ke = we.g, Ie = we.b;
          _e ? (m[0] = Oe, m[1] = ke, m[2] = Ie, m[3] = xe, I.clearBufferuiv(I.COLOR, 0, m)) : (_[0] = Oe, _[1] = ke, _[2] = Ie, _[3] = xe, I.clearBufferiv(I.COLOR, 0, _));
        } else
          z |= I.COLOR_BUFFER_BIT;
      }
      U && (z |= I.DEPTH_BUFFER_BIT), k && (z |= I.STENCIL_BUFFER_BIT, this.state.buffers.stencil.setMask(4294967295)), I.clear(z);
    }, this.clearColor = function() {
      this.clear(!0, !1, !1);
    }, this.clearDepth = function() {
      this.clear(!1, !0, !1);
    }, this.clearStencil = function() {
      this.clear(!1, !1, !0);
    }, this.dispose = function() {
      t.removeEventListener("webglcontextlost", fe, !1), t.removeEventListener("webglcontextrestored", Me, !1), t.removeEventListener("webglcontextcreationerror", re, !1), Ae.dispose(), q.dispose(), Re.dispose(), ne.dispose(), Ve.dispose(), ze.dispose(), F.dispose(), ge.dispose(), qe.dispose(), V.dispose(), le.dispose(), le.removeEventListener("sessionstart", Gi), le.removeEventListener("sessionend", jd), Wn.stop();
    };
    function fe(T) {
      T.preventDefault(), console.log("THREE.WebGLRenderer: Context Lost."), A = !0;
    }
    function Me() {
      console.log("THREE.WebGLRenderer: Context Restored."), A = !1;
      const T = de.autoReset, U = Te.enabled, k = Te.autoUpdate, z = Te.needsUpdate, O = Te.type;
      D(), de.autoReset = T, Te.enabled = U, Te.autoUpdate = k, Te.needsUpdate = z, Te.type = O;
    }
    function re(T) {
      console.error("THREE.WebGLRenderer: A WebGL context could not be created. Reason: ", T.statusMessage);
    }
    function J(T) {
      const U = T.target;
      U.removeEventListener("dispose", J), Ce(U);
    }
    function Ce(T) {
      Ge(T), ne.remove(T);
    }
    function Ge(T) {
      const U = ne.get(T).programs;
      U !== void 0 && (U.forEach(function(k) {
        V.releaseProgram(k);
      }), T.isShaderMaterial && V.releaseShaderCache(T));
    }
    this.renderBufferDirect = function(T, U, k, z, O, ae) {
      U === null && (U = Ee);
      const _e = O.isMesh && O.matrixWorld.determinant() < 0, we = Pg(T, U, k, z, O);
      j.setMaterial(z, _e);
      let xe = k.index, Oe = 1;
      if (z.wireframe === !0) {
        if (xe = M.getWireframeAttribute(k), xe === void 0) return;
        Oe = 2;
      }
      const ke = k.drawRange, Ie = k.attributes.position;
      let Ke = ke.start * Oe, pt = (ke.start + ke.count) * Oe;
      ae !== null && (Ke = Math.max(Ke, ae.start * Oe), pt = Math.min(pt, (ae.start + ae.count) * Oe)), xe !== null ? (Ke = Math.max(Ke, 0), pt = Math.min(pt, xe.count)) : Ie != null && (Ke = Math.max(Ke, 0), pt = Math.min(pt, Ie.count));
      const At = pt - Ke;
      if (At < 0 || At === 1 / 0) return;
      ge.setup(O, z, we, k, xe);
      let xt, gt = ye;
      if (xe !== null && (xt = R.get(xe), gt = Be, gt.setIndex(xt)), O.isMesh)
        z.wireframe === !0 ? (j.setLineWidth(z.wireframeLinewidth * yt()), gt.setMode(I.LINES)) : gt.setMode(I.TRIANGLES);
      else if (O.isLine) {
        let De = z.linewidth;
        De === void 0 && (De = 1), j.setLineWidth(De * yt()), O.isLineSegments ? gt.setMode(I.LINES) : O.isLineLoop ? gt.setMode(I.LINE_LOOP) : gt.setMode(I.LINE_STRIP);
      } else O.isPoints ? gt.setMode(I.POINTS) : O.isSprite && gt.setMode(I.TRIANGLES);
      if (O.isBatchedMesh)
        if (O._multiDrawInstances !== null)
          pa("THREE.WebGLRenderer: renderMultiDrawInstances has been deprecated and will be removed in r184. Append to renderMultiDraw arguments and use indirection."), gt.renderMultiDrawInstances(O._multiDrawStarts, O._multiDrawCounts, O._multiDrawCount, O._multiDrawInstances);
        else if (K.get("WEBGL_multi_draw"))
          gt.renderMultiDraw(O._multiDrawStarts, O._multiDrawCounts, O._multiDrawCount);
        else {
          const De = O._multiDrawStarts, St = O._multiDrawCounts, rt = O._multiDrawCount, _i = xe ? R.get(xe).bytesPerElement : 1, Rs = ne.get(z).currentProgram.getUniforms();
          for (let yi = 0; yi < rt; yi++)
            Rs.setValue(I, "_gl_DrawID", yi), gt.render(De[yi] / _i, St[yi]);
        }
      else if (O.isInstancedMesh)
        gt.renderInstances(Ke, At, O.count);
      else if (k.isInstancedBufferGeometry) {
        const De = k._maxInstanceCount !== void 0 ? k._maxInstanceCount : 1 / 0, St = Math.min(k.instanceCount, De);
        gt.renderInstances(Ke, At, St);
      } else
        gt.render(Ke, At);
    };
    function vt(T, U, k) {
      T.transparent === !0 && T.side === ri && T.forceSinglePass === !1 ? (T.side = zt, T.needsUpdate = !0, Ra(T, U, k), T.side = Di, T.needsUpdate = !0, Ra(T, U, k), T.side = ri) : Ra(T, U, k);
    }
    this.compile = function(T, U, k = null) {
      k === null && (k = T), f = Re.get(k), f.init(U), x.push(f), k.traverseVisible(function(O) {
        O.isLight && O.layers.test(U.layers) && (f.pushLight(O), O.castShadow && f.pushShadow(O));
      }), T !== k && T.traverseVisible(function(O) {
        O.isLight && O.layers.test(U.layers) && (f.pushLight(O), O.castShadow && f.pushShadow(O));
      }), f.setupLights();
      const z = /* @__PURE__ */ new Set();
      return T.traverse(function(O) {
        if (!(O.isMesh || O.isPoints || O.isLine || O.isSprite))
          return;
        const ae = O.material;
        if (ae)
          if (Array.isArray(ae))
            for (let _e = 0; _e < ae.length; _e++) {
              const we = ae[_e];
              vt(we, k, O), z.add(we);
            }
          else
            vt(ae, k, O), z.add(ae);
      }), f = x.pop(), z;
    }, this.compileAsync = function(T, U, k = null) {
      const z = this.compile(T, U, k);
      return new Promise((O) => {
        function ae() {
          if (z.forEach(function(_e) {
            ne.get(_e).currentProgram.isReady() && z.delete(_e);
          }), z.size === 0) {
            O(T);
            return;
          }
          setTimeout(ae, 10);
        }
        K.get("KHR_parallel_shader_compile") !== null ? ae() : setTimeout(ae, 10);
      });
    };
    let lt = null;
    function rn(T) {
      lt && lt(T);
    }
    function Gi() {
      Wn.stop();
    }
    function jd() {
      Wn.start();
    }
    const Wn = new lg();
    Wn.setAnimationLoop(rn), typeof self < "u" && Wn.setContext(self), this.setAnimationLoop = function(T) {
      lt = T, le.setAnimationLoop(T), T === null ? Wn.stop() : Wn.start();
    }, le.addEventListener("sessionstart", Gi), le.addEventListener("sessionend", jd), this.render = function(T, U) {
      if (U !== void 0 && U.isCamera !== !0) {
        console.error("THREE.WebGLRenderer.render: camera is not an instance of THREE.Camera.");
        return;
      }
      if (A === !0) return;
      if (T.matrixWorldAutoUpdate === !0 && T.updateMatrixWorld(), U.parent === null && U.matrixWorldAutoUpdate === !0 && U.updateMatrixWorld(), le.enabled === !0 && le.isPresenting === !0 && (le.cameraAutoUpdate === !0 && le.updateCamera(U), U = le.getCamera()), T.isScene === !0 && T.onBeforeRender(y, T, U, P), f = Re.get(T, x.length), f.init(U), x.push(f), te.multiplyMatrices(U.projectionMatrix, U.matrixWorldInverse), ht.setFromProjectionMatrix(te, wi, U.reversedDepth), Y = this.localClippingEnabled, nt = ce.init(this.clippingPlanes, Y), g = q.get(T, v.length), g.init(), v.push(g), le.enabled === !0 && le.isPresenting === !0) {
        const ae = y.xr.getDepthSensingMesh();
        ae !== null && yc(ae, U, -1 / 0, y.sortObjects);
      }
      yc(T, U, 0, y.sortObjects), g.finish(), y.sortObjects === !0 && g.sort(he, me), $e = le.enabled === !1 || le.isPresenting === !1 || le.hasDepthSensing() === !1, $e && Ae.addToRenderList(g, T), this.info.render.frame++, nt === !0 && ce.beginShadows();
      const k = f.state.shadowsArray;
      Te.render(k, T, U), nt === !0 && ce.endShadows(), this.info.autoReset === !0 && this.info.reset();
      const z = g.opaque, O = g.transmissive;
      if (f.setupLights(), U.isArrayCamera) {
        const ae = U.cameras;
        if (O.length > 0)
          for (let _e = 0, we = ae.length; _e < we; _e++) {
            const xe = ae[_e];
            Kd(z, O, T, xe);
          }
        $e && Ae.render(T);
        for (let _e = 0, we = ae.length; _e < we; _e++) {
          const xe = ae[_e];
          $d(g, T, xe, xe.viewport);
        }
      } else
        O.length > 0 && Kd(z, O, T, U), $e && Ae.render(T), $d(g, T, U);
      P !== null && C === 0 && (ue.updateMultisampleRenderTarget(P), ue.updateRenderTargetMipmap(P)), T.isScene === !0 && T.onAfterRender(y, T, U), ge.resetDefaultState(), E = -1, w = null, x.pop(), x.length > 0 ? (f = x[x.length - 1], nt === !0 && ce.setGlobalState(y.clippingPlanes, f.state.camera)) : f = null, v.pop(), v.length > 0 ? g = v[v.length - 1] : g = null;
    };
    function yc(T, U, k, z) {
      if (T.visible === !1) return;
      if (T.layers.test(U.layers)) {
        if (T.isGroup)
          k = T.renderOrder;
        else if (T.isLOD)
          T.autoUpdate === !0 && T.update(U);
        else if (T.isLight)
          f.pushLight(T), T.castShadow && f.pushShadow(T);
        else if (T.isSprite) {
          if (!T.frustumCulled || ht.intersectsSprite(T)) {
            z && Le.setFromMatrixPosition(T.matrixWorld).applyMatrix4(te);
            const _e = F.update(T), we = T.material;
            we.visible && g.push(T, _e, we, k, Le.z, null);
          }
        } else if ((T.isMesh || T.isLine || T.isPoints) && (!T.frustumCulled || ht.intersectsObject(T))) {
          const _e = F.update(T), we = T.material;
          if (z && (T.boundingSphere !== void 0 ? (T.boundingSphere === null && T.computeBoundingSphere(), Le.copy(T.boundingSphere.center)) : (_e.boundingSphere === null && _e.computeBoundingSphere(), Le.copy(_e.boundingSphere.center)), Le.applyMatrix4(T.matrixWorld).applyMatrix4(te)), Array.isArray(we)) {
            const xe = _e.groups;
            for (let Oe = 0, ke = xe.length; Oe < ke; Oe++) {
              const Ie = xe[Oe], Ke = we[Ie.materialIndex];
              Ke && Ke.visible && g.push(T, _e, Ke, k, Le.z, Ie);
            }
          } else we.visible && g.push(T, _e, we, k, Le.z, null);
        }
      }
      const ae = T.children;
      for (let _e = 0, we = ae.length; _e < we; _e++)
        yc(ae[_e], U, k, z);
    }
    function $d(T, U, k, z) {
      const O = T.opaque, ae = T.transmissive, _e = T.transparent;
      f.setupLightsView(k), nt === !0 && ce.setGlobalState(y.clippingPlanes, k), z && j.viewport(L.copy(z)), O.length > 0 && Ca(O, U, k), ae.length > 0 && Ca(ae, U, k), _e.length > 0 && Ca(_e, U, k), j.buffers.depth.setTest(!0), j.buffers.depth.setMask(!0), j.buffers.color.setMask(!0), j.setPolygonOffset(!1);
    }
    function Kd(T, U, k, z) {
      if ((k.isScene === !0 ? k.overrideMaterial : null) !== null)
        return;
      f.state.transmissionRenderTarget[z.id] === void 0 && (f.state.transmissionRenderTarget[z.id] = new nn(1, 1, {
        generateMipmaps: !0,
        type: K.has("EXT_color_buffer_half_float") || K.has("EXT_color_buffer_float") ? br : Hi,
        minFilter: Ji,
        samples: 4,
        stencilBuffer: s,
        resolveDepthBuffer: !1,
        resolveStencilBuffer: !1,
        colorSpace: et.workingColorSpace
      }));
      const ae = f.state.transmissionRenderTarget[z.id], _e = z.viewport || L;
      ae.setSize(_e.z * y.transmissionResolutionScale, _e.w * y.transmissionResolutionScale);
      const we = y.getRenderTarget(), xe = y.getActiveCubeFace(), Oe = y.getActiveMipmapLevel();
      y.setRenderTarget(ae), y.getClearColor(W), Z = y.getClearAlpha(), Z < 1 && y.setClearColor(16777215, 0.5), y.clear(), $e && Ae.render(k);
      const ke = y.toneMapping;
      y.toneMapping = mn;
      const Ie = z.viewport;
      if (z.viewport !== void 0 && (z.viewport = void 0), f.setupLightsView(z), nt === !0 && ce.setGlobalState(y.clippingPlanes, z), Ca(T, k, z), ue.updateMultisampleRenderTarget(ae), ue.updateRenderTargetMipmap(ae), K.has("WEBGL_multisampled_render_to_texture") === !1) {
        let Ke = !1;
        for (let pt = 0, At = U.length; pt < At; pt++) {
          const xt = U[pt], gt = xt.object, De = xt.geometry, St = xt.material, rt = xt.group;
          if (St.side === ri && gt.layers.test(z.layers)) {
            const _i = St.side;
            St.side = zt, St.needsUpdate = !0, Jd(gt, k, z, De, St, rt), St.side = _i, St.needsUpdate = !0, Ke = !0;
          }
        }
        Ke === !0 && (ue.updateMultisampleRenderTarget(ae), ue.updateRenderTargetMipmap(ae));
      }
      y.setRenderTarget(we, xe, Oe), y.setClearColor(W, Z), Ie !== void 0 && (z.viewport = Ie), y.toneMapping = ke;
    }
    function Ca(T, U, k) {
      const z = U.isScene === !0 ? U.overrideMaterial : null;
      for (let O = 0, ae = T.length; O < ae; O++) {
        const _e = T[O], we = _e.object, xe = _e.geometry, Oe = _e.group;
        let ke = _e.material;
        ke.allowOverride === !0 && z !== null && (ke = z), we.layers.test(k.layers) && Jd(we, U, k, xe, ke, Oe);
      }
    }
    function Jd(T, U, k, z, O, ae) {
      T.onBeforeRender(y, U, k, z, O, ae), T.modelViewMatrix.multiplyMatrices(k.matrixWorldInverse, T.matrixWorld), T.normalMatrix.getNormalMatrix(T.modelViewMatrix), O.onBeforeRender(y, U, k, z, T, ae), O.transparent === !0 && O.side === ri && O.forceSinglePass === !1 ? (O.side = zt, O.needsUpdate = !0, y.renderBufferDirect(k, U, z, O, T, ae), O.side = Di, O.needsUpdate = !0, y.renderBufferDirect(k, U, z, O, T, ae), O.side = ri) : y.renderBufferDirect(k, U, z, O, T, ae), T.onAfterRender(y, U, k, z, O, ae);
    }
    function Ra(T, U, k) {
      U.isScene !== !0 && (U = Ee);
      const z = ne.get(T), O = f.state.lights, ae = f.state.shadowsArray, _e = O.state.version, we = V.getParameters(T, O.state, ae, U, k), xe = V.getProgramCacheKey(we);
      let Oe = z.programs;
      z.environment = T.isMeshStandardMaterial ? U.environment : null, z.fog = U.fog, z.envMap = (T.isMeshStandardMaterial ? ze : Ve).get(T.envMap || z.environment), z.envMapRotation = z.environment !== null && T.envMap === null ? U.environmentRotation : T.envMapRotation, Oe === void 0 && (T.addEventListener("dispose", J), Oe = /* @__PURE__ */ new Map(), z.programs = Oe);
      let ke = Oe.get(xe);
      if (ke !== void 0) {
        if (z.currentProgram === ke && z.lightsStateVersion === _e)
          return eu(T, we), ke;
      } else
        we.uniforms = V.getUniforms(T), T.onBeforeCompile(we, y), ke = V.acquireProgram(we, xe), Oe.set(xe, ke), z.uniforms = we.uniforms;
      const Ie = z.uniforms;
      return (!T.isShaderMaterial && !T.isRawShaderMaterial || T.clipping === !0) && (Ie.clippingPlanes = ce.uniform), eu(T, we), z.needsLights = Ig(T), z.lightsStateVersion = _e, z.needsLights && (Ie.ambientLightColor.value = O.state.ambient, Ie.lightProbe.value = O.state.probe, Ie.directionalLights.value = O.state.directional, Ie.directionalLightShadows.value = O.state.directionalShadow, Ie.spotLights.value = O.state.spot, Ie.spotLightShadows.value = O.state.spotShadow, Ie.rectAreaLights.value = O.state.rectArea, Ie.ltc_1.value = O.state.rectAreaLTC1, Ie.ltc_2.value = O.state.rectAreaLTC2, Ie.pointLights.value = O.state.point, Ie.pointLightShadows.value = O.state.pointShadow, Ie.hemisphereLights.value = O.state.hemi, Ie.directionalShadowMap.value = O.state.directionalShadowMap, Ie.directionalShadowMatrix.value = O.state.directionalShadowMatrix, Ie.spotShadowMap.value = O.state.spotShadowMap, Ie.spotLightMatrix.value = O.state.spotLightMatrix, Ie.spotLightMap.value = O.state.spotLightMap, Ie.pointShadowMap.value = O.state.pointShadowMap, Ie.pointShadowMatrix.value = O.state.pointShadowMatrix), z.currentProgram = ke, z.uniformsList = null, ke;
    }
    function Qd(T) {
      if (T.uniformsList === null) {
        const U = T.currentProgram.getUniforms();
        T.uniformsList = Xo.seqWithValue(U.seq, T.uniforms);
      }
      return T.uniformsList;
    }
    function eu(T, U) {
      const k = ne.get(T);
      k.outputColorSpace = U.outputColorSpace, k.batching = U.batching, k.batchingColor = U.batchingColor, k.instancing = U.instancing, k.instancingColor = U.instancingColor, k.instancingMorph = U.instancingMorph, k.skinning = U.skinning, k.morphTargets = U.morphTargets, k.morphNormals = U.morphNormals, k.morphColors = U.morphColors, k.morphTargetsCount = U.morphTargetsCount, k.numClippingPlanes = U.numClippingPlanes, k.numIntersection = U.numClipIntersection, k.vertexAlphas = U.vertexAlphas, k.vertexTangents = U.vertexTangents, k.toneMapping = U.toneMapping;
    }
    function Pg(T, U, k, z, O) {
      U.isScene !== !0 && (U = Ee), ue.resetTextureUnits();
      const ae = U.fog, _e = z.isMeshStandardMaterial ? U.environment : null, we = P === null ? y.outputColorSpace : P.isXRRenderTarget === !0 ? P.texture.colorSpace : On, xe = (z.isMeshStandardMaterial ? ze : Ve).get(z.envMap || _e), Oe = z.vertexColors === !0 && !!k.attributes.color && k.attributes.color.itemSize === 4, ke = !!k.attributes.tangent && (!!z.normalMap || z.anisotropy > 0), Ie = !!k.morphAttributes.position, Ke = !!k.morphAttributes.normal, pt = !!k.morphAttributes.color;
      let At = mn;
      z.toneMapped && (P === null || P.isXRRenderTarget === !0) && (At = y.toneMapping);
      const xt = k.morphAttributes.position || k.morphAttributes.normal || k.morphAttributes.color, gt = xt !== void 0 ? xt.length : 0, De = ne.get(z), St = f.state.lights;
      if (nt === !0 && (Y === !0 || T !== w)) {
        const ti = T === w && z.id === E;
        ce.setState(z, T, ti);
      }
      let rt = !1;
      z.version === De.__version ? (De.needsLights && De.lightsStateVersion !== St.state.version || De.outputColorSpace !== we || O.isBatchedMesh && De.batching === !1 || !O.isBatchedMesh && De.batching === !0 || O.isBatchedMesh && De.batchingColor === !0 && O.colorTexture === null || O.isBatchedMesh && De.batchingColor === !1 && O.colorTexture !== null || O.isInstancedMesh && De.instancing === !1 || !O.isInstancedMesh && De.instancing === !0 || O.isSkinnedMesh && De.skinning === !1 || !O.isSkinnedMesh && De.skinning === !0 || O.isInstancedMesh && De.instancingColor === !0 && O.instanceColor === null || O.isInstancedMesh && De.instancingColor === !1 && O.instanceColor !== null || O.isInstancedMesh && De.instancingMorph === !0 && O.morphTexture === null || O.isInstancedMesh && De.instancingMorph === !1 && O.morphTexture !== null || De.envMap !== xe || z.fog === !0 && De.fog !== ae || De.numClippingPlanes !== void 0 && (De.numClippingPlanes !== ce.numPlanes || De.numIntersection !== ce.numIntersection) || De.vertexAlphas !== Oe || De.vertexTangents !== ke || De.morphTargets !== Ie || De.morphNormals !== Ke || De.morphColors !== pt || De.toneMapping !== At || De.morphTargetsCount !== gt) && (rt = !0) : (rt = !0, De.__version = z.version);
      let _i = De.currentProgram;
      rt === !0 && (_i = Ra(z, U, O));
      let Rs = !1, yi = !1, Tr = !1;
      const Mt = _i.getUniforms(), Ri = De.uniforms;
      if (j.useProgram(_i.program) && (Rs = !0, yi = !0, Tr = !0), z.id !== E && (E = z.id, yi = !0), Rs || w !== T) {
        j.buffers.depth.getReversed() && T.reversedDepth !== !0 && (T._reversedDepth = !0, T.updateProjectionMatrix()), Mt.setValue(I, "projectionMatrix", T.projectionMatrix), Mt.setValue(I, "viewMatrix", T.matrixWorldInverse);
        const ci = Mt.map.cameraPosition;
        ci !== void 0 && ci.setValue(I, be.setFromMatrixPosition(T.matrixWorld)), $.logarithmicDepthBuffer && Mt.setValue(
          I,
          "logDepthBufFC",
          2 / (Math.log(T.far + 1) / Math.LN2)
        ), (z.isMeshPhongMaterial || z.isMeshToonMaterial || z.isMeshLambertMaterial || z.isMeshBasicMaterial || z.isMeshStandardMaterial || z.isShaderMaterial) && Mt.setValue(I, "isOrthographic", T.isOrthographicCamera === !0), w !== T && (w = T, yi = !0, Tr = !0);
      }
      if (O.isSkinnedMesh) {
        Mt.setOptional(I, O, "bindMatrix"), Mt.setOptional(I, O, "bindMatrixInverse");
        const ti = O.skeleton;
        ti && (ti.boneTexture === null && ti.computeBoneTexture(), Mt.setValue(I, "boneTexture", ti.boneTexture, ue));
      }
      O.isBatchedMesh && (Mt.setOptional(I, O, "batchingTexture"), Mt.setValue(I, "batchingTexture", O._matricesTexture, ue), Mt.setOptional(I, O, "batchingIdTexture"), Mt.setValue(I, "batchingIdTexture", O._indirectTexture, ue), Mt.setOptional(I, O, "batchingColorTexture"), O._colorsTexture !== null && Mt.setValue(I, "batchingColorTexture", O._colorsTexture, ue));
      const Pi = k.morphAttributes;
      if ((Pi.position !== void 0 || Pi.normal !== void 0 || Pi.color !== void 0) && se.update(O, k, _i), (yi || De.receiveShadow !== O.receiveShadow) && (De.receiveShadow = O.receiveShadow, Mt.setValue(I, "receiveShadow", O.receiveShadow)), z.isMeshGouraudMaterial && z.envMap !== null && (Ri.envMap.value = xe, Ri.flipEnvMap.value = xe.isCubeTexture && xe.isRenderTargetTexture === !1 ? -1 : 1), z.isMeshStandardMaterial && z.envMap === null && U.environment !== null && (Ri.envMapIntensity.value = U.environmentIntensity), yi && (Mt.setValue(I, "toneMappingExposure", y.toneMappingExposure), De.needsLights && Lg(Ri, Tr), ae && z.fog === !0 && Q.refreshFogUniforms(Ri, ae), Q.refreshMaterialUniforms(Ri, z, G, ie, f.state.transmissionRenderTarget[T.id]), Xo.upload(I, Qd(De), Ri, ue)), z.isShaderMaterial && z.uniformsNeedUpdate === !0 && (Xo.upload(I, Qd(De), Ri, ue), z.uniformsNeedUpdate = !1), z.isSpriteMaterial && Mt.setValue(I, "center", O.center), Mt.setValue(I, "modelViewMatrix", O.modelViewMatrix), Mt.setValue(I, "normalMatrix", O.normalMatrix), Mt.setValue(I, "modelMatrix", O.matrixWorld), z.isShaderMaterial || z.isRawShaderMaterial) {
        const ti = z.uniformsGroups;
        for (let ci = 0, vc = ti.length; ci < vc; ci++) {
          const Xn = ti[ci];
          qe.update(Xn, _i), qe.bind(Xn, _i);
        }
      }
      return _i;
    }
    function Lg(T, U) {
      T.ambientLightColor.needsUpdate = U, T.lightProbe.needsUpdate = U, T.directionalLights.needsUpdate = U, T.directionalLightShadows.needsUpdate = U, T.pointLights.needsUpdate = U, T.pointLightShadows.needsUpdate = U, T.spotLights.needsUpdate = U, T.spotLightShadows.needsUpdate = U, T.rectAreaLights.needsUpdate = U, T.hemisphereLights.needsUpdate = U;
    }
    function Ig(T) {
      return T.isMeshLambertMaterial || T.isMeshToonMaterial || T.isMeshPhongMaterial || T.isMeshStandardMaterial || T.isShadowMaterial || T.isShaderMaterial && T.lights === !0;
    }
    this.getActiveCubeFace = function() {
      return S;
    }, this.getActiveMipmapLevel = function() {
      return C;
    }, this.getRenderTarget = function() {
      return P;
    }, this.setRenderTargetTextures = function(T, U, k) {
      const z = ne.get(T);
      z.__autoAllocateDepthBuffer = T.resolveDepthBuffer === !1, z.__autoAllocateDepthBuffer === !1 && (z.__useRenderToTexture = !1), ne.get(T.texture).__webglTexture = U, ne.get(T.depthTexture).__webglTexture = z.__autoAllocateDepthBuffer ? void 0 : k, z.__hasExternalTextures = !0;
    }, this.setRenderTargetFramebuffer = function(T, U) {
      const k = ne.get(T);
      k.__webglFramebuffer = U, k.__useDefaultFramebuffer = U === void 0;
    };
    const Dg = I.createFramebuffer();
    this.setRenderTarget = function(T, U = 0, k = 0) {
      P = T, S = U, C = k;
      let z = !0, O = null, ae = !1, _e = !1;
      if (T) {
        const xe = ne.get(T);
        if (xe.__useDefaultFramebuffer !== void 0)
          j.bindFramebuffer(I.FRAMEBUFFER, null), z = !1;
        else if (xe.__webglFramebuffer === void 0)
          ue.setupRenderTarget(T);
        else if (xe.__hasExternalTextures)
          ue.rebindTextures(T, ne.get(T.texture).__webglTexture, ne.get(T.depthTexture).__webglTexture);
        else if (T.depthBuffer) {
          const Ie = T.depthTexture;
          if (xe.__boundDepthTexture !== Ie) {
            if (Ie !== null && ne.has(Ie) && (T.width !== Ie.image.width || T.height !== Ie.image.height))
              throw new Error("WebGLRenderTarget: Attached DepthTexture is initialized to the incorrect size.");
            ue.setupDepthRenderbuffer(T);
          }
        }
        const Oe = T.texture;
        (Oe.isData3DTexture || Oe.isDataArrayTexture || Oe.isCompressedArrayTexture) && (_e = !0);
        const ke = ne.get(T).__webglFramebuffer;
        T.isWebGLCubeRenderTarget ? (Array.isArray(ke[U]) ? O = ke[U][k] : O = ke[U], ae = !0) : T.samples > 0 && ue.useMultisampledRTT(T) === !1 ? O = ne.get(T).__webglMultisampledFramebuffer : Array.isArray(ke) ? O = ke[k] : O = ke, L.copy(T.viewport), N.copy(T.scissor), B = T.scissorTest;
      } else
        L.copy(Se).multiplyScalar(G).floor(), N.copy(We).multiplyScalar(G).floor(), B = Qe;
      if (k !== 0 && (O = Dg), j.bindFramebuffer(I.FRAMEBUFFER, O) && z && j.drawBuffers(T, O), j.viewport(L), j.scissor(N), j.setScissorTest(B), ae) {
        const xe = ne.get(T.texture);
        I.framebufferTexture2D(I.FRAMEBUFFER, I.COLOR_ATTACHMENT0, I.TEXTURE_CUBE_MAP_POSITIVE_X + U, xe.__webglTexture, k);
      } else if (_e) {
        const xe = U;
        for (let Oe = 0; Oe < T.textures.length; Oe++) {
          const ke = ne.get(T.textures[Oe]);
          I.framebufferTextureLayer(I.FRAMEBUFFER, I.COLOR_ATTACHMENT0 + Oe, ke.__webglTexture, k, xe);
        }
      } else if (T !== null && k !== 0) {
        const xe = ne.get(T.texture);
        I.framebufferTexture2D(I.FRAMEBUFFER, I.COLOR_ATTACHMENT0, I.TEXTURE_2D, xe.__webglTexture, k);
      }
      E = -1;
    }, this.readRenderTargetPixels = function(T, U, k, z, O, ae, _e, we = 0) {
      if (!(T && T.isWebGLRenderTarget)) {
        console.error("THREE.WebGLRenderer.readRenderTargetPixels: renderTarget is not THREE.WebGLRenderTarget.");
        return;
      }
      let xe = ne.get(T).__webglFramebuffer;
      if (T.isWebGLCubeRenderTarget && _e !== void 0 && (xe = xe[_e]), xe) {
        j.bindFramebuffer(I.FRAMEBUFFER, xe);
        try {
          const Oe = T.textures[we], ke = Oe.format, Ie = Oe.type;
          if (!$.textureFormatReadable(ke)) {
            console.error("THREE.WebGLRenderer.readRenderTargetPixels: renderTarget is not in RGBA or implementation defined format.");
            return;
          }
          if (!$.textureTypeReadable(Ie)) {
            console.error("THREE.WebGLRenderer.readRenderTargetPixels: renderTarget is not in UnsignedByteType or implementation defined type.");
            return;
          }
          U >= 0 && U <= T.width - z && k >= 0 && k <= T.height - O && (T.textures.length > 1 && I.readBuffer(I.COLOR_ATTACHMENT0 + we), I.readPixels(U, k, z, O, Pe.convert(ke), Pe.convert(Ie), ae));
        } finally {
          const Oe = P !== null ? ne.get(P).__webglFramebuffer : null;
          j.bindFramebuffer(I.FRAMEBUFFER, Oe);
        }
      }
    }, this.readRenderTargetPixelsAsync = async function(T, U, k, z, O, ae, _e, we = 0) {
      if (!(T && T.isWebGLRenderTarget))
        throw new Error("THREE.WebGLRenderer.readRenderTargetPixels: renderTarget is not THREE.WebGLRenderTarget.");
      let xe = ne.get(T).__webglFramebuffer;
      if (T.isWebGLCubeRenderTarget && _e !== void 0 && (xe = xe[_e]), xe)
        if (U >= 0 && U <= T.width - z && k >= 0 && k <= T.height - O) {
          j.bindFramebuffer(I.FRAMEBUFFER, xe);
          const Oe = T.textures[we], ke = Oe.format, Ie = Oe.type;
          if (!$.textureFormatReadable(ke))
            throw new Error("THREE.WebGLRenderer.readRenderTargetPixelsAsync: renderTarget is not in RGBA or implementation defined format.");
          if (!$.textureTypeReadable(Ie))
            throw new Error("THREE.WebGLRenderer.readRenderTargetPixelsAsync: renderTarget is not in UnsignedByteType or implementation defined type.");
          const Ke = I.createBuffer();
          I.bindBuffer(I.PIXEL_PACK_BUFFER, Ke), I.bufferData(I.PIXEL_PACK_BUFFER, ae.byteLength, I.STREAM_READ), T.textures.length > 1 && I.readBuffer(I.COLOR_ATTACHMENT0 + we), I.readPixels(U, k, z, O, Pe.convert(ke), Pe.convert(Ie), 0);
          const pt = P !== null ? ne.get(P).__webglFramebuffer : null;
          j.bindFramebuffer(I.FRAMEBUFFER, pt);
          const At = I.fenceSync(I.SYNC_GPU_COMMANDS_COMPLETE, 0);
          return I.flush(), await D_(I, At, 4), I.bindBuffer(I.PIXEL_PACK_BUFFER, Ke), I.getBufferSubData(I.PIXEL_PACK_BUFFER, 0, ae), I.deleteBuffer(Ke), I.deleteSync(At), ae;
        } else
          throw new Error("THREE.WebGLRenderer.readRenderTargetPixelsAsync: requested read bounds are out of range.");
    }, this.copyFramebufferToTexture = function(T, U = null, k = 0) {
      const z = Math.pow(2, -k), O = Math.floor(T.image.width * z), ae = Math.floor(T.image.height * z), _e = U !== null ? U.x : 0, we = U !== null ? U.y : 0;
      ue.setTexture2D(T, 0), I.copyTexSubImage2D(I.TEXTURE_2D, k, 0, 0, _e, we, O, ae), j.unbindTexture();
    };
    const Ng = I.createFramebuffer(), Ug = I.createFramebuffer();
    this.copyTextureToTexture = function(T, U, k = null, z = null, O = 0, ae = null) {
      ae === null && (O !== 0 ? (pa("WebGLRenderer: copyTextureToTexture function signature has changed to support src and dst mipmap levels."), ae = O, O = 0) : ae = 0);
      let _e, we, xe, Oe, ke, Ie, Ke, pt, At;
      const xt = T.isCompressedTexture ? T.mipmaps[ae] : T.image;
      if (k !== null)
        _e = k.max.x - k.min.x, we = k.max.y - k.min.y, xe = k.isBox3 ? k.max.z - k.min.z : 1, Oe = k.min.x, ke = k.min.y, Ie = k.isBox3 ? k.min.z : 0;
      else {
        const Pi = Math.pow(2, -O);
        _e = Math.floor(xt.width * Pi), we = Math.floor(xt.height * Pi), T.isDataArrayTexture ? xe = xt.depth : T.isData3DTexture ? xe = Math.floor(xt.depth * Pi) : xe = 1, Oe = 0, ke = 0, Ie = 0;
      }
      z !== null ? (Ke = z.x, pt = z.y, At = z.z) : (Ke = 0, pt = 0, At = 0);
      const gt = Pe.convert(U.format), De = Pe.convert(U.type);
      let St;
      U.isData3DTexture ? (ue.setTexture3D(U, 0), St = I.TEXTURE_3D) : U.isDataArrayTexture || U.isCompressedArrayTexture ? (ue.setTexture2DArray(U, 0), St = I.TEXTURE_2D_ARRAY) : (ue.setTexture2D(U, 0), St = I.TEXTURE_2D), I.pixelStorei(I.UNPACK_FLIP_Y_WEBGL, U.flipY), I.pixelStorei(I.UNPACK_PREMULTIPLY_ALPHA_WEBGL, U.premultiplyAlpha), I.pixelStorei(I.UNPACK_ALIGNMENT, U.unpackAlignment);
      const rt = I.getParameter(I.UNPACK_ROW_LENGTH), _i = I.getParameter(I.UNPACK_IMAGE_HEIGHT), Rs = I.getParameter(I.UNPACK_SKIP_PIXELS), yi = I.getParameter(I.UNPACK_SKIP_ROWS), Tr = I.getParameter(I.UNPACK_SKIP_IMAGES);
      I.pixelStorei(I.UNPACK_ROW_LENGTH, xt.width), I.pixelStorei(I.UNPACK_IMAGE_HEIGHT, xt.height), I.pixelStorei(I.UNPACK_SKIP_PIXELS, Oe), I.pixelStorei(I.UNPACK_SKIP_ROWS, ke), I.pixelStorei(I.UNPACK_SKIP_IMAGES, Ie);
      const Mt = T.isDataArrayTexture || T.isData3DTexture, Ri = U.isDataArrayTexture || U.isData3DTexture;
      if (T.isDepthTexture) {
        const Pi = ne.get(T), ti = ne.get(U), ci = ne.get(Pi.__renderTarget), vc = ne.get(ti.__renderTarget);
        j.bindFramebuffer(I.READ_FRAMEBUFFER, ci.__webglFramebuffer), j.bindFramebuffer(I.DRAW_FRAMEBUFFER, vc.__webglFramebuffer);
        for (let Xn = 0; Xn < xe; Xn++)
          Mt && (I.framebufferTextureLayer(I.READ_FRAMEBUFFER, I.COLOR_ATTACHMENT0, ne.get(T).__webglTexture, O, Ie + Xn), I.framebufferTextureLayer(I.DRAW_FRAMEBUFFER, I.COLOR_ATTACHMENT0, ne.get(U).__webglTexture, ae, At + Xn)), I.blitFramebuffer(Oe, ke, _e, we, Ke, pt, _e, we, I.DEPTH_BUFFER_BIT, I.NEAREST);
        j.bindFramebuffer(I.READ_FRAMEBUFFER, null), j.bindFramebuffer(I.DRAW_FRAMEBUFFER, null);
      } else if (O !== 0 || T.isRenderTargetTexture || ne.has(T)) {
        const Pi = ne.get(T), ti = ne.get(U);
        j.bindFramebuffer(I.READ_FRAMEBUFFER, Ng), j.bindFramebuffer(I.DRAW_FRAMEBUFFER, Ug);
        for (let ci = 0; ci < xe; ci++)
          Mt ? I.framebufferTextureLayer(I.READ_FRAMEBUFFER, I.COLOR_ATTACHMENT0, Pi.__webglTexture, O, Ie + ci) : I.framebufferTexture2D(I.READ_FRAMEBUFFER, I.COLOR_ATTACHMENT0, I.TEXTURE_2D, Pi.__webglTexture, O), Ri ? I.framebufferTextureLayer(I.DRAW_FRAMEBUFFER, I.COLOR_ATTACHMENT0, ti.__webglTexture, ae, At + ci) : I.framebufferTexture2D(I.DRAW_FRAMEBUFFER, I.COLOR_ATTACHMENT0, I.TEXTURE_2D, ti.__webglTexture, ae), O !== 0 ? I.blitFramebuffer(Oe, ke, _e, we, Ke, pt, _e, we, I.COLOR_BUFFER_BIT, I.NEAREST) : Ri ? I.copyTexSubImage3D(St, ae, Ke, pt, At + ci, Oe, ke, _e, we) : I.copyTexSubImage2D(St, ae, Ke, pt, Oe, ke, _e, we);
        j.bindFramebuffer(I.READ_FRAMEBUFFER, null), j.bindFramebuffer(I.DRAW_FRAMEBUFFER, null);
      } else
        Ri ? T.isDataTexture || T.isData3DTexture ? I.texSubImage3D(St, ae, Ke, pt, At, _e, we, xe, gt, De, xt.data) : U.isCompressedArrayTexture ? I.compressedTexSubImage3D(St, ae, Ke, pt, At, _e, we, xe, gt, xt.data) : I.texSubImage3D(St, ae, Ke, pt, At, _e, we, xe, gt, De, xt) : T.isDataTexture ? I.texSubImage2D(I.TEXTURE_2D, ae, Ke, pt, _e, we, gt, De, xt.data) : T.isCompressedTexture ? I.compressedTexSubImage2D(I.TEXTURE_2D, ae, Ke, pt, xt.width, xt.height, gt, xt.data) : I.texSubImage2D(I.TEXTURE_2D, ae, Ke, pt, _e, we, gt, De, xt);
      I.pixelStorei(I.UNPACK_ROW_LENGTH, rt), I.pixelStorei(I.UNPACK_IMAGE_HEIGHT, _i), I.pixelStorei(I.UNPACK_SKIP_PIXELS, Rs), I.pixelStorei(I.UNPACK_SKIP_ROWS, yi), I.pixelStorei(I.UNPACK_SKIP_IMAGES, Tr), ae === 0 && U.generateMipmaps && I.generateMipmap(St), j.unbindTexture();
    }, this.initRenderTarget = function(T) {
      ne.get(T).__webglFramebuffer === void 0 && ue.setupRenderTarget(T);
    }, this.initTexture = function(T) {
      T.isCubeTexture ? ue.setTextureCube(T, 0) : T.isData3DTexture ? ue.setTexture3D(T, 0) : T.isDataArrayTexture || T.isCompressedArrayTexture ? ue.setTexture2DArray(T, 0) : ue.setTexture2D(T, 0), j.unbindTexture();
    }, this.resetState = function() {
      S = 0, C = 0, P = null, j.reset(), ge.reset();
    }, typeof __THREE_DEVTOOLS__ < "u" && __THREE_DEVTOOLS__.dispatchEvent(new CustomEvent("observe", { detail: this }));
  }
  /**
   * Defines the coordinate system of the renderer.
   *
   * In `WebGLRenderer`, the value is always `WebGLCoordinateSystem`.
   *
   * @type {WebGLCoordinateSystem|WebGPUCoordinateSystem}
   * @default WebGLCoordinateSystem
   * @readonly
   */
  get coordinateSystem() {
    return wi;
  }
  /**
   * Defines the output color space of the renderer.
   *
   * @type {SRGBColorSpace|LinearSRGBColorSpace}
   * @default SRGBColorSpace
   */
  get outputColorSpace() {
    return this._outputColorSpace;
  }
  set outputColorSpace(e) {
    this._outputColorSpace = e;
    const t = this.getContext();
    t.drawingBufferColorSpace = et._getDrawingBufferColorSpace(e), t.unpackColorSpace = et._getUnpackColorSpace();
  }
}
var GM = /* @__PURE__ */ Object.freeze({
  __proto__: null,
  ACESFilmicToneMapping: Xf,
  AddEquation: Ln,
  AddOperation: Hf,
  AdditiveAnimationBlendMode: ad,
  AdditiveBlending: Lh,
  AgXToneMapping: Zf,
  AlphaFormat: td,
  AlwaysCompare: om,
  AlwaysDepth: jo,
  AlwaysStencilFunc: ca,
  AmbientLight: Dd,
  AnimationAction: ig,
  AnimationClip: yr,
  AnimationLoader: r0,
  AnimationMixer: ng,
  AnimationObjectGroup: I0,
  AnimationUtils: t0,
  ArcCurve: Mm,
  ArrayCamera: Qm,
  ArrowHelper: iv,
  AttachedBindMode: Nh,
  Audio: eg,
  AudioAnalyser: S0,
  AudioContext: Nd,
  AudioListener: v0,
  AudioLoader: g0,
  AxesHelper: nv,
  BackSide: zt,
  BasicDepthPacking: Kf,
  BasicShadowMap: Fg,
  BatchedMesh: vm,
  Bone: ud,
  BooleanKeyframeTrack: As,
  Box2: H0,
  Box3: Tt,
  Box3Helper: ev,
  BoxGeometry: Es,
  BoxHelper: Q0,
  BufferAttribute: it,
  BufferGeometry: Ue,
  BufferGeometryLoader: Jm,
  ByteType: Kh,
  Cache: Qi,
  Camera: Yl,
  CameraHelper: J0,
  CanvasTexture: fd,
  CapsuleGeometry: nc,
  CatmullRomCurve3: wm,
  CineonToneMapping: Wf,
  CircleGeometry: sc,
  ClampToEdgeWrapping: fi,
  Clock: Ud,
  Color: oe,
  ColorKeyframeTrack: Rd,
  ColorManagement: et,
  CompressedArrayTexture: My,
  CompressedCubeTexture: wy,
  CompressedTexture: ic,
  CompressedTextureLoader: a0,
  ConeGeometry: wr,
  ConstantAlphaFactor: Bf,
  ConstantColorFactor: Of,
  Controls: zd,
  CubeCamera: pm,
  CubeReflectionMapping: _n,
  CubeRefractionMapping: Un,
  CubeTexture: Sa,
  CubeTextureLoader: o0,
  CubeUVReflectionMapping: xr,
  CubicBezierCurve: yd,
  CubicBezierCurve3: Em,
  CubicInterpolant: Vm,
  CullFaceBack: Ph,
  CullFaceFront: xf,
  CullFaceFrontBack: Og,
  CullFaceNone: vf,
  Curve: Vi,
  CurvePath: Am,
  CustomBlending: Sf,
  CustomToneMapping: qf,
  CylinderGeometry: Mr,
  Cylindrical: z0,
  Data3DTexture: Xl,
  DataArrayTexture: Wl,
  DataTexture: tn,
  DataTextureLoader: l0,
  DataUtils: Y_,
  DecrementStencilOp: $g,
  DecrementWrapStencilOp: Go,
  DefaultLoadingManager: Xm,
  DepthFormat: dr,
  DepthStencilFormat: ur,
  DepthTexture: md,
  DetachedBindMode: jf,
  DirectionalLight: Id,
  DirectionalLightHelper: K0,
  DiscreteInterpolant: Gm,
  DodecahedronGeometry: rc,
  DoubleSide: ri,
  DstAlphaFactor: Lf,
  DstColorFactor: Df,
  DynamicCopyUsage: h_,
  DynamicDrawUsage: s_,
  DynamicReadUsage: o_,
  EdgesGeometry: Sm,
  EllipseCurve: ac,
  EqualCompare: nm,
  EqualDepth: Ko,
  EqualStencilFunc: e_,
  EquirectangularReflectionMapping: na,
  EquirectangularRefractionMapping: sa,
  Euler: Ai,
  EventDispatcher: sn,
  ExternalTexture: gd,
  ExtrudeGeometry: wa,
  FileLoader: vn,
  Float16BufferAttribute: ty,
  Float32BufferAttribute: ve,
  FloatType: mi,
  Fog: $l,
  FogExp2: jl,
  FramebufferTexture: Sy,
  FrontSide: Di,
  Frustum: Sr,
  FrustumArray: ec,
  GLBufferAttribute: F0,
  GLSL1: u_,
  GLSL3: Uh,
  GreaterCompare: sm,
  GreaterDepth: Qo,
  GreaterEqualCompare: am,
  GreaterEqualDepth: Jo,
  GreaterEqualStencilFunc: n_,
  GreaterStencilFunc: i_,
  GridHelper: j0,
  Group: li,
  HalfFloatType: br,
  HemisphereLight: qm,
  HemisphereLightHelper: Y0,
  IcosahedronGeometry: oc,
  ImageBitmapLoader: m0,
  ImageLoader: ya,
  ImageUtils: hm,
  IncrementStencilOp: jg,
  IncrementWrapStencilOp: Vo,
  InstancedBufferAttribute: gr,
  InstancedBufferGeometry: mc,
  InstancedInterleavedBuffer: Nl,
  InstancedMesh: ym,
  Int16BufferAttribute: Q_,
  Int32BufferAttribute: ey,
  Int8BufferAttribute: $_,
  IntType: Fl,
  InterleavedBuffer: Kl,
  InterleavedBufferAttribute: Ei,
  Interpolant: Aa,
  InterpolateDiscrete: aa,
  InterpolateLinear: Rl,
  InterpolateSmooth: zo,
  InterpolationSamplingMode: m_,
  InterpolationSamplingType: f_,
  InvertStencilOp: Kg,
  KeepStencilOp: os,
  KeyframeTrack: Ni,
  LOD: gm,
  LatheGeometry: lc,
  Layers: ql,
  LessCompare: im,
  LessDepth: $o,
  LessEqualCompare: od,
  LessEqualDepth: vs,
  LessEqualStencilFunc: t_,
  LessStencilFunc: Qg,
  Light: Gn,
  LightProbe: Km,
  Line: Fn,
  Line3: rg,
  LineBasicMaterial: It,
  LineCurve: vd,
  LineCurve3: Tm,
  LineDashedMaterial: Td,
  LineLoop: xm,
  LineSegments: ei,
  LinearFilter: Pt,
  LinearInterpolant: Cd,
  LinearMipMapLinearFilter: Hg,
  LinearMipMapNearestFilter: zg,
  LinearMipmapLinearFilter: Ji,
  LinearMipmapNearestFilter: Zr,
  LinearSRGBColorSpace: On,
  LinearToneMapping: Vf,
  LinearTransfer: la,
  Loader: gi,
  LoaderUtils: zh,
  LoadingManager: Pd,
  LoopOnce: $f,
  LoopPingPong: rd,
  LoopRepeat: sd,
  MOUSE: bt,
  Material: qt,
  MaterialLoader: fc,
  MathUtils: da,
  Matrix2: kd,
  Matrix3: He,
  Matrix4: Ne,
  MaxEquation: Tf,
  Mesh: Je,
  MeshBasicMaterial: Ht,
  MeshDepthMaterial: wd,
  MeshDistanceMaterial: Ed,
  MeshLambertMaterial: Bm,
  MeshMatcapMaterial: km,
  MeshNormalMaterial: Fm,
  MeshPhongMaterial: Um,
  MeshPhysicalMaterial: Nm,
  MeshStandardMaterial: Bn,
  MeshToonMaterial: Om,
  MinEquation: Ef,
  MirroredRepeatWrapping: ra,
  MixOperation: zf,
  MultiplyBlending: Dh,
  MultiplyOperation: xa,
  NearestFilter: Xt,
  NearestMipMapLinearFilter: kg,
  NearestMipMapNearestFilter: Bg,
  NearestMipmapLinearFilter: nr,
  NearestMipmapNearestFilter: $h,
  NeutralToneMapping: Yf,
  NeverCompare: tm,
  NeverDepth: Yo,
  NeverStencilFunc: Jg,
  NoBlending: fn,
  NoColorSpace: un,
  NoToneMapping: mn,
  NormalAnimationBlendMode: Gl,
  NormalBlending: Dn,
  NotEqualCompare: rm,
  NotEqualDepth: el,
  NotEqualStencilFunc: em,
  NumberKeyframeTrack: _a,
  Object3D: tt,
  ObjectLoader: p0,
  ObjectSpaceNormalMap: Qf,
  OctahedronGeometry: Ea,
  OneFactor: Cf,
  OneMinusConstantAlphaFactor: kf,
  OneMinusConstantColorFactor: Ff,
  OneMinusDstAlphaFactor: If,
  OneMinusDstColorFactor: Nf,
  OneMinusSrcAlphaFactor: Zo,
  OneMinusSrcColorFactor: Pf,
  OrthographicCamera: kn,
  PCFShadowMap: jh,
  PCFSoftShadowMap: bf,
  PMREMGenerator: Wh,
  Path: Dl,
  PerspectiveCamera: kt,
  Plane: $i,
  PlaneGeometry: Vn,
  PlaneHelper: tv,
  PointLight: Ym,
  PointLightHelper: q0,
  Points: pd,
  PointsMaterial: tc,
  PolarGridHelper: $0,
  PolyhedronGeometry: Hn,
  PositionalAudio: b0,
  PropertyBinding: st,
  PropertyMixer: tg,
  QuadraticBezierCurve: xd,
  QuadraticBezierCurve3: bd,
  Quaternion: ot,
  QuaternionKeyframeTrack: Ss,
  QuaternionLinearInterpolant: Wm,
  RED_GREEN_RGTC2_Format: Al,
  RED_RGTC1_Format: El,
  REVISION: Ul,
  RGBADepthPacking: Jf,
  RGBAFormat: oi,
  RGBAIntegerFormat: Vl,
  RGBA_ASTC_10x10_Format: vl,
  RGBA_ASTC_10x5_Format: gl,
  RGBA_ASTC_10x6_Format: _l,
  RGBA_ASTC_10x8_Format: yl,
  RGBA_ASTC_12x10_Format: xl,
  RGBA_ASTC_12x12_Format: bl,
  RGBA_ASTC_4x4_Format: ll,
  RGBA_ASTC_5x4_Format: cl,
  RGBA_ASTC_5x5_Format: hl,
  RGBA_ASTC_6x5_Format: dl,
  RGBA_ASTC_6x6_Format: ul,
  RGBA_ASTC_8x5_Format: pl,
  RGBA_ASTC_8x6_Format: fl,
  RGBA_ASTC_8x8_Format: ml,
  RGBA_BPTC_Format: Sl,
  RGBA_ETC2_EAC_Format: ol,
  RGBA_PVRTC_2BPPV1_Format: sl,
  RGBA_PVRTC_4BPPV1_Format: nl,
  RGBA_S3TC_DXT1_Format: jr,
  RGBA_S3TC_DXT3_Format: $r,
  RGBA_S3TC_DXT5_Format: Kr,
  RGBDepthPacking: qg,
  RGBFormat: id,
  RGBIntegerFormat: Vg,
  RGB_BPTC_SIGNED_Format: Ml,
  RGB_BPTC_UNSIGNED_Format: wl,
  RGB_ETC1_Format: rl,
  RGB_ETC2_Format: al,
  RGB_PVRTC_2BPPV1_Format: il,
  RGB_PVRTC_4BPPV1_Format: tl,
  RGB_S3TC_DXT1_Format: Yr,
  RGDepthPacking: Zg,
  RGFormat: nd,
  RGIntegerFormat: Hl,
  RawShaderMaterial: Dm,
  Ray: ws,
  Raycaster: sg,
  RectAreaLight: jm,
  RedFormat: zl,
  RedIntegerFormat: ba,
  ReinhardToneMapping: Gf,
  RenderTarget: cd,
  RenderTarget3D: N0,
  RepeatWrapping: xs,
  ReplaceStencilOp: Ho,
  ReverseSubtractEquation: wf,
  RingGeometry: cc,
  SIGNED_RED_GREEN_RGTC2_Format: Cl,
  SIGNED_RED_RGTC1_Format: Tl,
  SRGBColorSpace: Qt,
  SRGBTransfer: ut,
  Scene: Ma,
  ShaderChunk: Ze,
  ShaderLib: si,
  ShaderMaterial: Ci,
  ShadowMaterial: Im,
  Shape: Nn,
  ShapeGeometry: Ta,
  ShapePath: og,
  ShapeUtils: zi,
  ShortType: Jh,
  Skeleton: Ql,
  SkeletonHelper: X0,
  SkinnedMesh: _m,
  Source: In,
  Sphere: Lt,
  SphereGeometry: Ts,
  Spherical: Vh,
  SphericalHarmonics3: $m,
  SplineCurve: Sd,
  SpotLight: Zm,
  SpotLightHelper: W0,
  Sprite: Qr,
  SpriteMaterial: Jl,
  SrcAlphaFactor: qo,
  SrcAlphaSaturateFactor: Uf,
  SrcColorFactor: Rf,
  StaticCopyUsage: c_,
  StaticDrawUsage: ha,
  StaticReadUsage: a_,
  StereoCamera: _0,
  StreamCopyUsage: d_,
  StreamDrawUsage: r_,
  StreamReadUsage: l_,
  StringKeyframeTrack: Cs,
  SubtractEquation: Mf,
  SubtractiveBlending: Ih,
  TOUCH: hs,
  TangentSpaceNormalMap: zn,
  TetrahedronGeometry: hc,
  Texture: Et,
  TextureLoader: c0,
  TextureUtils: lv,
  Timer: B0,
  TimestampQuery: p_,
  TorusGeometry: dc,
  TorusKnotGeometry: uc,
  Triangle: pi,
  TriangleFanDrawMode: Xg,
  TriangleStripDrawMode: Wg,
  TrianglesDrawMode: Gg,
  TubeGeometry: pc,
  UVMapping: Ol,
  Uint16BufferAttribute: hd,
  Uint32BufferAttribute: dd,
  Uint8BufferAttribute: K_,
  Uint8ClampedBufferAttribute: J_,
  Uniform: Bd,
  UniformsGroup: O0,
  UniformsLib: pe,
  UniformsUtils: Zl,
  UnsignedByteType: Hi,
  UnsignedInt101111Type: ed,
  UnsignedInt248Type: hr,
  UnsignedInt5999Type: Qh,
  UnsignedIntType: yn,
  UnsignedShort4444Type: Bl,
  UnsignedShort5551Type: kl,
  UnsignedShortType: cr,
  VSMShadowMap: Yi,
  Vector2: H,
  Vector3: b,
  Vector4: Ye,
  VectorKeyframeTrack: Ms,
  VideoFrameTexture: by,
  VideoTexture: bm,
  WebGL3DRenderTarget: B_,
  WebGLArrayRenderTarget: F_,
  WebGLCoordinateSystem: wi,
  WebGLCubeRenderTarget: fm,
  WebGLRenderTarget: nn,
  WebGLRenderer: fg,
  WebGLUtils: pg,
  WebGPUCoordinateSystem: pr,
  WebXRController: Wo,
  WireframeGeometry: Md,
  WrapAroundEnding: oa,
  ZeroCurvatureEnding: ds,
  ZeroFactor: Af,
  ZeroSlopeEnding: us,
  ZeroStencilOp: Yg,
  createCanvasElement: cm
});
const Lp = new Tt(), So = new b();
let Vd = class extends mc {
  /**
   * Constructs a new line segments geometry.
   */
  constructor() {
    super(), this.isLineSegmentsGeometry = !0, this.type = "LineSegmentsGeometry";
    const e = [-1, 2, 0, 1, 2, 0, -1, 1, 0, 1, 1, 0, -1, 0, 0, 1, 0, 0, -1, -1, 0, 1, -1, 0], t = [-1, 2, 1, 2, -1, 1, 1, 1, -1, -1, 1, -1, -1, -2, 1, -2], i = [0, 2, 1, 2, 3, 1, 2, 4, 3, 4, 5, 3, 4, 6, 5, 6, 7, 5];
    this.setIndex(i), this.setAttribute("position", new ve(e, 3)), this.setAttribute("uv", new ve(t, 2));
  }
  /**
   * Applies the given 4x4 transformation matrix to the geometry.
   *
   * @param {Matrix4} matrix - The matrix to apply.
   * @return {LineSegmentsGeometry} A reference to this instance.
   */
  applyMatrix4(e) {
    const t = this.attributes.instanceStart, i = this.attributes.instanceEnd;
    return t !== void 0 && (t.applyMatrix4(e), i.applyMatrix4(e), t.needsUpdate = !0), this.boundingBox !== null && this.computeBoundingBox(), this.boundingSphere !== null && this.computeBoundingSphere(), this;
  }
  /**
   * Sets the given line positions for this geometry. The length must be a multiple of six since
   * each line segment is defined by a start end vertex in the pattern `(xyz xyz)`.
   *
   * @param {Float32Array|Array<number>} array - The position data to set.
   * @return {LineSegmentsGeometry} A reference to this geometry.
   */
  setPositions(e) {
    let t;
    e instanceof Float32Array ? t = e : Array.isArray(e) && (t = new Float32Array(e));
    const i = new Nl(t, 6, 1);
    return this.setAttribute("instanceStart", new Ei(i, 3, 0)), this.setAttribute("instanceEnd", new Ei(i, 3, 3)), this.instanceCount = this.attributes.instanceStart.count, this.computeBoundingBox(), this.computeBoundingSphere(), this;
  }
  /**
   * Sets the given line colors for this geometry. The length must be a multiple of six since
   * each line segment is defined by a start end color in the pattern `(rgb rgb)`.
   *
   * @param {Float32Array|Array<number>} array - The position data to set.
   * @return {LineSegmentsGeometry} A reference to this geometry.
   */
  setColors(e) {
    let t;
    e instanceof Float32Array ? t = e : Array.isArray(e) && (t = new Float32Array(e));
    const i = new Nl(t, 6, 1);
    return this.setAttribute("instanceColorStart", new Ei(i, 3, 0)), this.setAttribute("instanceColorEnd", new Ei(i, 3, 3)), this;
  }
  /**
   * Setups this line segments geometry from the given wireframe geometry.
   *
   * @param {WireframeGeometry} geometry - The geometry that should be used as a data source for this geometry.
   * @return {LineSegmentsGeometry} A reference to this geometry.
   */
  fromWireframeGeometry(e) {
    return this.setPositions(e.attributes.position.array), this;
  }
  /**
   * Setups this line segments geometry from the given edges geometry.
   *
   * @param {EdgesGeometry} geometry - The geometry that should be used as a data source for this geometry.
   * @return {LineSegmentsGeometry} A reference to this geometry.
   */
  fromEdgesGeometry(e) {
    return this.setPositions(e.attributes.position.array), this;
  }
  /**
   * Setups this line segments geometry from the given mesh.
   *
   * @param {Mesh} mesh - The mesh geometry that should be used as a data source for this geometry.
   * @return {LineSegmentsGeometry} A reference to this geometry.
   */
  fromMesh(e) {
    return this.fromWireframeGeometry(new Md(e.geometry)), this;
  }
  /**
   * Setups this line segments geometry from the given line segments.
   *
   * @param {LineSegments} lineSegments - The line segments that should be used as a data source for this geometry.
   * Assumes the source geometry is not using indices.
   * @return {LineSegmentsGeometry} A reference to this geometry.
   */
  fromLineSegments(e) {
    const t = e.geometry;
    return this.setPositions(t.attributes.position.array), this;
  }
  computeBoundingBox() {
    this.boundingBox === null && (this.boundingBox = new Tt());
    const e = this.attributes.instanceStart, t = this.attributes.instanceEnd;
    e !== void 0 && t !== void 0 && (this.boundingBox.setFromBufferAttribute(e), Lp.setFromBufferAttribute(t), this.boundingBox.union(Lp));
  }
  computeBoundingSphere() {
    this.boundingSphere === null && (this.boundingSphere = new Lt()), this.boundingBox === null && this.computeBoundingBox();
    const e = this.attributes.instanceStart, t = this.attributes.instanceEnd;
    if (e !== void 0 && t !== void 0) {
      const i = this.boundingSphere.center;
      this.boundingBox.getCenter(i);
      let n = 0;
      for (let s = 0, a = e.count; s < a; s++)
        So.fromBufferAttribute(e, s), n = Math.max(n, i.distanceToSquared(So)), So.fromBufferAttribute(t, s), n = Math.max(n, i.distanceToSquared(So));
      this.boundingSphere.radius = Math.sqrt(n), isNaN(this.boundingSphere.radius) && console.error("THREE.LineSegmentsGeometry.computeBoundingSphere(): Computed radius is NaN. The instanced position data is likely to have NaN values.", this);
    }
  }
  toJSON() {
  }
};
pe.line = {
  worldUnits: { value: 1 },
  linewidth: { value: 1 },
  resolution: { value: new H(1, 1) },
  dashOffset: { value: 0 },
  dashScale: { value: 1 },
  dashSize: { value: 1 },
  gapSize: { value: 1 }
  // todo FIX - maybe change to totalSize
};
si.line = {
  uniforms: Zl.merge([
    pe.common,
    pe.fog,
    pe.line
  ]),
  vertexShader: (
    /* glsl */
    `
		#include <common>
		#include <color_pars_vertex>
		#include <fog_pars_vertex>
		#include <logdepthbuf_pars_vertex>
		#include <clipping_planes_pars_vertex>

		uniform float linewidth;
		uniform vec2 resolution;

		attribute vec3 instanceStart;
		attribute vec3 instanceEnd;

		attribute vec3 instanceColorStart;
		attribute vec3 instanceColorEnd;

		#ifdef WORLD_UNITS

			varying vec4 worldPos;
			varying vec3 worldStart;
			varying vec3 worldEnd;

			#ifdef USE_DASH

				varying vec2 vUv;

			#endif

		#else

			varying vec2 vUv;

		#endif

		#ifdef USE_DASH

			uniform float dashScale;
			attribute float instanceDistanceStart;
			attribute float instanceDistanceEnd;
			varying float vLineDistance;

		#endif

		void trimSegment( const in vec4 start, inout vec4 end ) {

			// trim end segment so it terminates between the camera plane and the near plane

			// conservative estimate of the near plane
			float a = projectionMatrix[ 2 ][ 2 ]; // 3nd entry in 3th column
			float b = projectionMatrix[ 3 ][ 2 ]; // 3nd entry in 4th column
			float nearEstimate = - 0.5 * b / a;

			float alpha = ( nearEstimate - start.z ) / ( end.z - start.z );

			end.xyz = mix( start.xyz, end.xyz, alpha );

		}

		void main() {

			#ifdef USE_COLOR

				vColor.xyz = ( position.y < 0.5 ) ? instanceColorStart : instanceColorEnd;

			#endif

			#ifdef USE_DASH

				vLineDistance = ( position.y < 0.5 ) ? dashScale * instanceDistanceStart : dashScale * instanceDistanceEnd;
				vUv = uv;

			#endif

			float aspect = resolution.x / resolution.y;

			// camera space
			vec4 start = modelViewMatrix * vec4( instanceStart, 1.0 );
			vec4 end = modelViewMatrix * vec4( instanceEnd, 1.0 );

			#ifdef WORLD_UNITS

				worldStart = start.xyz;
				worldEnd = end.xyz;

			#else

				vUv = uv;

			#endif

			// special case for perspective projection, and segments that terminate either in, or behind, the camera plane
			// clearly the gpu firmware has a way of addressing this issue when projecting into ndc space
			// but we need to perform ndc-space calculations in the shader, so we must address this issue directly
			// perhaps there is a more elegant solution -- WestLangley

			bool perspective = ( projectionMatrix[ 2 ][ 3 ] == - 1.0 ); // 4th entry in the 3rd column

			if ( perspective ) {

				if ( start.z < 0.0 && end.z >= 0.0 ) {

					trimSegment( start, end );

				} else if ( end.z < 0.0 && start.z >= 0.0 ) {

					trimSegment( end, start );

				}

			}

			// clip space
			vec4 clipStart = projectionMatrix * start;
			vec4 clipEnd = projectionMatrix * end;

			// ndc space
			vec3 ndcStart = clipStart.xyz / clipStart.w;
			vec3 ndcEnd = clipEnd.xyz / clipEnd.w;

			// direction
			vec2 dir = ndcEnd.xy - ndcStart.xy;

			// account for clip-space aspect ratio
			dir.x *= aspect;
			dir = normalize( dir );

			#ifdef WORLD_UNITS

				vec3 worldDir = normalize( end.xyz - start.xyz );
				vec3 tmpFwd = normalize( mix( start.xyz, end.xyz, 0.5 ) );
				vec3 worldUp = normalize( cross( worldDir, tmpFwd ) );
				vec3 worldFwd = cross( worldDir, worldUp );
				worldPos = position.y < 0.5 ? start: end;

				// height offset
				float hw = linewidth * 0.5;
				worldPos.xyz += position.x < 0.0 ? hw * worldUp : - hw * worldUp;

				// don't extend the line if we're rendering dashes because we
				// won't be rendering the endcaps
				#ifndef USE_DASH

					// cap extension
					worldPos.xyz += position.y < 0.5 ? - hw * worldDir : hw * worldDir;

					// add width to the box
					worldPos.xyz += worldFwd * hw;

					// endcaps
					if ( position.y > 1.0 || position.y < 0.0 ) {

						worldPos.xyz -= worldFwd * 2.0 * hw;

					}

				#endif

				// project the worldpos
				vec4 clip = projectionMatrix * worldPos;

				// shift the depth of the projected points so the line
				// segments overlap neatly
				vec3 clipPose = ( position.y < 0.5 ) ? ndcStart : ndcEnd;
				clip.z = clipPose.z * clip.w;

			#else

				vec2 offset = vec2( dir.y, - dir.x );
				// undo aspect ratio adjustment
				dir.x /= aspect;
				offset.x /= aspect;

				// sign flip
				if ( position.x < 0.0 ) offset *= - 1.0;

				// endcaps
				if ( position.y < 0.0 ) {

					offset += - dir;

				} else if ( position.y > 1.0 ) {

					offset += dir;

				}

				// adjust for linewidth
				offset *= linewidth;

				// adjust for clip-space to screen-space conversion // maybe resolution should be based on viewport ...
				offset /= resolution.y;

				// select end
				vec4 clip = ( position.y < 0.5 ) ? clipStart : clipEnd;

				// back to clip space
				offset *= clip.w;

				clip.xy += offset;

			#endif

			gl_Position = clip;

			vec4 mvPosition = ( position.y < 0.5 ) ? start : end; // this is an approximation

			#include <logdepthbuf_vertex>
			#include <clipping_planes_vertex>
			#include <fog_vertex>

		}
		`
  ),
  fragmentShader: (
    /* glsl */
    `
		uniform vec3 diffuse;
		uniform float opacity;
		uniform float linewidth;

		#ifdef USE_DASH

			uniform float dashOffset;
			uniform float dashSize;
			uniform float gapSize;

		#endif

		varying float vLineDistance;

		#ifdef WORLD_UNITS

			varying vec4 worldPos;
			varying vec3 worldStart;
			varying vec3 worldEnd;

			#ifdef USE_DASH

				varying vec2 vUv;

			#endif

		#else

			varying vec2 vUv;

		#endif

		#include <common>
		#include <color_pars_fragment>
		#include <fog_pars_fragment>
		#include <logdepthbuf_pars_fragment>
		#include <clipping_planes_pars_fragment>

		vec2 closestLineToLine(vec3 p1, vec3 p2, vec3 p3, vec3 p4) {

			float mua;
			float mub;

			vec3 p13 = p1 - p3;
			vec3 p43 = p4 - p3;

			vec3 p21 = p2 - p1;

			float d1343 = dot( p13, p43 );
			float d4321 = dot( p43, p21 );
			float d1321 = dot( p13, p21 );
			float d4343 = dot( p43, p43 );
			float d2121 = dot( p21, p21 );

			float denom = d2121 * d4343 - d4321 * d4321;

			float numer = d1343 * d4321 - d1321 * d4343;

			mua = numer / denom;
			mua = clamp( mua, 0.0, 1.0 );
			mub = ( d1343 + d4321 * ( mua ) ) / d4343;
			mub = clamp( mub, 0.0, 1.0 );

			return vec2( mua, mub );

		}

		void main() {

			float alpha = opacity;
			vec4 diffuseColor = vec4( diffuse, alpha );

			#include <clipping_planes_fragment>

			#ifdef USE_DASH

				if ( vUv.y < - 1.0 || vUv.y > 1.0 ) discard; // discard endcaps

				if ( mod( vLineDistance + dashOffset, dashSize + gapSize ) > dashSize ) discard; // todo - FIX

			#endif

			#ifdef WORLD_UNITS

				// Find the closest points on the view ray and the line segment
				vec3 rayEnd = normalize( worldPos.xyz ) * 1e5;
				vec3 lineDir = worldEnd - worldStart;
				vec2 params = closestLineToLine( worldStart, worldEnd, vec3( 0.0, 0.0, 0.0 ), rayEnd );

				vec3 p1 = worldStart + lineDir * params.x;
				vec3 p2 = rayEnd * params.y;
				vec3 delta = p1 - p2;
				float len = length( delta );
				float norm = len / linewidth;

				#ifndef USE_DASH

					#ifdef USE_ALPHA_TO_COVERAGE

						float dnorm = fwidth( norm );
						alpha = 1.0 - smoothstep( 0.5 - dnorm, 0.5 + dnorm, norm );

					#else

						if ( norm > 0.5 ) {

							discard;

						}

					#endif

				#endif

			#else

				#ifdef USE_ALPHA_TO_COVERAGE

					// artifacts appear on some hardware if a derivative is taken within a conditional
					float a = vUv.x;
					float b = ( vUv.y > 0.0 ) ? vUv.y - 1.0 : vUv.y + 1.0;
					float len2 = a * a + b * b;
					float dlen = fwidth( len2 );

					if ( abs( vUv.y ) > 1.0 ) {

						alpha = 1.0 - smoothstep( 1.0 - dlen, 1.0 + dlen, len2 );

					}

				#else

					if ( abs( vUv.y ) > 1.0 ) {

						float a = vUv.x;
						float b = ( vUv.y > 0.0 ) ? vUv.y - 1.0 : vUv.y + 1.0;
						float len2 = a * a + b * b;

						if ( len2 > 1.0 ) discard;

					}

				#endif

			#endif

			#include <logdepthbuf_fragment>
			#include <color_fragment>

			gl_FragColor = vec4( diffuseColor.rgb, alpha );

			#include <tonemapping_fragment>
			#include <colorspace_fragment>
			#include <fog_fragment>
			#include <premultiplied_alpha_fragment>

		}
		`
  )
};
class _c extends Ci {
  /**
   * Constructs a new line segments geometry.
   *
   * @param {Object} [parameters] - An object with one or more properties
   * defining the material's appearance. Any property of the material
   * (including any property from inherited materials) can be passed
   * in here. Color values can be passed any type of value accepted
   * by {@link Color#set}.
   */
  constructor(e) {
    super({
      type: "LineMaterial",
      uniforms: Zl.clone(si.line.uniforms),
      vertexShader: si.line.vertexShader,
      fragmentShader: si.line.fragmentShader,
      clipping: !0
      // required for clipping support
    }), this.isLineMaterial = !0, this.setValues(e);
  }
  /**
   * The material's color.
   *
   * @type {Color}
   * @default (1,1,1)
   */
  get color() {
    return this.uniforms.diffuse.value;
  }
  set color(e) {
    this.uniforms.diffuse.value = e;
  }
  /**
   * Whether the material's sizes (width, dash gaps) are in world units.
   *
   * @type {boolean}
   * @default false
   */
  get worldUnits() {
    return "WORLD_UNITS" in this.defines;
  }
  set worldUnits(e) {
    e === !0 ? this.defines.WORLD_UNITS = "" : delete this.defines.WORLD_UNITS;
  }
  /**
   * Controls line thickness in CSS pixel units when `worldUnits` is `false` (default),
   * or in world units when `worldUnits` is `true`.
   *
   * @type {number}
   * @default 1
   */
  get linewidth() {
    return this.uniforms.linewidth.value;
  }
  set linewidth(e) {
    this.uniforms.linewidth && (this.uniforms.linewidth.value = e);
  }
  /**
   * Whether the line is dashed, or solid.
   *
   * @type {boolean}
   * @default false
   */
  get dashed() {
    return "USE_DASH" in this.defines;
  }
  set dashed(e) {
    e === !0 !== this.dashed && (this.needsUpdate = !0), e === !0 ? this.defines.USE_DASH = "" : delete this.defines.USE_DASH;
  }
  /**
   * The scale of the dashes and gaps.
   *
   * @type {number}
   * @default 1
   */
  get dashScale() {
    return this.uniforms.dashScale.value;
  }
  set dashScale(e) {
    this.uniforms.dashScale.value = e;
  }
  /**
   * The size of the dash.
   *
   * @type {number}
   * @default 1
   */
  get dashSize() {
    return this.uniforms.dashSize.value;
  }
  set dashSize(e) {
    this.uniforms.dashSize.value = e;
  }
  /**
   * Where in the dash cycle the dash starts.
   *
   * @type {number}
   * @default 0
   */
  get dashOffset() {
    return this.uniforms.dashOffset.value;
  }
  set dashOffset(e) {
    this.uniforms.dashOffset.value = e;
  }
  /**
   * The size of the gap.
   *
   * @type {number}
   * @default 0
   */
  get gapSize() {
    return this.uniforms.gapSize.value;
  }
  set gapSize(e) {
    this.uniforms.gapSize.value = e;
  }
  /**
   * The opacity.
   *
   * @type {number}
   * @default 1
   */
  get opacity() {
    return this.uniforms.opacity.value;
  }
  set opacity(e) {
    this.uniforms && (this.uniforms.opacity.value = e);
  }
  /**
   * The size of the viewport, in screen pixels. This must be kept updated to make
   * screen-space rendering accurate.The `LineSegments2.onBeforeRender` callback
   * performs the update for visible objects.
   *
   * @type {Vector2}
   */
  get resolution() {
    return this.uniforms.resolution.value;
  }
  set resolution(e) {
    this.uniforms.resolution.value.copy(e);
  }
  /**
   * Whether to use alphaToCoverage or not. When enabled, this can improve the
   * anti-aliasing of line edges when using MSAA.
   *
   * @type {boolean}
   */
  get alphaToCoverage() {
    return "USE_ALPHA_TO_COVERAGE" in this.defines;
  }
  set alphaToCoverage(e) {
    this.defines && (e === !0 !== this.alphaToCoverage && (this.needsUpdate = !0), e === !0 ? this.defines.USE_ALPHA_TO_COVERAGE = "" : delete this.defines.USE_ALPHA_TO_COVERAGE);
  }
}
const hh = new Ye(), Ip = new b(), Dp = new b(), Vt = new Ye(), Gt = new Ye(), qi = new Ye(), dh = new b(), uh = new Ne(), Wt = new rg(), Np = new b(), Mo = new Tt(), wo = new Lt(), Zi = new Ye();
let Ki, gs;
function Up(r, e, t) {
  return Zi.set(0, 0, -e, 1).applyMatrix4(r.projectionMatrix), Zi.multiplyScalar(1 / Zi.w), Zi.x = gs / t.width, Zi.y = gs / t.height, Zi.applyMatrix4(r.projectionMatrixInverse), Zi.multiplyScalar(1 / Zi.w), Math.abs(Math.max(Zi.x, Zi.y));
}
function WM(r, e) {
  const t = r.matrixWorld, i = r.geometry, n = i.attributes.instanceStart, s = i.attributes.instanceEnd, a = Math.min(i.instanceCount, n.count);
  for (let o = 0, l = a; o < l; o++) {
    Wt.start.fromBufferAttribute(n, o), Wt.end.fromBufferAttribute(s, o), Wt.applyMatrix4(t);
    const c = new b(), h = new b();
    Ki.distanceSqToSegment(Wt.start, Wt.end, h, c), h.distanceTo(c) < gs * 0.5 && e.push({
      point: h,
      pointOnLine: c,
      distance: Ki.origin.distanceTo(h),
      object: r,
      face: null,
      faceIndex: o,
      uv: null,
      uv1: null
    });
  }
}
function XM(r, e, t) {
  const i = e.projectionMatrix, s = r.material.resolution, a = r.matrixWorld, o = r.geometry, l = o.attributes.instanceStart, c = o.attributes.instanceEnd, h = Math.min(o.instanceCount, l.count), d = -e.near;
  Ki.at(1, qi), qi.w = 1, qi.applyMatrix4(e.matrixWorldInverse), qi.applyMatrix4(i), qi.multiplyScalar(1 / qi.w), qi.x *= s.x / 2, qi.y *= s.y / 2, qi.z = 0, dh.copy(qi), uh.multiplyMatrices(e.matrixWorldInverse, a);
  for (let u = 0, p = h; u < p; u++) {
    if (Vt.fromBufferAttribute(l, u), Gt.fromBufferAttribute(c, u), Vt.w = 1, Gt.w = 1, Vt.applyMatrix4(uh), Gt.applyMatrix4(uh), Vt.z > d && Gt.z > d)
      continue;
    if (Vt.z > d) {
      const x = Vt.z - Gt.z, y = (Vt.z - d) / x;
      Vt.lerp(Gt, y);
    } else if (Gt.z > d) {
      const x = Gt.z - Vt.z, y = (Gt.z - d) / x;
      Gt.lerp(Vt, y);
    }
    Vt.applyMatrix4(i), Gt.applyMatrix4(i), Vt.multiplyScalar(1 / Vt.w), Gt.multiplyScalar(1 / Gt.w), Vt.x *= s.x / 2, Vt.y *= s.y / 2, Gt.x *= s.x / 2, Gt.y *= s.y / 2, Wt.start.copy(Vt), Wt.start.z = 0, Wt.end.copy(Gt), Wt.end.z = 0;
    const _ = Wt.closestPointToPointParameter(dh, !0);
    Wt.at(_, Np);
    const g = da.lerp(Vt.z, Gt.z, _), f = g >= -1 && g <= 1, v = dh.distanceTo(Np) < gs * 0.5;
    if (f && v) {
      Wt.start.fromBufferAttribute(l, u), Wt.end.fromBufferAttribute(c, u), Wt.start.applyMatrix4(a), Wt.end.applyMatrix4(a);
      const x = new b(), y = new b();
      Ki.distanceSqToSegment(Wt.start, Wt.end, y, x), t.push({
        point: y,
        pointOnLine: x,
        distance: Ki.origin.distanceTo(y),
        object: r,
        face: null,
        faceIndex: u,
        uv: null,
        uv1: null
      });
    }
  }
}
class Gd extends Je {
  /**
   * Constructs a new wide line.
   *
   * @param {LineSegmentsGeometry} [geometry] - The line geometry.
   * @param {LineMaterial} [material] - The line material.
   */
  constructor(e = new Vd(), t = new _c({ color: Math.random() * 16777215 })) {
    super(e, t), this.isLineSegments2 = !0, this.type = "LineSegments2";
  }
  /**
   * Computes an array of distance values which are necessary for rendering dashed lines.
   * For each vertex in the geometry, the method calculates the cumulative length from the
   * current point to the very beginning of the line.
   *
   * @return {LineSegments2} A reference to this instance.
   */
  computeLineDistances() {
    const e = this.geometry, t = e.attributes.instanceStart, i = e.attributes.instanceEnd, n = new Float32Array(2 * t.count);
    for (let a = 0, o = 0, l = t.count; a < l; a++, o += 2)
      Ip.fromBufferAttribute(t, a), Dp.fromBufferAttribute(i, a), n[o] = o === 0 ? 0 : n[o - 1], n[o + 1] = n[o] + Ip.distanceTo(Dp);
    const s = new Nl(n, 2, 1);
    return e.setAttribute("instanceDistanceStart", new Ei(s, 1, 0)), e.setAttribute("instanceDistanceEnd", new Ei(s, 1, 1)), this;
  }
  /**
   * Computes intersection points between a casted ray and this instance.
   *
   * @param {Raycaster} raycaster - The raycaster.
   * @param {Array<Object>} intersects - The target array that holds the intersection points.
   */
  raycast(e, t) {
    const i = this.material.worldUnits, n = e.camera;
    n === null && !i && console.error('LineSegments2: "Raycaster.camera" needs to be set in order to raycast against LineSegments2 while worldUnits is set to false.');
    const s = e.params.Line2 !== void 0 && e.params.Line2.threshold || 0;
    Ki = e.ray;
    const a = this.matrixWorld, o = this.geometry, l = this.material;
    gs = l.linewidth + s, o.boundingSphere === null && o.computeBoundingSphere(), wo.copy(o.boundingSphere).applyMatrix4(a);
    let c;
    if (i)
      c = gs * 0.5;
    else {
      const d = Math.max(n.near, wo.distanceToPoint(Ki.origin));
      c = Up(n, d, l.resolution);
    }
    if (wo.radius += c, Ki.intersectsSphere(wo) === !1)
      return;
    o.boundingBox === null && o.computeBoundingBox(), Mo.copy(o.boundingBox).applyMatrix4(a);
    let h;
    if (i)
      h = gs * 0.5;
    else {
      const d = Math.max(n.near, Mo.distanceToPoint(Ki.origin));
      h = Up(n, d, l.resolution);
    }
    Mo.expandByScalar(h), Ki.intersectsBox(Mo) !== !1 && (i ? WM(this, t) : XM(this, n, t));
  }
  onBeforeRender(e) {
    const t = this.material.uniforms;
    t && t.resolution && (e.getViewport(hh), this.material.uniforms.resolution.value.set(hh.z, hh.w));
  }
}
class mg extends Vd {
  toJSON() {
    return mc.prototype.toJSON.call(this);
  }
}
const kr = new b(), zr = new b(), Op = new He();
class qM extends ei {
  /**
   * Constructs a new vertex normals helper.
   *
   * @param {Object3D} object - The object for which to visualize vertex normals.
   * @param {number} [size=1] - The helper's size.
   * @param {number|Color|string} [color=0xff0000] - The helper's color.
   */
  constructor(e, t = 1, i = 16711680) {
    const n = new Ue(), s = e.geometry.attributes.normal.count, a = new ve(s * 2 * 3, 3);
    n.setAttribute("position", a), super(n, new It({ color: i, toneMapped: !1 })), this.object = e, this.size = t, this.type = "VertexNormalsHelper", this.matrixAutoUpdate = !1, this.isVertexNormalsHelper = !0, this.update();
  }
  /**
   * Updates the vertex normals preview based on the object's world transform.
   */
  update() {
    this.object.updateMatrixWorld(!0), Op.getNormalMatrix(this.object.matrixWorld);
    const e = this.object.matrixWorld, t = this.geometry.attributes.position, i = this.object.geometry;
    if (i) {
      const n = i.attributes.position, s = i.attributes.normal;
      let a = 0;
      for (let o = 0, l = n.count; o < l; o++)
        kr.fromBufferAttribute(n, o).applyMatrix4(e), zr.fromBufferAttribute(s, o), zr.applyMatrix3(Op).normalize().multiplyScalar(this.size).add(kr), t.setXYZ(a, kr.x, kr.y, kr.z), a = a + 1, t.setXYZ(a, zr.x, zr.y, zr.z), a = a + 1;
    }
    t.needsUpdate = !0;
  }
  /**
   * Frees the GPU-related resources allocated by this instance. Call this
   * method whenever this instance is no longer used in your app.
   */
  dispose() {
    this.geometry.dispose(), this.material.dispose();
  }
}
const An = {
  debug: 0,
  info: 1,
  warn: 2,
  error: 3,
  silent: 4
};
let Ks = "warn";
const ft = {
  /**
   * Set the minimum log level. Messages below this level are suppressed.
   * @param level - The minimum level to display
   */
  setLevel(r) {
    Ks = r;
  },
  /**
   * Get the current log level.
   * @returns The current minimum log level
   */
  getLevel() {
    return Ks;
  },
  /**
   * Log debug message (verbose, for development).
   * Only shown when level is "debug".
   */
  debug(...r) {
    An[Ks] <= An.debug && console.log("[three-cad-viewer]", ...r);
  },
  /**
   * Log info message (general information).
   * Shown when level is "debug" or "info".
   */
  info(...r) {
    An[Ks] <= An.info && console.log("[three-cad-viewer]", ...r);
  },
  /**
   * Log warning message (potential issues).
   * Shown when level is "debug", "info", or "warn".
   */
  warn(...r) {
    An[Ks] <= An.warn && console.warn("[three-cad-viewer]", ...r);
  },
  /**
   * Log error message (failures).
   * Shown unless level is "silent".
   */
  error(...r) {
    An[Ks] <= An.error && console.error("[three-cad-viewer]", ...r);
  }
}, bi = {
  geometry: 0,
  material: 0,
  texture: 0
};
let as = !1;
const Js = /* @__PURE__ */ new Map(), Ut = {
  /**
   * Enable debug mode to capture creation info (stack traces, labels).
   * Call before creating any viewer resources for full tracking.
   *
   * Performance impact: Captures stack trace on every resource creation.
   * Only enable when debugging leaks.
   */
  enableDebug() {
    as = !0, ft.info("GPU tracker debug mode enabled");
  },
  /**
   * Disable debug mode and clear tracked objects.
   */
  disableDebug() {
    as = !1, Js.clear(), ft.info("GPU tracker debug mode disabled");
  },
  /**
   * Check if debug mode is enabled.
   */
  get isDebugEnabled() {
    return as;
  },
  /**
   * Track a GPU resource creation.
   *
   * @param type - Resource type (geometry, material, texture)
   * @param obj - The Three.js object being tracked
   * @param label - Optional descriptive label (e.g., "front face material for /Assembly/Part1")
   */
  track(r, e, t) {
    var i;
    if (bi[r]++, as) {
      const n = ((i = new Error().stack) == null ? void 0 : i.split(`
`).slice(2, 6).join(`
`)) ?? "";
      Js.set(e, {
        type: r,
        label: t ?? "unlabeled",
        stack: n,
        timestamp: performance.now()
      });
    }
  },
  /**
   * Untrack a GPU resource after disposal.
   *
   * @param type - Resource type (required in non-debug mode)
   * @param obj - The Three.js object being untracked (optional in non-debug mode)
   */
  untrack(r, e) {
    if (as && e) {
      const t = Js.get(e);
      if (t) {
        bi[t.type]--, Js.delete(e);
        return;
      }
    }
    bi[r] > 0 && bi[r]--;
  },
  /**
   * Get current resource counts.
   */
  get summary() {
    return {
      geometry: bi.geometry,
      material: bi.material,
      texture: bi.texture,
      total: bi.geometry + bi.material + bi.texture
    };
  },
  /**
   * Get all tracked resources (debug mode only).
   *
   * @returns Array of currently tracked resources
   */
  getResources() {
    return as ? Array.from(Js.values()) : (ft.warn("GPU tracker: getResources() requires debug mode - call enableDebug() first"), []);
  },
  /**
   * Get tracked resources grouped by type.
   */
  getResourcesByType() {
    const r = this.getResources();
    return {
      geometry: r.filter((e) => e.type === "geometry"),
      material: r.filter((e) => e.type === "material"),
      texture: r.filter((e) => e.type === "texture")
    };
  },
  /**
   * Log details of currently tracked resources.
   * Useful for inspecting allocations or detecting leaks after disposal.
   * Always outputs to console regardless of logger level.
   */
  details() {
    const { total: r, geometry: e, material: t, texture: i } = this.summary;
    if (r === 0) {
      console.log("GPU tracker: No resources currently allocated");
      return;
    }
    if (console.log(`GPU tracker: ${r} resources allocated:`), console.log(`  - Geometries: ${e}`), console.log(`  - Materials: ${t}`), console.log(`  - Textures: ${i}`), as) {
      const n = this.getResources();
      console.log(`
Resource details:`), n.forEach((s, a) => {
        console.log(`
[${a + 1}] ${s.type}: ${s.label}`), console.log(`    Created at: ${s.timestamp.toFixed(2)}ms`), console.log(`    Stack:
${s.stack}`);
      });
    } else
      console.log(`
For detailed resource info, enable debug mode before creating resources:`), console.log("  gpuTracker.enableDebug()");
  },
  /**
   * Reset all counters and tracked objects.
   * Useful for testing or starting fresh.
   */
  reset() {
    bi.geometry = 0, bi.material = 0, bi.texture = 0, Js.clear();
  },
  /**
   * Assert that all resources have been disposed.
   * Useful in tests.
   *
   * @throws Error if any resources remain
   */
  assertEmpty() {
    const { total: r } = this.summary;
    if (r !== 0)
      throw this.details(), new Error(`GPU tracker: ${r} resources not disposed`);
  },
  // Convenience methods for common Three.js types
  /**
   * Track a geometry and return it (for chaining).
   */
  trackGeometry(r, e) {
    return this.track("geometry", r, e), r;
  },
  /**
   * Track a material and return it (for chaining).
   */
  trackMaterial(r, e) {
    return this.track("material", r, e), r;
  },
  /**
   * Track a texture and return it (for chaining).
   */
  trackTexture(r, e) {
    return this.track("texture", r, e), r;
  }
};
typeof window < "u" && (window.tcv_gpu = Ut);
const gg = {
  x: new b(1, 0, 0),
  y: new b(0, 1, 0),
  z: new b(0, 0, 1)
};
function qh(r, e = 1) {
  return r.flat(e);
}
function ji(r) {
  if (!Array.isArray(r) || r.length !== 3)
    throw new Error(`Expected array of length 3, got ${Array.isArray(r) ? r.length : typeof r}`);
  return r;
}
function Fp(r) {
  if (!Array.isArray(r) || r.length !== 4)
    throw new Error(`Expected array of length 4, got ${Array.isArray(r) ? r.length : typeof r}`);
  return r;
}
function Zh(r, e, t = 1e-9) {
  if (Array.isArray(r) && Array.isArray(e))
    return r.length === e.length && r.every((i, n) => Zh(i, e[n], t));
  if (r !== null && e !== null && typeof r == "object" && typeof e == "object") {
    const i = r, n = e, s = Object.keys(i), a = Object.keys(n);
    return s.length === a.length && s.every((o) => Object.prototype.hasOwnProperty.call(n, o)) ? s.every((o) => Zh(i[o], n[o], t)) : !1;
  } else
    return typeof r == "number" && typeof e == "number" ? Math.abs(r - e) < t : r === e;
}
function _g(r, e) {
  r && (e(r), r.children && r.children.length > 0 && r.children.forEach((t) => {
    _g(t, e);
  }));
}
function Wd(r) {
  if (r) {
    Ut.untrack("geometry", r), r.dispose();
    for (const e of Object.values(r.attributes))
      e && typeof e == "object" && "dispose" in e && typeof e.dispose == "function" && e.dispose();
  }
}
function ZM(r) {
  return r !== null && typeof r == "object" && "dispose" in r && typeof r.dispose == "function";
}
function Bp(r) {
  if (!r)
    return;
  const e = [
    r.map,
    r.normalMap,
    r.roughnessMap,
    r.metalnessMap,
    r.aoMap,
    r.emissiveMap,
    r.alphaMap,
    r.bumpMap
  ];
  for (const t of e)
    ZM(t) && (Ut.untrack("texture", t), t.dispose());
  Ut.untrack("material", r), r.dispose();
}
function YM(r) {
  r.geometry && Wd(r.geometry), r.material && (Array.isArray(r.material) ? r.material.forEach(Bp) : Bp(r.material));
}
function ct(r) {
  if (r) {
    if (Array.isArray(r)) {
      r.forEach(ct);
      return;
    }
    Array.isArray(r.children) && r.children.forEach(ct), r.dispose ? r.dispose() : (r.isMesh || r.isLine || r.isPoints) && YM(r);
  }
}
class jM {
  constructor() {
    this.getshortcuts = (e) => this.keyMapping[e].replace("Key", ""), this.get = (e, t) => {
      const i = this.keyMapping[t];
      return e[i];
    }, this.set = (e) => {
      for (const t of Object.keys(e)) {
        const i = e[t];
        i !== void 0 && (this.keyMapping[t] = i);
      }
    }, this.setActionShortcuts = (e) => {
      this.actionShortcuts = { ...e }, this.reverseActionShortcuts = {};
      for (const [t, i] of Object.entries(e))
        this.reverseActionShortcuts[i] = t;
    }, this.getActionForKey = (e) => this.reverseActionShortcuts[e], this.getShortcutForAction = (e) => this.actionShortcuts[e], this.getActionShortcuts = () => ({ ...this.actionShortcuts }), this.keyMapping = {
      shift: "ctrlKey",
      ctrl: "shiftKey",
      meta: "altKey",
      alt: "metaKey"
    }, this.actionShortcuts = {}, this.reverseActionShortcuts = {};
  }
  get_config() {
    return Object.assign({}, this.keyMapping);
  }
}
function Eo(r) {
  return Math.round(Math.PI * r);
}
function $t(r) {
  return "isMesh" in r && r.isMesh === !0;
}
function kp(r) {
  return "isLine" in r && r.isLine === !0;
}
function zp(r) {
  return "isPoints" in r && r.isPoints === !0;
}
function or(r) {
  return "isOrthographicCamera" in r && r.isOrthographicCamera === !0;
}
function ia(r) {
  return "isPerspectiveCamera" in r && r.isPerspectiveCamera === !0;
}
function en(r) {
  return r.type === "LineSegments2";
}
function $M(r) {
  return "color" in r;
}
function KM(r) {
  return "isMeshStandardMaterial" in r && r.isMeshStandardMaterial === !0;
}
const _t = new jM();
class JM {
  constructor() {
    this.add = (e, t, i, n = !1) => {
      e.addEventListener(t, i, n), this.listeners.push({
        target: e,
        event: t,
        handler: i,
        options: n
      });
    }, this.listeners = [];
  }
  dispose() {
    this.listeners.forEach(({ target: e, event: t, handler: i, options: n }) => {
      e.removeEventListener(t, i, n);
    }), this.listeners = [];
  }
}
class QM {
  constructor() {
    this.originalMaterials = /* @__PURE__ */ new Map(), this.zebraMaterials = /* @__PURE__ */ new Map(), this.settings = {
      stripeCount: 15,
      stripeDirection: 0,
      // angle in degrees
      colorScheme: "blackwhite",
      // 'blackwhite', 'colorful', 'grayscale'
      opacity: 1,
      // 0.0 = fully transparent (see original), 1.0 = fully opaque (only zebra)
      mappingMode: "normal"
      // 'reflection' (Onshape-like) or 'normal' (Fusion360/Shapr3D-like)
    }, this.zebraTexture = null, this.createZebraTexture();
  }
  /**
   * Create the zebra stripe texture
   */
  createZebraTexture() {
    const e = document.createElement("canvas");
    e.width = 1, e.height = 4096;
    const t = e.getContext("2d"), i = this.settings.stripeCount % 2 === 1, n = i ? this.settings.stripeCount - 1 : this.settings.stripeCount, s = e.height / n;
    let a = 0;
    for (let o = 0; o < this.settings.stripeCount; o++) {
      let l, c;
      switch (this.settings.colorScheme) {
        case "blackwhite":
          l = "#000000", c = "#ffffff";
          break;
        case "colorful": {
          const d = o / this.settings.stripeCount * 360;
          l = `hsl(${d}, 100%, 50%)`, c = `hsl(${(d + 180) % 360}, 100%, 50%)`;
          break;
        }
        case "grayscale":
          l = "#D2D2D2", c = "#464646";
          break;
      }
      const h = i && (o === 0 || o === this.settings.stripeCount - 1) ? s * 0.5 : s;
      t.fillStyle = o % 2 === 0 ? l : c, t.fillRect(0, a, e.width, h), a += h;
    }
    this.zebraTexture && this.zebraTexture.dispose(), this.zebraTexture = new fd(e), this.zebraTexture.wrapS = xs, this.zebraTexture.wrapT = xs, this.zebraTexture.needsUpdate = !0, this.zebraMaterials.forEach((o) => {
      o.uniforms.zebraTexture.value = this.zebraTexture, o.uniforms.zebraTexture.value.needsUpdate = !0, o.uniformsNeedUpdate = !0, o.needsUpdate = !0;
    });
  }
  /**
   * Create zebra shader material
   */
  createZebraMaterial() {
    const e = this.settings.stripeDirection * Math.PI / 180, t = new b(Math.cos(e), Math.sin(e), 0).normalize();
    return new Ci({
      uniforms: {
        zebraTexture: { value: this.zebraTexture },
        direction: { value: t },
        opacity: { value: this.settings.opacity },
        baseColor: { value: new oe(0.7, 0.7, 0.7) },
        // Will be overridden per mesh
        mappingMode: {
          value: this.settings.mappingMode === "reflection" ? 0 : 1
        }
        // 0 = reflection, 1 = normal
      },
      vertexShader: `
                varying vec3 vViewNormal;
                varying vec3 vViewPosition;
                varying vec4 vScreenPosition;

                void main() {
                    // Transform normal to view space
                    vViewNormal = normalize(normalMatrix * normal);

                    // Transform position to view space
                    vec4 mvPosition = modelViewMatrix * vec4(position, 1.0);
                    vViewPosition = mvPosition.xyz;

                    gl_Position = projectionMatrix * mvPosition;

                    // Store screen position for normal mode
                    vScreenPosition = gl_Position;
                }
            `,
      fragmentShader: `
                uniform sampler2D zebraTexture;
                uniform vec3 direction;
                uniform float opacity;
                uniform vec3 baseColor;
                uniform int mappingMode; // 0 = reflection, 1 = normal

                varying vec3 vViewNormal;
                varying vec3 vViewPosition;
                varying vec4 vScreenPosition;

                void main() {
                    // Normalize view-space normal
                    vec3 normal = normalize(vViewNormal);

                    float v;

                    if (mappingMode == 0) {
                        // Reflection mode (Onshape-like): circular/elliptical stripes
                        // View direction in view space (points toward camera)
                        vec3 viewDir = normalize(-vViewPosition);

                        // Calculate reflection in view space
                        vec3 mappingVector = reflect(-viewDir, normal);

                        // Use the reflection vector with screen-space direction
                        v = dot(mappingVector, direction) * 3.0 * 0.5 + 0.5;
                    } else {
                        // Normal mode (Fusion360/Shapr3D-like): zoom-independent view-based stripes
                        // Use view direction normalized by distance (zoom-independent)

                        // Normalize view position by distance to make it zoom-independent
                        float dist = length(vViewPosition);
                        vec2 viewDir2D = vViewPosition.xy / dist;

                        // Rotate by stripe direction
                        float cosA = direction.x / length(direction.xy);
                        float sinA = direction.y / length(direction.xy);
                        float rotatedPos = viewDir2D.x * cosA + viewDir2D.y * sinA;

                        // Scale for stripe frequency (zoom-independent)
                        float positionValue = rotatedPos * 2.0;

                        // Add normal influence to follow curvature
                        float normalValue = dot(normal, direction) * 0.5;

                        // Combine: position creates base stripes, normal makes them follow curvature
                        v = (positionValue + normalValue) * 3.0 * 0.5 + 0.5;
                    }

                    // Sample the zebra texture (texture varies in V/Y direction)
                    vec4 zebraColor = texture2D(zebraTexture, vec2(0.5, v));

                    // Blend zebra stripes with original material color based on opacity
                    vec3 finalColor = mix(baseColor, zebraColor.rgb, opacity);

                    gl_FragColor = vec4(finalColor, 1.0);
                }
            `,
      side: ri
    });
  }
  /**
   * Apply zebra material to a mesh
   */
  applyToMesh(e, t) {
    if (!e.isMesh || e.userData.excludeFromZebra)
      return;
    const i = Array.isArray(e.material) ? e.material[0] : e.material;
    if (this.originalMaterials.has(e.uuid) || this.originalMaterials.set(e.uuid, i), !this.zebraMaterials.has(e.uuid)) {
      const n = this.createZebraMaterial();
      let s = new oe(0.7, 0.7, 0.7);
      $M(i) ? s = i.color.clone() : KM(i) && i.map && (s = new oe(1, 1, 1)), n.uniforms.baseColor = { value: s }, this.zebraMaterials.set(e.uuid, n);
    }
    e.material = this.zebraMaterials.get(e.uuid), e.material.visible = t;
  }
  /**
   * Restore original material to a mesh
   */
  restoreMesh(e, t) {
    if (!e.isMesh)
      return;
    const i = this.originalMaterials.get(e.uuid);
    i && (e.material = i, i.visible = t);
  }
  /**
   * Update stripe count
   */
  setStripeCount(e) {
    this.settings.stripeCount = Math.max(2, Math.min(50, e)), this.createZebraTexture();
  }
  /**
   * Update stripe direction (in degrees, 0-90° is sufficient)
   */
  setStripeDirection(e) {
    this.settings.stripeDirection = e;
    const t = e * Math.PI / 180, i = new b(Math.cos(t), Math.sin(t), 0).normalize();
    this.zebraMaterials.forEach((n) => {
      n.uniforms.direction.value = i;
    });
  }
  /**
   * Update color scheme
   */
  setColorScheme(e) {
    ["blackwhite", "colorful", "grayscale"].includes(e) && (this.settings.colorScheme = e, this.createZebraTexture());
  }
  /**
   * Update stripe opacity (0.0 = show original material, 1.0 = full zebra)
   */
  setStripeOpacity(e) {
    this.settings.opacity = Math.max(0, Math.min(1, e)), this.zebraMaterials.forEach((t) => {
      t.uniforms.opacity.value = this.settings.opacity;
    });
  }
  /**
   * Update mapping mode ('reflection' = Onshape-like, 'normal' = Fusion360/Shapr3D-like)
   */
  setMappingMode(e) {
    if (["reflection", "normal"].includes(e)) {
      this.settings.mappingMode = e;
      const t = e === "reflection" ? 0 : 1;
      this.zebraMaterials.forEach((i) => {
        i.uniforms.mappingMode.value = t, i.uniformsNeedUpdate = !0, i.needsUpdate = !0;
      });
    }
  }
  /**
   * Update camera position for shaders (call in render loop).
   * No longer needed - view space calculations handle this automatically.
   * This method is kept for API compatibility.
   */
  update() {
  }
  /**
   * Clean up resources
   */
  dispose() {
    this.zebraTexture && this.zebraTexture.dispose(), this.zebraMaterials.forEach((e) => {
      e.dispose();
    }), this.originalMaterials.clear(), this.zebraMaterials.clear();
  }
}
const ew = 5480675, tw = 9026019;
function iw(r) {
  return "color" in r && "linewidth" in r;
}
class Mi extends li {
  /**
   * Create an ObjectGroup for managing a CAD object's visual representation.
   * @param opacity - Default opacity value (0.0 to 1.0).
   * @param alpha - Transparency alpha value (0.0 to 1.0).
   * @param edge_color - Edge color as hex value.
   * @param shapeInfo - Shape metadata with topo and geomtype fields.
   * @param subtype - Shape subtype (e.g., "solid", "edges", "vertices").
   * @param renderback - Whether back faces should be rendered.
   */
  constructor(e, t, i, n, s, a = !1) {
    super(), this.type = "ObjectGroup", this.isObjectGroup = !0, this.opacity = e, this.alpha = t ?? 1, this.transparent = !1, this.edge_color = i, this.shapeInfo = n, this.subtype = s, this.renderback = a, this.front = null, this.back = null, this.edges = null, this.edgeMaterial = null, this.vertices = null, this.clipping = /* @__PURE__ */ new Map(), this.isSelected = !1, this.originalColor = null, this.originalBackColor = null, this.originalWidth = null, this.vertexFocusSize = 8, this.edgeFocusWidth = 5, this._zebra = null;
  }
  /**
   * Get the zebra tool, creating it on first access.
   */
  get zebra() {
    return this._zebra || (this._zebra = new QM()), this._zebra;
  }
  /**
   * Dispose of all resources and clean up memory.
   * Releases geometry, materials, children, and zebra tool.
   */
  dispose() {
    this.shapeGeometry && (Wd(this.shapeGeometry), this.shapeGeometry = null), this.children && (ct(this.children), this.clear()), this._zebra && (this._zebra.dispose(), this._zebra = null);
  }
  /**
   * Set the front face mesh.
   */
  setFront(e) {
    this.add(e), this.front = e, this.originalColor = e.material.color.clone();
  }
  /**
   * Set the back face mesh.
   */
  setBack(e) {
    this.add(e), this.back = e, this.front || (this.originalBackColor = e.material.color.clone());
  }
  /**
   * Set the edges geometry.
   * Extracts and stores the material separately for type-safe access.
   */
  setEdges(e) {
    this.add(e), this.edges = e;
    const t = e.material;
    if (Array.isArray(t))
      throw new Error("Multi-material edges are not supported");
    if (!iw(t))
      throw new Error("Edge material must have color and linewidth properties");
    this.edgeMaterial = t, this.front || (this.originalColor = this.edgeMaterial.color.clone(), this.originalWidth = this.edgeMaterial.linewidth);
  }
  /**
   * Set the vertices points.
   */
  setVertices(e) {
    this.add(e), this.vertices = e, this.originalColor = e.material.color.clone(), this.originalWidth = e.material.size;
  }
  /**
   * Add a clipping group for a plane index.
   */
  addClipping(e, t) {
    this.add(e), this.clipping.set(t, e);
  }
  /**
   * Widen or restore point/edge size for visual emphasis.
   * @param flag - Whether to widen (true) or restore original size (false).
   */
  widen(e) {
    this.vertices ? this.vertices.material.size = e ? this.vertexFocusSize : this.isSelected ? this.vertexFocusSize - 2 : this.originalWidth : this.edgeMaterial && (this.edgeMaterial.linewidth = e ? this.edgeFocusWidth : this.isSelected ? this.edgeFocusWidth - 2 : this.originalWidth);
  }
  /**
   * Toggle the selection state of this object.
   * Updates highlight and resets widening.
   */
  toggleSelection() {
    const e = !this.isSelected;
    this.isSelected = e, this.highlight(e), this.widen(!1);
  }
  /**
   * Remove highlight from this object.
   * @param keepSelection - If true, preserve selection state.
   */
  unhighlight(e) {
    (!e || !this.isSelected) && (this.isSelected = !1, this.highlight(!1)), this.widen(!1);
  }
  /**
   * Get the highlight color based on selection state.
   */
  _getHighlightColor() {
    return new oe(this.isSelected ? ew : tw);
  }
  /**
   * Apply color to a mesh and mark material for update.
   */
  _applyColorToMaterial(e, t) {
    e.color = t, e.needsUpdate = !0;
  }
  /**
   * Iterate over all child materials, excluding clipping planes.
   */
  _forEachMaterial(e) {
    for (const t of this.children)
      if (!t.name.startsWith("clipping") && $t(t)) {
        if (Array.isArray(t.material))
          throw new Error("Multi-material meshes are not supported");
        e(t.material);
      }
  }
  /**
   * Iterate over face materials that are MeshStandardMaterial (have PBR properties).
   * Skips MeshBasicMaterial and other non-PBR materials.
   */
  _forEachStandardMaterial(e) {
    this.front && this.front.material instanceof Bn && e(this.front.material), this.back && this.back.material instanceof Bn && e(this.back.material);
  }
  /**
   * Apply or remove highlight color to this object.
   * @param flag - Whether to apply highlight (true) or restore original color (false).
   */
  highlight(e) {
    var n, s;
    const t = this._getHighlightColor(), i = ((n = this.front) == null ? void 0 : n.material) || ((s = this.vertices) == null ? void 0 : s.material) || this.edgeMaterial;
    i && (this.widen(e), this._applyColorToMaterial(i, e ? t : this.originalColor)), this.back && this._applyColorToMaterial(this.back.material, e ? t : this.originalBackColor);
  }
  /**
   * Clear all highlights and selection state.
   */
  clearHighlights() {
    this.highlight(!1), this.isSelected = !1, this.widen(!1);
  }
  /**
   * Get metrics about this object's topology type.
   */
  metrics() {
    return this.front ? { name: "face", value: 0 } : this.vertices ? { name: "vertex", value: 0 } : this.edges ? { name: "edge", value: 0 } : null;
  }
  /**
   * Set metalness value for front face materials.
   */
  setMetalness(e) {
    this._forEachStandardMaterial((t) => {
      t.metalness = e, t.needsUpdate = !0;
    });
  }
  /**
   * Set roughness value for front face materials.
   */
  setRoughness(e) {
    this._forEachStandardMaterial((t) => {
      t.roughness = e, t.needsUpdate = !0;
    });
  }
  /**
   * Enable or disable transparency mode.
   * Adjusts opacity and depth write settings.
   */
  setTransparent(e) {
    this.transparent = e;
    const t = e ? this.opacity * this.alpha : this.alpha;
    this.back && (this.back.material.opacity = t), this.front && (this.front.material.opacity = t), this._forEachMaterial((i) => {
      i.depthWrite = this.alpha < 1 ? !1 : !e, i.depthTest = !0, i.needsUpdate = !0;
    });
  }
  /**
   * Set whether edges should be rendered in black or original color.
   * Skips edges with vertexColors enabled (e.g., trihedron axes).
   */
  setBlackEdges(e) {
    if (this.edgeMaterial && !this.edgeMaterial.vertexColors) {
      const t = e ? 0 : this.edge_color;
      this.originalColor = new oe(t), this.edgeMaterial.color = new oe(t), this.edgeMaterial.needsUpdate = !0;
    }
  }
  /**
   * Set the edge color.
   * Skips edges with vertexColors enabled (e.g., trihedron axes).
   */
  setEdgeColor(e) {
    this.edgeMaterial && !this.edgeMaterial.vertexColors && (this.edge_color = e, this.edgeMaterial.color = new oe(e), this.edgeMaterial.needsUpdate = !0);
  }
  /**
   * Set the opacity value. Only applied visually when transparent mode is enabled.
   */
  setOpacity(e) {
    if (this.opacity = e, this.transparent) {
      const t = this.opacity * this.alpha;
      this.front && (this.front.material.opacity = t, this.front.material.needsUpdate = !0), this.back && (this.back.material.opacity = t, this.back.material.needsUpdate = !0);
    }
  }
  /**
   * Set visibility of the shape (front face and clipping caps).
   */
  setShapeVisible(e) {
    this.front && (this.front.material.visible = e);
    for (const t of this.clipping.values()) {
      const i = t.children[0], n = t.children[1];
      if ($t(i)) {
        if (Array.isArray(i.material))
          throw new Error("Multi-material meshes are not supported");
        i.material.visible = e;
      }
      if ($t(n)) {
        if (Array.isArray(n.material))
          throw new Error("Multi-material meshes are not supported");
        n.material.visible = e;
      }
    }
    this.back && this.renderback && (this.back.material.visible = e);
  }
  /**
   * Set visibility of edges and vertices.
   */
  setEdgesVisible(e) {
    this.edgeMaterial && (this.edgeMaterial.visible = e), this.vertices && (this.vertices.material.visible = e);
  }
  /**
   * Set visibility of back faces.
   */
  setBackVisible(e) {
    this.back && this.front && this.front.material.visible && (this.back.material.visible = this.renderback || e);
  }
  /**
   * Get the current visibility state.
   */
  getVisibility() {
    return this.front ? this.edgeMaterial ? this.front.material.visible || this.edgeMaterial.visible : this.front.material.visible : this.edgeMaterial ? this.edgeMaterial.visible : this.vertices ? this.vertices.material.visible : !1;
  }
  /**
   * Set clip intersection mode for all materials.
   */
  setClipIntersection(e) {
    this._forEachMaterial((t) => {
      t.clipIntersection = e;
    });
  }
  /**
   * Set clipping planes for all materials.
   */
  setClipPlanes(e) {
    this.back && (this.back.material.clippingPlanes = e), this.front && (this.front.material.clippingPlanes = e), this.edgeMaterial && (this.edgeMaterial.clippingPlanes = e), this.vertices && (this.vertices.material.clippingPlanes = e), this.updateMaterials(!0);
  }
  /**
   * Set polygon offset for depth sorting of back faces.
   */
  setPolygonOffset(e) {
    this.back && (this.back.material.polygonOffsetUnits = e);
  }
  /**
   * Set Z-axis scale for GDS extrusion visualization.
   * Recursively scales all meshes and adjusts positions.
   */
  setZScale(e) {
    const t = (i, n, s, a = !0) => {
      for (const o of i.children)
        "isMesh" in o || "isLine" in o ? (o.scale.z = e, a && o.parent && (o.parent.position.z = n * e)) : "isGroup" in o && t(o, n, s, !o.name.startsWith("clipping"));
    };
    (this.front || this.back || this.edges) && t(this, this.minZ, this.height);
  }
  /**
   * Mark all materials as needing update.
   */
  updateMaterials(e) {
    this.back && (this.back.material.needsUpdate = e), this.front && (this.front.material.needsUpdate = e), this.edgeMaterial && (this.edgeMaterial.needsUpdate = e), this.vertices && (this.vertices.material.needsUpdate = e);
  }
  /**
   * Remove and dispose all clipping groups from this object.
   */
  clearClipping() {
    for (const [, e] of this.clipping)
      this.remove(e), ct(e);
    this.clipping.clear();
  }
  /**
   * Enable or disable zebra stripe visualization on front faces.
   */
  setZebra(e) {
    if (this.front) {
      const t = this.front.material.visible;
      e ? this.zebra.applyToMesh(this.front, t) : this.zebra.restoreMesh(this.front, t);
    }
  }
  /**
   * Set the number of zebra stripes.
   */
  setZebraCount(e) {
    this.zebra.setStripeCount(e);
  }
  /**
   * Set the opacity of zebra stripes.
   */
  setZebraOpacity(e) {
    this.zebra.setStripeOpacity(e);
  }
  /**
   * Set the direction/angle of zebra stripes.
   */
  setZebraDirection(e) {
    this.zebra.setStripeDirection(e);
  }
  /**
   * Set the color scheme for zebra stripes.
   */
  setZebraColorScheme(e) {
    this.zebra.setColorScheme(e);
  }
  /**
   * Set the mapping mode for zebra stripes.
   */
  setZebraMappingMode(e) {
    this.zebra.setMappingMode(e);
  }
}
function fs(r) {
  return r != null && "isObjectGroup" in r && r.isObjectGroup === !0;
}
function nw(r) {
  return "geometry" in r && r.geometry instanceof Ue ? r.geometry : null;
}
class _s extends Tt {
  /**
   * Expand the bounding box to include an object.
   * For ObjectGroup instances, only the first mesh (faces) is considered.
   * Clipping plane meshes (PlaneMeshes/StencilPlane) are excluded.
   */
  expandByObject(e, t = !1) {
    if (e.updateWorldMatrix(!1, !1), fs(e))
      return this.expandByObject(e.children[0], t), this;
    const i = nw(e);
    if (i !== null)
      if (t && i.attributes !== void 0 && i.attributes.position !== void 0)
        if (e.type.startsWith("LineSegment")) {
          const s = i.clone();
          s.applyMatrix4(e.matrixWorld), s.boundingBox = null, s.computeBoundingBox(), this.union(s.boundingBox), s.dispose();
        } else {
          const s = i.attributes.position;
          for (let a = 0, o = s.count; a < o; a++)
            To.fromBufferAttribute(s, a).applyMatrix4(e.matrixWorld), this.expandByPoint(To);
        }
      else
        i.boundingBox === null && i.computeBoundingBox(), ph.copy(i.boundingBox), ph.applyMatrix4(e.matrixWorld), this.union(ph);
    const n = e.children;
    for (let s = 0, a = n.length; s < a; s++) {
      const o = n[s];
      o.name === "PlaneMeshes" && o.children && o.children.length > 0 && o.children[0].type.startsWith("StencilPlane") || this.expandByObject(o, t);
    }
    return this;
  }
  /**
   * Calculate the maximum distance from the origin to any corner of the box.
   */
  max_dist_from_center() {
    return Math.max(...this.min.toArray().concat(this.max.toArray()).map((e) => Math.abs(e)));
  }
  /**
   * Get the bounding sphere of this box.
   */
  boundingSphere() {
    return this.getBoundingSphere(Hp), Hp;
  }
  /**
   * Get the center point of this box as an array.
   */
  center() {
    return this.getCenter(To), ji(To.toArray());
  }
}
class sw extends ei {
  /**
   * Create a BoxHelper for visualizing an object's bounding box.
   */
  constructor(e, t = 16776960) {
    const i = new Uint16Array([
      0,
      1,
      1,
      2,
      2,
      3,
      3,
      0,
      4,
      5,
      5,
      6,
      6,
      7,
      7,
      4,
      0,
      4,
      1,
      5,
      2,
      6,
      3,
      7
    ]), n = new Float32Array(8 * 3), s = new Ue();
    s.setIndex(new it(i, 1)), s.setAttribute("position", new it(n, 3)), super(s, new It({ color: t, toneMapped: !1 })), this.object = e, this.type = "BoxHelper", this.matrixAutoUpdate = !1, this.update();
  }
  /**
   * Update the helper geometry to match the current bounding box.
   * Should be called when the target object changes.
   */
  update() {
    if (this.object !== void 0 && Ao.setFromObject(this.object, !0), Ao.isEmpty())
      return;
    const e = Ao.min, t = Ao.max, i = this.geometry.attributes.position, n = i.array;
    n[0] = t.x, n[1] = t.y, n[2] = t.z, n[3] = e.x, n[4] = t.y, n[5] = t.z, n[6] = e.x, n[7] = e.y, n[8] = t.z, n[9] = t.x, n[10] = e.y, n[11] = t.z, n[12] = t.x, n[13] = t.y, n[14] = e.z, n[15] = e.x, n[16] = t.y, n[17] = e.z, n[18] = e.x, n[19] = e.y, n[20] = e.z, n[21] = t.x, n[22] = e.y, n[23] = e.z, i.needsUpdate = !0, this.geometry.computeBoundingSphere();
  }
  /**
   * Set the target object and update the helper.
   */
  setFromObject(e) {
    return this.object = e, this.update(), this;
  }
  /**
   * Dispose of geometry and material resources.
   */
  dispose() {
    Wd(this.geometry);
  }
}
const To = new b(), ph = new _s(), Ao = new _s(), Hp = new Lt();
class rw {
  /**
   * Create a MaterialFactory instance.
   */
  constructor(e = {}) {
    this.defaultOpacity = e.defaultOpacity ?? 1, this.metalness = e.metalness ?? 0.3, this.roughness = e.roughness ?? 0.65, this.edgeColor = e.edgeColor ?? 7368816, this.transparent = e.transparent ?? !1;
  }
  /**
   * Create base properties shared by all face materials.
   */
  _createBaseProps(e) {
    return {
      polygonOffset: !0,
      polygonOffsetFactor: 1,
      polygonOffsetUnits: 1,
      transparent: !0,
      opacity: this.transparent ? this.defaultOpacity * e : e,
      depthWrite: !this.transparent,
      depthTest: !0,
      clipIntersection: !1
    };
  }
  /**
   * Create a standard material for front faces with PBR properties.
   */
  createFrontFaceMaterial({ color: e, alpha: t, visible: i = !0 }, n) {
    const s = new Bn({
      ...this._createBaseProps(t),
      color: e,
      metalness: this.metalness,
      roughness: this.roughness,
      flatShading: !1,
      side: Di,
      visible: i
    });
    return Ut.track("material", s, n ?? "MeshStandardMaterial (front face)"), s;
  }
  /**
   * Create a standard material for back faces with PBR properties.
   * Used for polygon rendering where back faces need full shading.
   */
  createBackFaceStandardMaterial({ color: e, alpha: t, polygonOffsetUnits: i = 2, visible: n = !0 }, s) {
    const a = new Bn({
      ...this._createBaseProps(t),
      color: e,
      metalness: this.metalness,
      roughness: this.roughness,
      flatShading: !1,
      side: zt,
      visible: n
    });
    return a.polygonOffsetUnits = i, Ut.track("material", a, s ?? "MeshStandardMaterial (back face)"), a;
  }
  /**
   * Create a basic material for back faces (no lighting/PBR).
   * Used for shape rendering where back faces are simple fills.
   */
  createBackFaceBasicMaterial({ color: e, alpha: t, polygonOffsetUnits: i = 2, visible: n = !0 }, s) {
    const a = new Ht({
      ...this._createBaseProps(t),
      color: e,
      side: zt,
      visible: n
    });
    return a.polygonOffsetUnits = i, Ut.track("material", a, s ?? "MeshBasicMaterial (back face)"), a;
  }
  /**
   * Create a basic front face material (no PBR, for simple shapes).
   */
  createBasicFaceMaterial({ color: e, alpha: t, visible: i = !0 }, n) {
    const s = new Ht({
      ...this._createBaseProps(t),
      color: e,
      side: Di,
      visible: i
    });
    return Ut.track("material", s, n ?? "MeshBasicMaterial (front face)"), s;
  }
  /**
   * Create a fat line material (LineMaterial from Three.js examples).
   */
  createEdgeMaterial({ lineWidth: e, color: t, vertexColors: i = !1, visible: n = !0, resolution: s }, a) {
    const o = new _c({
      linewidth: e,
      transparent: !0,
      depthWrite: !this.transparent,
      depthTest: !this.transparent,
      clipIntersection: !1,
      vertexColors: i,
      // boolean, not string "VertexColors"
      toneMapped: !1
      // critical for correct vertex colors
    });
    return i || (o.color = new oe(t ?? this.edgeColor)), o.visible = n, s && o.resolution.set(s.width, s.height), Ut.track("material", o, a ?? "LineMaterial (edges)"), o;
  }
  /**
   * Create a basic line material for simple edges (e.g., polygon outlines).
   */
  createSimpleEdgeMaterial({ color: e, visible: t = !0 }, i) {
    const n = new It({
      color: e ?? this.edgeColor,
      depthWrite: !this.transparent,
      depthTest: !this.transparent,
      visible: t
    });
    return Ut.track("material", n, i ?? "LineBasicMaterial (simple edges)"), n;
  }
  /**
   * Create a point material for vertex rendering.
   */
  createVertexMaterial({ size: e, color: t, visible: i = !0 }, n) {
    const s = new tc({
      color: t ?? this.edgeColor,
      sizeAttenuation: !1,
      size: e,
      transparent: !0,
      clipIntersection: !1,
      visible: i
    });
    return Ut.track("material", s, n ?? "PointsMaterial (vertices)"), s;
  }
  /**
   * Create a basic material for texture-mapped surfaces.
   */
  createTextureMaterial({ texture: e, visible: t = !0 }, i) {
    const n = new Ht({
      color: "#ffffff",
      map: e,
      side: ri,
      visible: t
    });
    return Ut.track("material", n, i ?? "MeshBasicMaterial (textured)"), n;
  }
  /**
   * Update global settings.
   */
  update(e) {
    e.metalness !== void 0 && (this.metalness = e.metalness), e.roughness !== void 0 && (this.roughness = e.roughness), e.transparent !== void 0 && (this.transparent = e.transparent), e.defaultOpacity !== void 0 && (this.defaultOpacity = e.defaultOpacity), e.edgeColor !== void 0 && (this.edgeColor = e.edgeColor);
  }
}
function aw(r) {
  return "parts" in r;
}
class yg extends li {
  constructor() {
    super(...arguments), this.type = "CompoundGroup", this.isCompoundGroup = !0;
  }
}
class ow {
  /**
   * Create a NestedGroup for rendering CAD geometry.
   * @param shapes - The tessellated shape data to render.
   * @param width - Canvas/viewport width for line material resolution.
   * @param height - Canvas/viewport height for line material resolution.
   * @param edgeColor - Default edge color as hex value (e.g., 0x000000).
   * @param transparent - Whether to render shapes with transparency.
   * @param opacity - Default opacity value (0.0 to 1.0).
   * @param metalness - Material metalness value (0.0 to 1.0).
   * @param roughness - Material roughness value (0.0 to 1.0).
   * @param normalLen - Length for vertex normal helpers (0 to disable).
   * @param bb_max - Maximum bounding box dimension.
   */
  constructor(e, t, i, n, s, a, o, l, c, h = 0) {
    this.shapes = e, this.width = t, this.height = i, this.edgeColor = n, this.transparent = s, this.metalness = o, this.roughness = l, this.defaultOpacity = a, this.normalLen = c, this.blackEdges = !1, this.backVisible = !1, this.bb_max = h, this.delim = "|", this.rootGroup = null, this.instances = null, this.bbox = null, this.bsphere = null, this.groups = {}, this.clipPlanes = null, this.materialFactory = new rw({
      defaultOpacity: a,
      metalness: o,
      roughness: l,
      edgeColor: n,
      transparent: s
    });
  }
  /**
   * Dispose of all resources and clean up memory.
   */
  dispose() {
    Object.keys(this.groups).length > 0 && (ct(Object.values(this.groups)), this.groups = {}), this.rootGroup && (ct(this.rootGroup), this.rootGroup = null);
  }
  /**
   * Check if array is nested (number[][]).
   */
  _isNestedArray(e) {
    return e.length > 0 && Array.isArray(e[0]);
  }
  /**
   * Convert array data to Float32Array, detecting nested arrays at runtime.
   */
  _toFloat32Array(e, t = 1) {
    return e instanceof Float32Array ? e : this._isNestedArray(e) ? new Float32Array(qh(e, t)) : new Float32Array(e);
  }
  /**
   * Convert array data to Uint32Array, detecting nested arrays at runtime.
   */
  _toUint32Array(e, t = 1) {
    return e instanceof Uint32Array ? e : this._isNestedArray(e) ? new Uint32Array(qh(e, t)) : new Uint32Array(e);
  }
  /**
   * Internal method to render edge geometry as fat lines.
   */
  _renderEdges(e, t, i, n, s) {
    const a = this._toFloat32Array(e, 3), o = Ut.trackGeometry(new mg(), s ? `LineSegmentsGeometry for ${s}` : "LineSegmentsGeometry (edges)");
    if (o.setPositions(a), Array.isArray(i)) {
      const h = i.map((d) => {
        const u = new oe(d);
        return [u.r, u.g, u.b, u.r, u.g, u.b];
      }).flat();
      o.setColors(new Float32Array(h));
    }
    const l = this.materialFactory.createEdgeMaterial({
      lineWidth: t,
      color: Array.isArray(i) ? null : i ?? this.edgeColor,
      vertexColors: Array.isArray(i),
      visible: n == 1,
      resolution: { width: this.width, height: this.height }
    }, s ? `LineMaterial for ${s}` : "LineMaterial (edges)"), c = new Gd(o, l);
    return c.renderOrder = 999, c;
  }
  /**
   * Render standalone edge geometry (not associated with a face).
   */
  renderEdges(e, t, i, n, s, a, o = null) {
    const l = Array.isArray(i) ? this.edgeColor : i ?? this.edgeColor, c = new Mi(this.defaultOpacity, 1, l, o, "edges"), h = this._renderEdges(e.edges, t, i, a, n);
    return s && (h.name = s), c.setEdges(h), this.groups[n] = c, c.name = n.replaceAll("/", this.delim), c;
  }
  /**
   * Render vertex points as a point cloud.
   */
  renderVertices(e, t, i, n, s, a, o = null) {
    const l = new Mi(this.defaultOpacity, 1, i ?? this.edgeColor, o, "vertices"), c = this._toFloat32Array(e.obj_vertices), h = Ut.trackGeometry(new Ue(), `BufferGeometry (vertices) for ${n}`);
    h.setAttribute("position", new ve(c, 3));
    const d = this.materialFactory.createVertexMaterial({
      size: t,
      color: i,
      visible: a == 1
    }, `PointsMaterial for ${n}`), u = new pd(h, d);
    return s && (u.name = s), l.setVertices(u), this.groups[n] = l, l.name = n.replaceAll("/", this.delim), l;
  }
  /**
   * Render a tessellated 3D shape with front/back faces and optional edges.
   */
  renderShape(e, t, i, n, s, a, o, l, c = null, h = null, d = null, u = null, p = null) {
    const m = this._toFloat32Array(e.vertices), _ = this._toFloat32Array(e.normals), g = this._toUint32Array(e.triangles), f = new Mi(this.defaultOpacity, i ?? 1, this.edgeColor, c, h, n);
    this.groups[a] = f, f.name = a.replaceAll("/", this.delim), i == null ? i = 1 : i < 1 && (this.transparent = !0);
    let v, x = null, y;
    if (d != null) {
      const w = `data:image/${d.format};base64,${d.data}`, L = new Image();
      v = Ut.trackGeometry(new Vn(u, p), `PlaneGeometry (textured) for ${a}`), x = Ut.trackTexture(new Et(L), `Texture for ${a}`), x.colorSpace = Qt, L.onload = () => {
        x.needsUpdate = !0;
      }, L.src = w, y = this.materialFactory.createTextureMaterial({ texture: x }, `MeshBasicMaterial (textured) for ${a}`), n = !1;
    } else
      v = Ut.trackGeometry(new Ue(), `BufferGeometry (shape) for ${a}`), v.setAttribute("position", new it(m, 3)), v.setAttribute("normal", new it(_, 3)), v.setIndex(new it(g, 1)), f.shapeGeometry = v, y = this.materialFactory.createFrontFaceMaterial({
        color: t,
        alpha: i,
        visible: l[0] == 1
      }, `MeshStandardMaterial (front) for ${a}`), y.name = "frontMaterial";
    const A = f.subtype === "solid" && !s ? t : new oe(this.edgeColor).lerp(new oe(1, 1, 1), 0.15).getHex(), S = this.materialFactory.createBackFaceBasicMaterial({
      color: A,
      alpha: i,
      visible: l[0] == 1 && (n || this.backVisible)
    }, `MeshBasicMaterial (back) for ${a}`);
    S.name = "backMaterial";
    const C = new Je(v, S);
    C.name = o;
    const P = new Je(v, y);
    if (P.name = o, i < 1 && (C.renderOrder = 999, P.renderOrder = 999), P.geometry.boundingBox == null && P.geometry.computeBoundingBox(), f.setBack(C), f.setFront(P), this.normalLen > 0) {
      const w = new qM(P, this.normalLen, 16711935);
      f.add(w);
    }
    const E = e.edges;
    if (E && E.length > 0) {
      const w = this._renderEdges(E, 1, null, l[1], a);
      w.name = o, f.setEdges(w);
    }
    return f;
  }
  /**
   * Create edge geometry from extruded polygons.
   */
  _createEdgesFromPolygons(e, t) {
    const i = [], n = [];
    let s = 0;
    for (let o = 0; o < e.length; o++) {
      const c = e[o].getPoints(), h = c.map((p) => new b(p.x, p.y, 0)), d = c.map((p) => new b(p.x, p.y, t)), u = (p) => {
        for (let m = 0; m < p.length; m++) {
          const _ = (m + 1) % p.length;
          n.push(s + m, s + _);
        }
        i.push(...p), s += p.length;
      };
      u(h), u(d);
      for (let p = 0; p < c.length; p++)
        n.push(
          s - 2 * c.length + p,
          // Bottom point index
          s - c.length + p
        );
    }
    const a = new Ue();
    return a.setFromPoints(i), a.setIndex(n), a;
  }
  /**
   * Render extruded 2D polygons (GDS format) as 3D geometry.
   */
  renderPolygons(e, t, i, n, s, a, o, l, c, h = null, d = null) {
    const u = new Mi(this.defaultOpacity, 1, this.edgeColor, h, d, s);
    u.name = o.replaceAll("/", this.delim), u.minZ = t, u.height = e.height, this.groups[o] = u;
    const p = [];
    let m;
    e.matrices && e.matrices.length > 0 ? m = e.matrices : m = [1, 0, 0, 0, 1, 0];
    for (const P of e.refs) {
      const E = this.instances[P], w = E.length / 2, L = new Array(w);
      for (let N = 0; N < m.length / 6; N++) {
        const B = m[6 * N], W = m[6 * N + 1], Z = m[6 * N + 2], X = m[6 * N + 3], ie = m[6 * N + 4], G = m[6 * N + 5];
        for (let me = 0; me < w; me++)
          L[me] = new H(B * E[2 * me] + W * E[2 * me + 1] + Z, X * E[2 * me] + ie * E[2 * me + 1] + G);
        const he = new Nn(L);
        p.push(he);
      }
    }
    const _ = {
      depth: e.height,
      bevelEnabled: !1
    }, g = Ut.trackGeometry(new wa(p, _), `ExtrudeGeometry (polygon) for ${o}`), f = this.materialFactory.createFrontFaceMaterial({
      color: i,
      alpha: n,
      visible: c[0] == 1
    }, `MeshStandardMaterial (front polygon) for ${o}`);
    f.name = "frontMaterial";
    const v = this.materialFactory.createBackFaceStandardMaterial({
      color: i,
      alpha: n,
      visible: c[0] == 1 && (s || this.backVisible)
    }, `MeshStandardMaterial (back polygon) for ${o}`);
    v.name = "backMaterial";
    const x = new Je(g, v);
    x.name = l;
    const y = new Je(g, f);
    y.name = l;
    const A = Ut.trackGeometry(this._createEdgesFromPolygons(p, e.height), `BufferGeometry (polygon edges) for ${o}`), S = this.materialFactory.createSimpleEdgeMaterial({}, `LineBasicMaterial (polygon edges) for ${o}`), C = new ei(A, S);
    return u.shapeGeometry = g, u.setFront(y), u.setBack(x), u.setEdges(C), u;
  }
  /**
   * Recursively render all shapes in the shape tree.
   * Note: The shapes parameter uses the public Shapes type but internally
   * contains ShapeEntry/ShapeTree data after decomposition by viewer._decompose()
   */
  renderLoop(e) {
    const t = (n, s, a, o) => {
      let l;
      switch (n.type) {
        case "edges":
          l = this.renderEdges(n.shape, n.width, n.color, n.id, n.name, n.state[1], { topo: "edge", geomtype: n.geomtype || null });
          break;
        case "vertices":
          l = this.renderVertices(n.shape, n.size, n.color ?? null, n.id, n.name, n.state[1], { topo: "vertex", geomtype: null });
          break;
        case "polygon":
          l = this.renderPolygons(
            n.shape,
            n.loc[0][2],
            n.color ?? this.edgeColor,
            1,
            n.renderback == null ? !1 : n.renderback,
            !1,
            //exploded
            n.id,
            n.name,
            n.state,
            { topo: "face", geomtype: n.geomtype || null },
            n.subtype || null
          );
          break;
        default: {
          const c = Array.isArray(n.color) ? n.color[0] : n.color;
          l = this.renderShape(n.shape, c ?? this.edgeColor, n.alpha ?? null, n.renderback == null ? !1 : n.renderback, n.exploded ?? !1, n.id, n.name, n.state, { topo: "face", geomtype: n.geomtype || null }, n.subtype || null, s, a, o);
        }
      }
      return n.loc != null && (l.position.set(...n.loc[0]), l.quaternion.set(...n.loc[1])), l;
    }, i = new yg();
    e.loc == null && (e.loc = [
      [0, 0, 0],
      [0, 0, 0, 1]
    ]), i.position.set(...e.loc[0]), i.quaternion.set(...e.loc[1]), this.groups[e.id] = i, i.name = e.id.replaceAll("/", "|");
    for (const n of e.parts)
      if (aw(n))
        i.add(this.renderLoop(n));
      else {
        const s = n, a = s.texture != null, o = a ? s.texture.image : null, l = a ? s.texture.width : null, c = a ? s.texture.height : null, h = t(s, o, l, c);
        this.groups[s.id] = h, i.add(h);
      }
    return i;
  }
  /**
   * Main entry point to render all shapes.
   */
  render() {
    return this.shapes.format == "GDS" && (this.instances = this.shapes.instances || null), this.rootGroup = this.renderLoop(this.shapes), this.rootGroup;
  }
  /**
   * Get the bounding box of all rendered geometry.
   */
  boundingBox() {
    return this.bbox == null && (this.bbox = new _s(), this.bbox.setFromObject(this.rootGroup, !1)), this.bbox;
  }
  /**
   * Traverse all ObjectGroup instances and call a method on each.
   * Note: Uses dynamic dispatch for methods that exist on ObjectGroup.
   */
  // eslint-disable-next-line @typescript-eslint/no-explicit-any
  _traverse(e, t) {
    for (const i in this.groups) {
      const n = this.groups[i];
      if (n instanceof Mi) {
        const s = n[e];
        typeof s == "function" && s.call(n, t);
      }
    }
  }
  /**
   * Get all currently selected ObjectGroup instances.
   */
  selection() {
    const e = [];
    for (const t in this.groups)
      for (const i of this.groups[t].children)
        i instanceof Mi && i.isSelected && e.push(i);
    return e;
  }
  /**
   * Clear selection and highlights from all selected objects.
   */
  clearSelection() {
    for (const e of this.selection())
      e.clearHighlights();
  }
  /**
   * Set metalness value for all materials.
   */
  setMetalness(e) {
    this.metalness = e, this.materialFactory.update({ metalness: e }), this._traverse("setMetalness", e);
  }
  /**
   * Set roughness value for all materials.
   */
  setRoughness(e) {
    this.roughness = e, this.materialFactory.update({ roughness: e }), this._traverse("setRoughness", e);
  }
  /**
   * Enable or disable transparency for all shapes.
   */
  setTransparent(e) {
    this.transparent = e, this.materialFactory.update({ transparent: e }), this._traverse("setTransparent", e);
  }
  /**
   * Set whether edges should be rendered in black.
   */
  setBlackEdges(e) {
    this.blackEdges = e, this._traverse("setBlackEdges", e);
  }
  /**
   * Set visibility of back faces.
   */
  setBackVisible(e) {
    this.backVisible = e, this._traverse("setBackVisible", e);
  }
  /**
   * Set the edge color for all shapes.
   */
  setEdgeColor(e) {
    this.edgeColor = e, this._traverse("setEdgeColor", e);
  }
  /**
   * Set the opacity for all shapes.
   */
  setOpacity(e) {
    this.defaultOpacity = e, this._traverse("setOpacity", e);
  }
  /**
   * Set clip intersection mode for all materials.
   */
  setClipIntersection(e) {
    this._traverse("setClipIntersection", e);
  }
  /**
   * Set clipping planes for all materials.
   */
  setClipPlanes(e) {
    this.clipPlanes = e, this._traverse("setClipPlanes", e);
  }
  /**
   * Set polygon offset for depth sorting.
   */
  setPolygonOffset(e) {
    this._traverse("setPolygonOffset", e);
  }
  /**
   * Set Z-axis scale for all shapes (used for GDS extrusion visualization).
   */
  setZScale(e) {
    this._traverse("setZScale", e);
  }
  /**
   * Reset minimum Z position for all shapes.
   */
  setMinZ() {
    this._traverse("setMinZ");
  }
  /**
   * Mark all materials as needing update.
   */
  updateMaterials() {
    this._traverse("updateMaterials", !0);
  }
  /**
   * Enable or disable zebra stripe visualization.
   */
  setZebra(e) {
    this._traverse("setZebra", e);
  }
  /**
   * Set the number of zebra stripes.
   */
  setZebraCount(e) {
    this._traverse("setZebraCount", e);
  }
  /**
   * Set the opacity of zebra stripes.
   */
  setZebraOpacity(e) {
    this._traverse("setZebraOpacity", e);
  }
  /**
   * Set the direction/angle of zebra stripes.
   */
  setZebraDirection(e) {
    this._traverse("setZebraDirection", e);
  }
  /**
   * Set the color scheme for zebra stripes.
   */
  setZebraColorScheme(e) {
    this._traverse("setZebraColorScheme", e);
  }
  /**
   * Set the mapping mode for zebra stripes.
   */
  setZebraMappingMode(e) {
    this._traverse("setZebraMappingMode", e);
  }
}
function lw(r) {
  return r != null && "isCompoundGroup" in r && r.isCompoundGroup === !0;
}
function cw(r, e, t, i, n) {
  const s = (i - e) / (t - r);
  return n < r ? e : n > t ? i : s * (n - r) + e;
}
function Vp(r) {
  let e = r.replace(/(\.\d*[1-9])0+$/, "$1").replace(/\.0+$/, "");
  return e === "-0" && (e = "0"), e.indexOf(".") < 0 && (e = `${e}.0`), e;
}
class hw extends tt {
  /**
   * Create a GridHelper
   * @param size - Total size of the grid (width and height)
   * @param divisions - Number of divisions (grid lines)
   * @param colorX - Color for the X-axis centerline
   * @param colorY - Color for the Y-axis centerline
   * @param colorGrid - Color for the dashed grid lines
   */
  constructor(e, t, i, n, s) {
    super();
    const a = e / t, o = e / 2, l = [], c = [], h = [];
    let d = !1, u = !1;
    for (let S = 0; S <= t; S++) {
      const C = -o + S * a, P = Math.abs(C) < 1e-10;
      P ? u || (h.push(-o, 0, 0, o, 0, 0), u = !0) : l.push(-o, 0, C, o, 0, C), P ? d || (c.push(0, 0, -o, 0, 0, o), d = !0) : l.push(C, 0, -o, C, 0, o);
    }
    u || h.push(-o, 0, 0, o, 0, 0), d || c.push(0, 0, -o, 0, 0, o);
    const p = new Ue();
    p.setAttribute("position", new ve(l, 3));
    const m = p.getAttribute("position"), _ = new Float32Array(m.count);
    for (let S = 0; S < m.count; S += 2) {
      const C = m.getX(S), P = m.getY(S), E = m.getZ(S), w = m.getX(S + 1), L = m.getY(S + 1), N = m.getZ(S + 1);
      _[S] = 0, _[S + 1] = Math.sqrt((w - C) ** 2 + (L - P) ** 2 + (N - E) ** 2);
    }
    p.setAttribute("lineDistance", new it(_, 1));
    const g = new Td({
      color: s,
      dashSize: a / 20,
      gapSize: a / 20,
      opacity: 1,
      transparent: !1,
      vertexColors: !1
    }), f = new ei(p, g);
    this.add(f);
    const v = new Ue();
    v.setAttribute("position", new ve(c, 3));
    const x = new It({ color: i });
    this.add(new ei(v, x));
    const y = new Ue();
    y.setAttribute("position", new ve(h, 3));
    const A = new It({ color: n });
    this.add(new ei(y, A));
  }
}
class dw extends li {
  /**
   * Create a Grid instance
   * @param options - Configuration options
   */
  constructor(e) {
    super();
    const t = [
      "bbox",
      "gridFontSize",
      "grid",
      "theme",
      "cadWidth",
      "height",
      "maxAnisotropy",
      "getCamera",
      "getAxes0"
    ];
    for (const S of t)
      if (e[S] === void 0)
        throw new Error(`Grid: required option "${S}" is missing`);
    const { bbox: i, ticks: n = 5, gridFontSize: s, centerGrid: a, axes0: o, grid: l, flipY: c, theme: h, cadWidth: d, height: u, maxAnisotropy: p, tickValueElement: m, tickInfoElement: _, getCamera: g, getAxes0: f, onGridChange: v } = e;
    this.ticks = n, this.ticks0 = n, this.gridFontSize = s, this.bbox = i, this.centerGrid = a || !1, this.axes0 = o || !1, this.grid = l, this.allGrid = !!(l[0] || l[1] || l[2]), this.theme = h, this.flipY = c || !1, this.lastZoomIndex = 0, this.lastFontIndex = 50, this.cadWidth = d, this.height = u, this.maxAnisotropy = p, this.tickValue = m || null, this.info = _ || null, this.getCamera = g, this.getAxes0 = f, this.onGridChange = v || null;
    const x = i.max_dist_from_center(), y = Math.min(d, u), A = Math.max(1, 6 - Math.log2(y / 100));
    this.minFontIndex = Math.round((x < 2 ? 6 : x < 1e3 ? 5 : 3) * A), this.minZoomIndex = -4, this.zoomMaxIndex = 5, this.canvasHeight = 128, this.geomCache = {}, this.textureAspectRatios = {}, this.labelCache = {}, this.materialCache = {}, this.size = 0, this.delta = 0, this.colors = {
      dark: [
        "#ff4500",
        // x
        "#32cd32",
        // y
        "#3b9eff"
        // z
      ],
      light: [
        "#ff4500",
        // x
        "#32cd32",
        // y
        "#3b9eff"
        // z
      ]
    }, this.create();
  }
  /**
   * Calculate text scale based on camera mode and canvas size
   */
  calculateTextScale(e) {
    const t = this.getCamera();
    if (!t)
      return e;
    const i = this.height, n = cw(300, 0.8, 800, 1, i) * e;
    if (t instanceof kn) {
      const s = (t.top - t.bottom) / t.zoom, a = i / s;
      return n / a * 1.6;
    } else
      return n / i * 0.6;
  }
  /**
   * Update scale of all grid labels
   */
  scaleLabels() {
    for (const e of this.children)
      if (e instanceof li)
        for (let t = 1; t < e.children.length; t++) {
          const i = e.children[t];
          if (!(i instanceof Qr))
            continue;
          const n = this.calculateTextScale(this.gridFontSize), s = i.userData.aspectRatio || 4;
          i.scale.set(n * s, n, 1);
        }
  }
  /**
   * Show or hide all grid labels
   */
  showLabels(e) {
    for (const t of this.children)
      if (t instanceof li)
        for (let i = 1; i < t.children.length; i++)
          t.children[i].visible = e;
  }
  /**
   * Update grid based on zoom level
   * @param zoom - Current zoom level
   * @param force - Force update regardless of zoom change
   * @param theme - Optional new theme to apply
   */
  async update(e, t = !1, i = null) {
    if (!this.getVisible())
      return;
    i && (this.theme = i);
    let n = Math.round(Math.log2(0.4 * e));
    if (Math.abs(n) < 1e-6 && (n = 0), t || n != this.lastZoomIndex && n < this.zoomMaxIndex && n > this.minZoomIndex) {
      ct(this.children), this.children = [];
      const a = this.ticks0 / 2 * 2 ** n;
      this.ticks = Math.round(2 * a), await this.create(!1), this.lastZoomIndex = n, t = !0;
    }
    const s = Math.round(e * 50);
    (t || s != this.lastFontIndex) && (s < this.minFontIndex ? this.showLabels(!1) : (this.getCamera() instanceof kn && this.scaleLabels(), this.showLabels(!0)), this.lastFontIndex = s);
  }
  /**
   * Create the grid geometry and labels
   * @param nice - Whether to use nice bounds calculation
   */
  async create(e = !0) {
    if (e) {
      const t = Math.max(Math.abs(this.bbox.max.x), Math.abs(this.bbox.max.y), Math.abs(this.bbox.max.z), Math.abs(this.bbox.min.x), Math.abs(this.bbox.min.y), Math.abs(this.bbox.min.z)), [i, n, s] = this.niceBounds(-t * 1.05, t * 1.05, this.ticks);
      this.size = n - i, this.ticks = this.size / s, this.ticks0 = this.ticks, this.delta = s;
    } else
      this.delta = this.size / this.ticks;
    this.setTickInfo();
    for (let t = 0; t < 3; t++) {
      const i = new yg();
      i.name = `GridHelper-${t}`, i.add(new hw(this.size, 2 * this.ticks, this.colors[this.theme][t === 0 ? 1 : t === 1 ? 0 : 2], this.colors[this.theme][t === 0 ? 0 : t === 1 ? 2 : 1], this.theme == "dark" ? 125269879 : 12303291));
      let n;
      for (let s = -this.size / 2; s <= this.size / 2; s += this.delta / 2) {
        if (Math.abs(s) < 1e-6)
          continue;
        let a = Vp(s.toFixed(4));
        s > 0 && (a = "+" + a), n = this.createLabel(a, s, t, !0), i.add(n), n = this.createLabel(a, s, t, !1), i.add(n);
      }
      this.add(i);
    }
    this.children[0].rotateX(Math.PI / 2), this.children[1].rotateY(Math.PI / 2), this.children[2].rotateZ(Math.PI / 2), this.setCenter(this.axes0, this.flipY), this.scaleLabels(), this.setCenter(this.getAxes0(), this.flipY), this.setVisible();
  }
  /**
   * Create a text texture for grid labels
   */
  createTextTexture(e) {
    if (this.geomCache[e])
      return this.geomCache[e];
    const t = document.createElement("canvas"), i = t.getContext("2d", {
      alpha: !0,
      desynchronized: !1,
      willReadFrequently: !1
    }), n = 80, s = 12, o = `${this.theme === "dark" ? "500" : "560"} ${n}px Verdana, Arial, sans-serif`;
    i.font = o;
    const c = i.measureText(e).width, d = Math.round(c + 20 * 2), u = this.canvasHeight;
    t.width = d, t.height = u, i.textRendering = "optimizeLegibility", i.font = o, i.textAlign = "center", i.textBaseline = "middle", i.clearRect(0, 0, t.width, t.height);
    const p = t.width / 2, m = t.height / 2;
    i.lineWidth = s, i.lineJoin = "round", i.miterLimit = 2, i.strokeStyle = this.theme === "dark" ? "#444444" : "#ffffff", i.strokeText(e, p, m), i.fillStyle = this.theme === "dark" ? "#aaaaaa" : "#333333", i.fillText(e, p, m);
    const _ = new fd(t);
    return _.needsUpdate = !0, _.colorSpace = this.theme === "dark" ? Qt : On, _.minFilter = Pt, _.magFilter = Pt, _.generateMipmaps = !1, _.anisotropy = this.maxAnisotropy, _.premultiplyAlpha = !1, _.wrapS = fi, _.wrapT = fi, this.geomCache[e] = _, this.textureAspectRatios[e] = d / u, _;
  }
  /**
   * Create a label sprite for grid axis
   */
  createLabel(e, t, i, n) {
    const s = `${e}_${i}_${n}`;
    if (this.labelCache[s]) {
      const p = this.labelCache[s], m = new Qr(p.material);
      return m.position.copy(p.position), m.scale.copy(p.scale), m.userData.aspectRatio = p.userData.aspectRatio, m;
    }
    const a = this.createTextTexture(e);
    let o = 0;
    i === 0 ? o = 0 : i === 1 ? o = n ? Math.PI / 2 : 0 : o = n ? 0 : Math.PI / 2;
    const l = `${e}_${i}_${n}`;
    let c = this.materialCache[l];
    c || (c = new Jl({
      map: a,
      transparent: !0,
      depthTest: !0,
      depthWrite: !1,
      blending: Dn,
      rotation: o,
      sizeAttenuation: !1
      // Disable distance scaling - maintain constant screen size
    }), this.materialCache[l] = c);
    const h = new Qr(c);
    let d;
    i === 0 ? d = n ? 1 : -1 : i === 1 ? d = n ? -1 : 1 : d = 1, n ? h.position.set(d * t, 0, 0) : h.position.set(0, 0, d * t);
    const u = this.textureAspectRatios[e] || 4;
    return h.scale.set(u, 1, 1), h.userData.aspectRatio = u, this.labelCache[s] = h, h;
  }
  /**
   * Calculate nice symmetric grid bounds centered at zero
   */
  niceBounds(e, t, i) {
    i || (i = 8);
    const n = Math.max(Math.abs(e), Math.abs(t));
    if (n === 0)
      return [0, 0, 0];
    const s = n / i, a = Math.floor(Math.log10(s)), o = Math.pow(10, a), l = s / o;
    let c;
    l <= 1 ? c = 1 : l <= 2 ? c = 2 : l <= 2.5 ? c = 2.5 : l <= 5 ? c = 5 : c = 10;
    const h = c * o, d = Math.ceil(n / h), u = h * d;
    return [-u, u, h];
  }
  /**
   * Compute grid visibility and notify UI
   */
  computeGrid() {
    this.allGrid = !!(this.grid[0] || this.grid[1] || this.grid[2]), this.onGridChange && this.onGridChange(this.allGrid, this.grid), this.setVisible();
  }
  /**
   * Toggle grid visibility by action
   * @param action - Action type ("grid", "grid-xy", "grid-xz", "grid-yz")
   * @param flag - Optional explicit flag for "grid" action
   */
  setGrid(e, t = null) {
    switch (e) {
      case "grid":
        this.allGrid = t ?? !this.allGrid, this.grid[0] = this.allGrid, this.grid[1] = this.allGrid, this.grid[2] = this.allGrid;
        break;
      case "grid-xy":
        this.grid[0] = !this.grid[0];
        break;
      case "grid-xz":
        this.grid[1] = !this.grid[1];
        break;
      case "grid-yz":
        this.grid[2] = !this.grid[2];
        break;
    }
    this.computeGrid();
  }
  /**
   * Set grid visibility for all planes
   * @param xy - XY plane visibility
   * @param xz - XZ plane visibility
   * @param yz - YZ plane visibility
   */
  setGrids(e, t, i) {
    this.grid[0] = e, this.grid[1] = t, this.grid[2] = i, this.computeGrid();
  }
  /**
   * Set grid center position
   * @param axes0 - Whether to center at origin
   * @param flipY - Whether Y axis is flipped
   */
  setCenter(e, t) {
    const i = e ? [0, 0, 0] : this.bbox.center();
    this.children.forEach((n) => n.position.set(i[0], i[1], i[2])), this.centerGrid || (this.children[0].position.z -= this.size / 2, this.children[1].position.y -= (t ? -1 : 1) * this.size / 2, this.children[2].position.x -= this.size / 2);
  }
  /**
   * Update visibility of grid planes and tick info
   */
  setVisible() {
    this.children.forEach((e, t) => {
      e.visible = this.grid[t];
    }), this.info && (this.info.style.display = this.allGrid ? "block" : "none");
  }
  /**
   * Update tick info display
   */
  setTickInfo() {
    this.tickValue && (this.tickValue.innerText = Vp((this.delta / 2).toFixed(4)));
  }
  /**
   * Get overall grid visibility
   * @returns Whether any grid plane is visible
   */
  getVisible() {
    return this.allGrid;
  }
  /**
   * Clear all caches (textures, materials, labels)
   */
  clearCache() {
    if (Object.keys(this.geomCache).length > 0) {
      for (const e of Object.keys(this.geomCache))
        this.geomCache[e].dispose();
      this.geomCache = {};
    }
    if (this.textureAspectRatios = {}, this.materialCache && Object.keys(this.materialCache).length > 0) {
      for (const e of Object.keys(this.materialCache))
        this.materialCache[e].dispose();
      this.materialCache = {};
    }
    Object.keys(this.labelCache).length > 0 && (this.labelCache = {});
  }
  /**
   * Dispose all resources
   */
  dispose() {
    this.clearCache();
  }
}
class vg extends Gd {
  /**
   * Create an AxesHelper.
   * @param center - Origin point [x, y, z] for the axes.
   * @param size - Length of each axis in world units.
   * @param lineWidth - Line width in pixels.
   * @param width - Viewport width for material resolution.
   * @param height - Viewport height for material resolution.
   * @param axes0 - If true, position at origin; if false, at center.
   * @param visible - Initial visibility state.
   * @param theme - Color theme ("dark" or "light").
   */
  constructor(e, t, i, n, s, a, o, l) {
    const c = new Float32Array([
      0,
      0,
      0,
      t,
      0,
      0,
      0,
      0,
      0,
      0,
      t,
      0,
      0,
      0,
      0,
      0,
      0,
      t
    ]), h = new mg();
    h.setPositions(c);
    const d = new _c({
      vertexColors: !0,
      toneMapped: !1,
      linewidth: i,
      transparent: !0
    });
    d.resolution.set(n, s), super(h, d), this.colors = {
      dark: [
        1,
        69 / 255,
        0,
        1,
        69 / 255,
        0,
        // x
        50 / 255,
        205 / 255,
        50 / 255,
        50 / 255,
        205 / 255,
        50 / 255,
        // y
        59 / 255,
        158 / 255,
        1,
        59 / 255,
        158 / 255,
        1
        // z
      ],
      light: [
        1,
        0,
        0,
        1,
        0,
        0,
        // x
        0,
        0.5,
        0,
        0,
        0.5,
        0,
        // y
        0,
        0,
        1,
        0,
        0,
        1
        // z
      ]
    }, h.setColors(new Float32Array(this.colors[l])), this.geometry = h, this.center = e, this.type = "AxesHelper", this.name = "AxesHelper", this.visible = o, this.setCenter(a);
  }
  /**
   * Set the axes position based on the axes0 flag.
   * @param axes0 - If true, position at origin; if false, at center.
   */
  setCenter(e) {
    e ? this.position.set(0, 0, 0) : this.position.set(this.center[0], this.center[1], this.center[2]);
  }
  /**
   * Set the visibility of the axes helper.
   * @param visible - Whether the axes should be visible.
   */
  setVisible(e) {
    this.visible = e;
  }
  /**
   * Change the color theme of the axes.
   * @param theme - The theme name ("dark" or "light").
   */
  changeTheme(e) {
    this.geometry.setColors(new Float32Array(this.colors[e]));
  }
}
class uw {
  /**
   * Constructs a new font.
   *
   * @param {Object} data - The font data as JSON.
   */
  constructor(e) {
    this.isFont = !0, this.type = "Font", this.data = e;
  }
  /**
   * Generates geometry shapes from the given text and size. The result of this method
   * should be used with {@link ShapeGeometry} to generate the actual geometry data.
   *
   * @param {string} text - The text.
   * @param {number} [size=100] - The text size.
   * @return {Array<Shape>} An array of shapes representing the text.
   */
  generateShapes(e, t = 100) {
    const i = [], n = pw(e, t, this.data);
    for (let s = 0, a = n.length; s < a; s++)
      i.push(...n[s].toShapes());
    return i;
  }
}
function pw(r, e, t) {
  const i = Array.from(r), n = e / t.resolution, s = (t.boundingBox.yMax - t.boundingBox.yMin + t.underlineThickness) * n, a = [];
  let o = 0, l = 0;
  for (let c = 0; c < i.length; c++) {
    const h = i[c];
    if (h === `
`)
      o = 0, l -= s;
    else {
      const d = fw(h, n, o, l, t);
      o += d.offsetX, a.push(d.path);
    }
  }
  return a;
}
function fw(r, e, t, i, n) {
  const s = n.glyphs[r] || n.glyphs["?"];
  if (!s) {
    console.error('THREE.Font: character "' + r + '" does not exists in font family ' + n.familyName + ".");
    return;
  }
  const a = new og();
  let o, l, c, h, d, u, p, m;
  if (s.o) {
    const _ = s._cachedOutline || (s._cachedOutline = s.o.split(" "));
    for (let g = 0, f = _.length; g < f; )
      switch (_[g++]) {
        case "m":
          o = _[g++] * e + t, l = _[g++] * e + i, a.moveTo(o, l);
          break;
        case "l":
          o = _[g++] * e + t, l = _[g++] * e + i, a.lineTo(o, l);
          break;
        case "q":
          c = _[g++] * e + t, h = _[g++] * e + i, d = _[g++] * e + t, u = _[g++] * e + i, a.quadraticCurveTo(d, u, c, h);
          break;
        case "b":
          c = _[g++] * e + t, h = _[g++] * e + i, d = _[g++] * e + t, u = _[g++] * e + i, p = _[g++] * e + t, m = _[g++] * e + i, a.bezierCurveTo(d, u, p, m, c, h);
          break;
      }
  }
  return { offsetX: s.ha * e, path: a };
}
const mw = {
  glyphs: {
    X: {
      x_min: -0.015625,
      x_max: 854.15625,
      ha: 940,
      o: "m 854 0 l 683 0 l 423 409 l 166 0 l 0 0 l 347 519 l 18 1013 l 186 1013 l 428 637 l 675 1013 l 836 1013 l 504 520 l 854 0 "
    },
    Y: {
      x_min: 0,
      x_max: 820,
      ha: 886,
      o: "m 820 1013 l 482 416 l 482 0 l 342 0 l 342 416 l 0 1013 l 140 1013 l 411 534 l 679 1012 l 820 1013 "
    },
    Z: {
      x_min: 0,
      x_max: 779,
      ha: 849,
      o: "m 779 0 l 0 0 l 0 113 l 621 896 l 40 896 l 40 1013 l 779 1013 l 778 887 l 171 124 l 779 124 l 779 0 "
    }
  },
  cssFontWeight: "normal",
  ascender: 1189,
  underlinePosition: -100,
  cssFontStyle: "normal",
  boundingBox: { yMin: -334, xMin: -111, yMax: 1189, xMax: 1672 },
  resolution: 1e3,
  descender: -334,
  familyName: "Helvetiker",
  lineHeight: 1522,
  underlineThickness: 50,
  original_font_information: {}
}, qr = 54, fh = qr + 18;
class gw {
  /**
   * Create an OrientationMarker.
   * @param width - Viewport width for the marker.
   * @param height - Viewport height for the marker.
   * @param camera - The main CAD camera to sync orientation with.
   * @param theme - Color theme ("dark" or "light").
   */
  constructor(e, t, i, n) {
    this.width = e, this.height = t, this.cad_camera = i, this.theme = n, this.camera = null, this.scene = null, this.renderer = null, this.labels = [], this.ready = !1, this.colors = {
      dark: [
        [1, 69 / 255, 0],
        [50 / 255, 205 / 255, 50 / 255],
        [59 / 255, 158 / 255, 1]
      ],
      light: [
        [1, 0, 0],
        [0, 0.5, 0],
        [0, 0, 1]
      ]
    }, this.cones = [], this.axes = null;
  }
  /**
   * Create the orientation marker scene with axes, cones, and labels.
   */
  create() {
    const e = new uw(mw), t = 2.5;
    this.scene = new Ma(), this.camera = new kn(-this.width, this.width, this.height, -this.height, 1, 1e3), this.camera.up = this.cad_camera.up, this.camera.lookAt(new b(0, 0, 0)), this.axes = new vg([0, 0, 0], qr, t, this.width, this.height, !0, !0, this.theme), this.scene.add(this.axes), this.cones = [];
    for (let o = 0; o < 3; o++) {
      const l = new Mr(0, 2.5 * t, 5 * t, 20, 1), c = new Ht({
        color: new oe(...this.colors[this.theme][o]),
        toneMapped: !1
      }), h = new Je(l, c);
      h.matrixAutoUpdate = !1, this.cones.push(h);
    }
    this.cones[0].geometry.rotateZ(-Math.PI / 2), this.cones[0].geometry.translate(qr, 0, 0), this.cones[1].geometry.translate(0, qr, 0), this.cones[2].geometry.rotateX(Math.PI / 2), this.cones[2].geometry.translate(0, 0, qr), this.scene.add(...this.cones);
    const i = ["X", "Y", "Z"];
    for (let o = 0; o < 3; o++) {
      const l = new It({
        color: this.theme === "dark" ? new oe(0.9, 0.9, 0.9) : new oe(0, 0, 0),
        side: ri
      }), c = e.generateShapes(i[o], 16), h = new Ta(c);
      h.computeBoundingBox();
      const d = -0.5 * (h.boundingBox.max.x - h.boundingBox.min.x), u = -0.5 * (h.boundingBox.max.y - h.boundingBox.min.y);
      h.translate(d, u, 0);
      const p = new Je(h, l);
      this.scene.add(p), this.labels.push(p);
    }
    const n = new Ts(3 * t, 20, 20), s = new Ht({ color: 10526880 }), a = new Je(n, s);
    this.scene.add(a), this.scene.background = null, this.ready = !0;
  }
  /**
   * Set visibility of all orientation marker elements.
   * @param flag - Whether the marker should be visible.
   */
  setVisible(e) {
    if (this.scene)
      for (const t of this.scene.children)
        t.visible = e;
  }
  /**
   * Dispose of all resources and clean up memory.
   */
  dispose() {
    _g(this.scene, (e) => {
      var t;
      e instanceof Je && ((t = e.geometry) == null || t.dispose(), e.material instanceof qt && e.material.dispose());
    }), this.scene = null, this.camera = null, this.cad_camera = null, this.cones = [], this.labels = [];
  }
  /**
   * Render the orientation marker to the given renderer.
   * @param renderer - The renderer to draw to.
   */
  render(e) {
    this.ready && this.scene && this.camera && (e.setViewport(0, 0, this.width, this.height), e.render(this.scene, this.camera));
  }
  /**
   * Update the marker to match the main camera's orientation.
   * @param position - Camera position (will be normalized).
   * @param quaternion - Camera rotation quaternion.
   */
  update(e, t) {
    if (this.ready && this.camera) {
      const i = new ot().setFromUnitVectors(new b(0, 0, 1), e.normalize());
      this.camera.position.set(0, 0, 1).applyQuaternion(i).multiplyScalar(300), this.camera.quaternion.copy(t);
      for (let n = 0; n < 3; n++)
        this.labels[n].position.set(n == 0 ? fh : 0, n == 1 ? fh : 0, n == 2 ? fh : 0), this.labels[n].quaternion.copy(t);
    }
  }
  /**
   * Change the color theme of the orientation marker.
   * @param theme - The theme name ("dark" or "light").
   */
  changeTheme(e) {
    for (const t in this.cones) {
      const i = this.cones[t];
      i.material.color = new oe(...this.colors[e][t]);
    }
    this.axes && this.axes.changeTheme(e);
    for (const t in this.labels) {
      const i = this.labels[t];
      i.material.color = e === "dark" ? new oe(0.9, 0.9, 0.9) : new oe(0, 0, 0);
    }
  }
}
const je = {
  unselected: 0,
  selected: 1,
  mixed: 2,
  disabled: 3
};
function _w(r) {
  return Array.isArray(r) && r.length === 2;
}
function yw(r) {
  return typeof r == "object" && !Array.isArray(r);
}
class vw {
  /**
   * Create a TreeModel instance.
   * @param treeData - The raw tree structure data.
   * @param options - Configuration options.
   */
  constructor(e, t = {}) {
    this.linkIcons = t.linkIcons !== void 0 ? t.linkIcons : !0, this.onStateChange = t.onStateChange || null, this.maxLevel = 0, this.root = this._buildTreeStructure(e);
  }
  /**
   * Builds the internal tree structure from raw data.
   * @param data - Raw tree data.
   * @returns The root node of the built tree.
   */
  _buildTreeStructure(e) {
    const t = (n, s, a) => {
      const o = [je.unselected, je.unselected], l = (u) => {
        for (const p of [0, 1])
          u[je.mixed][p] || u[je.selected][p] && u[je.unselected][p] ? o[p] = je.mixed : u[je.selected][p] ? o[p] = je.selected : u[je.unselected][p] ? o[p] = je.unselected : u[je.disabled][p] && (o[p] = je.disabled);
        return o;
      }, c = {};
      this.maxLevel < a && (this.maxLevel = a);
      const h = [
        [!1, !1],
        [!1, !1],
        [!1, !1],
        [!1, !1]
      ];
      for (const u in n) {
        let p = "";
        s == null ? p = u : p = `${s}/${u}`;
        let m;
        const _ = n[u];
        if (_w(_))
          m = _, h[_[0]][0] = !0, h[_[1]][1] = !0, c[u] = {
            name: u,
            state: m,
            path: p,
            rendered: !1,
            level: a
          };
        else if (yw(_) && Object.keys(_).length > 0) {
          let g;
          [g, m] = t(_, p, a + 1), h[m[0]][0] = !0, h[m[1]][1] = !0, c[u] = {
            name: u,
            state: m,
            path: p,
            rendered: !1,
            level: a,
            children: g,
            expanded: !1
          };
        } else
          m = [je.disabled, je.disabled], h[je.disabled][0] = !0, h[je.disabled][1] = !0, c[u] = {
            name: u,
            state: m,
            path: p,
            rendered: !1,
            level: a
          };
      }
      const d = l(h);
      return [c, d];
    }, i = t(e, null, 0)[0];
    return i[Object.keys(i)[0]];
  }
  // ============================================================================
  // Tree Traversal Methods
  // ============================================================================
  /**
   * Traverse the tree and call a callback for each node.
   * @param node - Starting node (usually root).
   * @param callback - Function to call for each node.
   */
  traverse(e, t) {
    if (t(e), e.children)
      for (const i of Object.keys(e.children))
        this.traverse(e.children[i], t);
  }
  /**
   * Check if a node is a leaf (has no children).
   * @param node - The node to check.
   * @returns True if the node is a leaf.
   */
  isLeaf(e) {
    return e.children == null;
  }
  /**
   * Get the full path of a node (with leading slash).
   * @param node - The node.
   * @returns The full path (e.g., "/root/child").
   */
  getNodePath(e) {
    return e == null ? "" : "/" + e.path;
  }
  /**
   * Find a node by its path.
   * @param path - Path string or array of path parts.
   * @returns The found node or null.
   */
  findNodeByPath(e) {
    if (!this.root)
      return null;
    const t = Array.isArray(e) ? e : e.split("/").filter(Boolean);
    let i = this.root;
    for (let n = 1; n < t.length; n++) {
      const s = t[n];
      if (i.children && i.children[s])
        i = i.children[s];
      else
        return null;
    }
    return i;
  }
  /**
   * Get the parent node of a given node.
   * @param node - The child node.
   * @returns The parent node or null if node is root.
   */
  getParent(e) {
    const t = e.path.substring(0, e.path.lastIndexOf("/"));
    return t.length === 0 ? null : this.findNodeByPath(t);
  }
  // ============================================================================
  // State Management Methods
  // ============================================================================
  /**
   * Get the state of a node by path.
   * @param path - The node path.
   * @returns The state array [icon0State, icon1State] or null.
   */
  getState(e) {
    const t = this.findNodeByPath(e);
    return t ? t.state : null;
  }
  /**
   * Get all leaf node states.
   * @returns Map of path -> state array.
   */
  getStates() {
    const e = {};
    return this.root && this.traverse(this.root, (t) => {
      this.isLeaf(t) && (e[this.getNodePath(t)] = t.state);
    }), e;
  }
  /**
   * Set the state of a node by path.
   * @param path - The node path.
   * @param state - The new state [icon0State, icon1State].
   */
  setState(e, t) {
    const i = this.findNodeByPath(e);
    i && (this.toggleNodeState(i, 0, t[0] === je.selected), this.toggleNodeState(i, 1, t[1] === je.selected));
  }
  /**
   * Set multiple node states at once.
   * @param states - Map of path -> state array.
   */
  setStates(e) {
    for (const t in e)
      this.setState(t, e[t]);
  }
  /**
   * Toggle the state of a node's icon.
   * @param node - The node to toggle.
   * @param iconNumber - Which icon (0 or 1).
   * @param force - Force to specific state (true=selected, false=unselected, null=toggle).
   * @returns True if state was changed.
   */
  toggleNodeState(e, t, i = null) {
    const n = e.state[t];
    if (n === je.disabled)
      return !1;
    const s = t === 0 ? this.linkIcons ? [0, 1] : [0] : [1];
    for (const a of s)
      e.state[a] !== je.disabled && (i !== null ? e.state[a] = i ? je.selected : je.unselected : e.state[a] = n === je.selected ? je.unselected : je.selected, this.onStateChange && this.onStateChange(e, a), this._updateParentStates(e, a), this._updateChildrenStates(e, a));
    return !0;
  }
  /**
   * Update parent states based on children states.
   * @param node - The node whose parents should be updated.
   * @param iconNumber - Which icon to update.
   */
  _updateParentStates(e, t) {
    let i = this.getParent(e);
    for (; i; ) {
      const n = Object.values(i.children), s = n.every((l) => l.state[t] === je.selected || l.state[t] === je.disabled), a = n.every((l) => l.state[t] === je.unselected || l.state[t] === je.disabled), o = s ? je.selected : a ? je.unselected : je.mixed;
      i.state[t] !== o && i.state[t] !== je.disabled && (i.state[t] = o, this.onStateChange && this.onStateChange(i, t)), i = this.getParent(i);
    }
  }
  /**
   * Update children states to match parent state.
   * @param node - The parent node.
   * @param iconNumber - Which icon to update.
   */
  _updateChildrenStates(e, t) {
    const i = e.state[t], n = (s) => {
      if (s.state[t] !== i && s.state[t] !== je.disabled && (s.state[t] = i, this.onStateChange && this.onStateChange(s, t)), s.children)
        for (const a in s.children)
          n(s.children[a]);
    };
    n(e);
  }
  // ============================================================================
  // Convenience Methods
  // ============================================================================
  /**
   * Hide all nodes (set state to unselected).
   */
  hideAll() {
    this.root && (this.toggleNodeState(this.root, 0, !1), (!this.linkIcons || this.root.state[0] === je.disabled) && this.toggleNodeState(this.root, 1, !1));
  }
  /**
   * Show all nodes (set state to selected).
   */
  showAll() {
    this.root && (this.toggleNodeState(this.root, 0, !0), this.linkIcons || this.toggleNodeState(this.root, 1, !0));
  }
  /**
   * Show a specific node by path.
   * @param path - The node path.
   */
  show(e) {
    const t = this.findNodeByPath(e);
    t && this.toggleNodeState(t, 0, !0);
  }
  /**
   * Hide a specific node by path.
   * @param path - The node path.
   */
  hide(e) {
    const t = this.findNodeByPath(e);
    t && this.toggleNodeState(t, 0, !1);
  }
  /**
   * Set expanded state for all nodes up to a certain level.
   * @param level - The level to expand to (-1 for smart expand).
   */
  setExpandedLevel(e) {
    this.root && this.traverse(this.root, (t) => {
      this.isLeaf(t) || (e === -1 ? t.expanded = t.children != null && !(Object.keys(t.children).length === 1 && this.isLeaf(Object.values(t.children)[0])) : t.expanded = t.level < e);
    });
  }
  /**
   * Expand all nodes along a path.
   * @param path - The path to expand to.
   * @returns The final node in the path, or null if not found.
   */
  expandPath(e) {
    const t = e.split("/").filter(Boolean);
    let i = "", n = null;
    for (const s of t)
      if (i += "/" + s, n = this.findNodeByPath(i), n)
        n.children && (n.expanded = !0);
      else
        return null;
    return n;
  }
  /**
   * Collapse a node by path.
   * @param path - The path to collapse.
   * @returns The collapsed node, or null if not found.
   */
  collapsePath(e) {
    const t = this.findNodeByPath(e);
    return t && (t.expanded = !1), t;
  }
  /**
   * Dispose of resources.
   */
  dispose() {
    this.root = null, this.onStateChange = null;
  }
}
const Hr = {
  expanded: "▾",
  collapsed: "▸"
}, mh = [
  ["shape_no", "shape", "shape_mix", "shape_empty"],
  ["mesh_no", "mesh", "mesh_mix", "mesh_empty"]
], Gp = 12, Wp = [0, 1];
class gh {
  /**
   * Constructs a TreeView object.
   * @param tree - The tree structure data.
   * @param scrollContainer - The scrollable container element.
   * @param objectHandler - Callback for object visibility changes.
   * @param pickHandler - Callback for node selection/picking.
   * @param updateHandler - Callback for tree updates.
   * @param notificationHandler - Callback for notifications.
   * @param colorGetter - Function to get color for a path.
   * @param theme - The UI theme ('light' or 'dark').
   * @param linkIcons - Whether icon 0 and 1 are linked.
   * @param debug - Enable debug logging.
   */
  constructor(e, t, i, n, s, a, o, l, c, h = !1) {
    this.handleScroll = () => {
      this.scrollContainer && (this.lastScrollTop = this.scrollContainer.scrollTop, this.debug && ft.debug("update => scroll"), this.update());
    }, this.handleNavigationClick = (d) => (u) => {
      u.stopPropagation(), d.expanded = !d.expanded, this.showChildContainer(d), this.debug && ft.debug("update => navClick"), this.update();
    }, this.handleIconClick = (d, u) => (p) => {
      p.stopPropagation(), this.toggleIcon(d, u);
    }, this.update = (d = null) => {
      if (!this.container || !this.model)
        return;
      const u = this.getVisibleElements().filter((p) => p instanceof HTMLElement && (d == null || (p.dataset.path || "").startsWith(d)));
      for (const p of u) {
        const m = p.dataset.path || "", _ = this.findNodeByPath(m);
        if (_ != null) {
          if (_.rendered || (this.renderNode(_, p), _.rendered = !0), _.expanded) {
            const g = p.querySelector(".tv-children");
            if (g instanceof HTMLElement && g.children.length === 0) {
              for (const f in _.children) {
                const v = _.children[f];
                this.renderPlaceholder(v, g);
              }
              this.showChildContainer(_), this.update(m);
            }
          }
          for (const g of Wp) {
            const f = p.dataset[`state${g}`], v = _.state[g];
            f != String(v) && this.updateIconInDOM(_, g);
          }
          this.showChildContainer(_);
        } else
          ft.error(`Node not found: ${m}`);
      }
    }, this.getDomNode = (d) => {
      if (!this.container)
        return null;
      const u = this.container.querySelector(`[data-path="${d}"]`);
      return u instanceof HTMLElement ? u : null;
    }, this.tree = e, this.scrollContainer = t, this.objectHandler = i, this.pickHandler = n, this.updateHandler = s, this.notificationHandler = a, this.colorGetter = o, this.theme = l, this.linkIcons = c, this.debug = h, this.model = null, this.container = null, this.lastLabel = null, this.lastScrollTop = 0;
  }
  /**
   * Initialize the tree view - creates the model and DOM container.
   * @returns The container element.
   */
  create() {
    return this.model = new vw(this.tree, {
      linkIcons: this.linkIcons,
      onStateChange: (e, t) => this._handleStateChange(e, t)
    }), this.container = document.createElement("ul"), this.container.classList.add("tcv_toplevel"), this.scrollContainer.addEventListener("scroll", this.handleScroll), this.container;
  }
  /**
   * Handle state changes from the model.
   * @param node - The node whose state changed.
   * @param iconNumber - Which icon changed (0 or 1).
   */
  _handleStateChange(e, t) {
    const i = t === 0 && this.linkIcons ? [0, 1] : [t];
    for (const n of i)
      this.objectHandler(this.getNodePath(e), e.state[n], n, !0, !1);
  }
  // ============================================================================
  // Delegated Properties (for backward compatibility)
  // ============================================================================
  /** @returns The root node of the tree. */
  get root() {
    return this.model ? this.model.root : null;
  }
  /** @returns The maximum depth level of the tree. */
  get maxLevel() {
    return this.model ? this.model.maxLevel : 0;
  }
  // ============================================================================
  // Visible Elements Handling
  // ============================================================================
  /**
   * Retrieves the visible elements within the container.
   * @returns An array of visible elements.
   */
  getVisibleElements() {
    if (!this.container)
      return [];
    const e = (s, a) => {
      const o = s.getBoundingClientRect();
      return o.height > 0 && o.top >= -Gp && o.top <= a.bottom + Gp;
    }, t = this.container.querySelectorAll(".tv-tree-node"), i = this.scrollContainer.getBoundingClientRect(), n = Array.from(t).filter((s) => e(s, i));
    return this.debug && this._logVisibleElements(n), n;
  }
  /**
   * Debug logging for visible elements.
   * @param elements - The visible elements.
   */
  _logVisibleElements(e) {
    ft.debug(`
Visible elements (${e.length}):`);
    for (const t of e) {
      if (!(t instanceof HTMLElement))
        continue;
      const i = this.findNodeByPath(t.dataset.path || "");
      i && ft.debug(i.path, i.state[0], i.state[1], " => ", t.dataset.state0, t.dataset.state1);
    }
  }
  /**
   * Handles the click event on a label.
   * @param node - The node that was clicked.
   * @param e - The event.
   */
  handleLabelClick(e, t) {
    const i = t instanceof MouseEvent;
    this.pickHandler(this.getNodePath(this.getParent(e)), e.name, i ? _t.get(t, "meta") : !1, i ? _t.get(t, "shift") : !1, i ? _t.get(t, "alt") : !1, null, this.isLeaf(e) ? "leaf" : "node", !0), this.debug && ft.debug(`Label clicked: ${this.getNodePath(e)}`);
  }
  /************************************************************************************
   *  Rendering routines
   ************************************************************************************/
  /**
   * Renders the tree view by clearing the container, rendering the placeholder,
   * and updating the tree.
   */
  render() {
    !this.container || !this.root || (this.container.innerHTML = "", this.renderPlaceholder(this.root, this.container), this.debug && ft.debug("update => render"), this.update());
  }
  /**
   * Renders a placeholder node in the tree view.
   * @param node - The node object to render.
   * @param container - The container element to append the rendered node to.
   * @param openPath - The path of the node to be opened, or null if no node should be opened.
   */
  renderPlaceholder(e, t, i = null) {
    this.debug && ft.debug("renderPlaceholder", e.path, e.level);
    const n = document.createElement("div");
    n.className = "tv-tree-node", n.dataset.path = this.getNodePath(e), n.dataset.openPath = i || "", n.dataset.state0 = String(e.state[0]), n.dataset.state1 = String(e.state[1]);
    const s = document.createElement("div");
    s.className = "tv-node-content", this.debug && (s.innerText = e.path), n.appendChild(s), t.appendChild(n);
  }
  /**
   * Renders a node in the tree view to replace the placeholder.
   * @param node - The node object to render.
   * @param parentElement - The parent element to append the rendered node to.
   * @returns The container element for the node's children, if any.
   */
  renderNode(e, t) {
    this.debug && ft.debug("renderNode", e.path, e.level);
    const i = document.createElement("div");
    i.className = "tv-node-content", t.removeChild(t.firstChild), t.appendChild(i);
    const n = document.createElement("span");
    n.className = "tv-nav-marker", n.innerHTML = e.children ? e.expanded ? Hr.expanded : Hr.collapsed : "", n.onclick = this.handleNavigationClick(e), i.dataset.state0 = String(e.state[0]), i.dataset.state1 = String(e.state[1]), i.appendChild(n);
    for (const l of Wp) {
      const c = document.createElement("span"), h = e.state[l];
      let d = `tv-icon tv-icon${l}`;
      h !== je.disabled && (d += " tv-pointer"), c.className = d, c.classList.add("tcv_tree_button"), c.classList.add(`tcv_button_${mh[l][h]}`), h !== je.disabled && (c.onmousedown = (u) => {
        u.preventDefault();
      }, c.onclick = this.handleIconClick(e, l)), i.appendChild(c);
    }
    const s = document.createElement("span");
    s.className = "tv-node-label", s.innerHTML = e.name;
    const a = this.colorGetter(e.path);
    a != null && (s.innerHTML += `<span style="color:${a}"> ⚈</span>`), s.onmousedown = (l) => {
      l.preventDefault();
    }, s.oncontextmenu = (l) => {
      l.preventDefault(), l.stopPropagation(), this.handleLabelClick(e, l);
    }, s.onclick = (l) => {
      l.stopPropagation(), this.handleLabelClick(e, l);
    }, i.appendChild(s);
    let o = null;
    return e.children && (o = document.createElement("div"), o.className = "tv-children", o.style.display = "none", t.appendChild(o)), o;
  }
  /**
   * Shows or hides the child container of a node based on the expanded parameter.
   * @param node - The node object.
   */
  showChildContainer(e) {
    if (e.expanded == null)
      return;
    const t = this.getNodePath(e), i = this.getDomNode(t);
    if (i) {
      const n = i.querySelector(".tv-children");
      if (n instanceof HTMLElement && n.style.display !== "none" !== e.expanded) {
        n.style.display = e.expanded ? "block" : "none";
        const a = i.querySelector(".tv-nav-marker");
        a && (a.innerHTML = e.expanded ? Hr.expanded : Hr.collapsed), e.expanded || (this.debug && ft.debug("update => showChildContainer"), this.update());
      }
    } else
      ft.error(`Element not found: ${t}`);
  }
  /**
   * Updates the icon in the DOM for a given node.
   * @param node - The node to update the icon for.
   * @param iconNumber - The icon number to update.
   */
  updateIconInDOM(e, t) {
    if (!this.container)
      return;
    const i = this.getNodePath(e), n = this.container.querySelector(`[data-path="${i}"]`);
    if (n instanceof HTMLElement) {
      const s = n.querySelector(`.tv-icon${t}`);
      if (s) {
        for (const a of mh[t])
          s.classList.remove(`tcv_button_${a}`);
        s.classList.add(`tcv_button_${mh[t][e.state[t]]}`);
      }
      n.dataset[`state${t}`] = String(e.state[t]);
    }
  }
  /**
   * Toggles the color of the label for a given node.
   * @param node - The node for which to toggle the label color.
   * @param path - If node is null, the path for which to toggle the label color.
   */
  toggleLabelColor(e, t = null) {
    if (!this.container)
      return;
    const i = t == null && e ? this.getNodePath(e) : t;
    if (!i)
      return;
    const n = this.container.querySelector(`[data-path="${i}"]`);
    if (this.lastLabel && this.lastLabel.classList.remove("tv-node-label-highlight"), n) {
      const s = n.querySelector(".tv-node-label");
      s instanceof HTMLElement && (this.lastLabel === s ? this.lastLabel = null : (s.classList.toggle("tv-node-label-highlight"), this.lastLabel = s));
    }
  }
  // ============================================================================
  // Tree Handling - Delegated to TreeModel
  // ============================================================================
  /**
   * Traverse the tree and call a callback for each node.
   * @param node - Starting node.
   * @param callback - Function to call for each node.
   */
  traverse(e, t) {
    this.model && this.model.traverse(e, t);
  }
  /**
   * Check if a node is a leaf (has no children).
   * @param node - The node to check.
   * @returns True if the node is a leaf.
   */
  isLeaf(e) {
    return this.model ? this.model.isLeaf(e) : !0;
  }
  /**
   * Get the full path of a node.
   * @param node - The node.
   * @returns The full path.
   */
  getNodePath(e) {
    return this.model ? this.model.getNodePath(e) : "";
  }
  /**
   * Find a node by its path.
   * @param path - The path to find.
   * @returns The found node or null.
   */
  findNodeByPath(e) {
    return this.model ? this.model.findNodeByPath(e) : null;
  }
  /**
   * Get the parent node of a given node.
   * @param node - The child node.
   * @returns The parent node or null.
   */
  getParent(e) {
    return this.model ? this.model.getParent(e) : null;
  }
  // ============================================================================
  // State Management - Uses TreeModel, handles UI updates
  // ============================================================================
  /**
   * Toggle the state of a node's icon.
   * @param node - The node to toggle.
   * @param iconNumber - Which icon (0 or 1).
   * @param force - Force state (true=selected, false=unselected, null=toggle).
   */
  toggleIcon(e, t, i = null) {
    if (!this.model)
      return;
    this.model.toggleNodeState(e, t, i) && (this.update(), this.updateHandler(!0), this.notificationHandler());
  }
  /**
   * Hide all nodes in the tree.
   */
  hideAll() {
    this.model && (this.model.hideAll(), this.update(), this.updateHandler(!0), this.notificationHandler());
  }
  /**
   * Show all nodes in the tree.
   */
  showAll() {
    this.model && (this.model.showAll(), this.update(), this.updateHandler(!0), this.notificationHandler());
  }
  /**
   * Show a specific node by path.
   * @param path - The node path.
   */
  show(e) {
    this.model && (this.model.show(e), this.update(), this.updateHandler(!0), this.notificationHandler());
  }
  /**
   * Hide a specific node by path.
   * @param path - The node path.
   */
  hide(e) {
    this.model && (this.model.hide(e), this.update(), this.updateHandler(!0), this.notificationHandler());
  }
  /**
   * Get the state of a node by path.
   * @param path - The node path.
   * @returns The state array or null.
   */
  getState(e) {
    return this.model ? this.model.getState(e) : null;
  }
  /**
   * Get all leaf node states.
   * @returns Map of path -> state array.
   */
  getStates() {
    return this.model ? this.model.getStates() : {};
  }
  /**
   * Set the state of a node by path.
   * @param path - The node path.
   * @param state - The new state.
   */
  setState(e, t) {
    this.model && (this.model.setState(e, t), this.update(), this.updateHandler(!0), this.notificationHandler());
  }
  /**
   * Set multiple node states at once.
   * @param states - Map of path -> state array.
   */
  setStates(e) {
    this.model && (this.model.setStates(e), this.update(), this.updateHandler(!0), this.notificationHandler());
  }
  /************************************************************************************
   *  Tree handling high level API
   ************************************************************************************/
  /**
   * Scrolls the parent container to center the specified element within the visible area.
   * @param element - The DOM element to center within the scroll container.
   */
  scrollCentered(e) {
    if (e != null) {
      const t = this.scrollContainer, i = e.offsetHeight, n = t.clientHeight, a = e.offsetTop - t.offsetTop - n / 2 + i / 2, o = t.scrollHeight - n, l = Math.max(0, Math.min(a, o));
      t.scrollTo({ top: l, behavior: "smooth" });
    }
  }
  /**
   * Ensures a node and its children are rendered in the DOM.
   * @param node - The node to render.
   */
  _ensureNodeRendered(e) {
    const t = this.getNodePath(e);
    let i = this.getDomNode(t);
    if (!i) {
      const n = this.getParent(e);
      n && (this._ensureNodeRendered(n), i = this.getDomNode(t));
    }
    if (!i) {
      const n = this.getParent(e);
      if (n) {
        const s = this.getDomNode(this.getNodePath(n));
        if (s) {
          let a = s.querySelector(".tv-children");
          !a && n.children && (n.rendered || (this.renderNode(n, s), n.rendered = !0), a = s.querySelector(".tv-children")), a instanceof HTMLElement && (this.renderPlaceholder(e, a), i = this.getDomNode(t));
        }
      }
    }
    if (i && !e.rendered && (this.renderNode(e, i), e.rendered = !0), i && e.expanded && e.children) {
      const n = i.querySelector(".tv-children");
      if (n instanceof HTMLElement) {
        if (n.children.length === 0)
          for (const s in e.children)
            this.renderPlaceholder(e.children[s], n);
        n.style.display = "block";
      }
    }
    return i;
  }
  /**
   * Opens the specified path in the tree view.
   * @param path - The path to open in the tree view.
   */
  openPath(e) {
    const t = e.split("/").filter(Boolean);
    let i = "", n = null, s = null;
    for (const a of t)
      if (i += "/" + a, n = this.findNodeByPath(i), n) {
        if (n.children && (n.expanded = !0), s = this._ensureNodeRendered(n), s) {
          const o = s.querySelector(".tv-nav-marker");
          o && n.children && (o.innerHTML = Hr.expanded);
        }
        this.debug && ft.debug("update => openPath", i);
      } else {
        ft.error(`Path not found: ${i}`);
        break;
      }
    this.update(), this.scrollCentered(s), n && this.toggleLabelColor(n);
  }
  /**
   * Closes the specified path in the tree view.
   * @param path - The path to be closed.
   */
  closePath(e) {
    const t = this.findNodeByPath(e);
    if (t) {
      t.expanded = !1, this.showChildContainer(t);
      const i = this.getDomNode(e);
      i != null && (this.scrollContainer.scrollTop = i.offsetTop - this.scrollContainer.offsetTop), this.debug && ft.debug("update => collapsePath"), this.update();
    } else
      ft.error(`Path not found: ${e}`);
  }
  /**
   * Open all nodes to a specified level.
   * @param level - The level to open (-1 for smart expand).
   */
  openLevel(e) {
    if (!this.model || !this.root)
      return;
    this.model.setExpandedLevel(e);
    const t = this.getDomNode(this.getNodePath(this.root));
    t != null && (this.scrollContainer.scrollTop = t.offsetTop - this.scrollContainer.offsetTop);
    const i = e === -1 ? this.maxLevel : e;
    for (let n = 0; n <= i; n++)
      this.debug && ft.debug("update => openLevel", n), this.update();
  }
  /**
   * Collapse all nodes in the tree view.
   */
  collapseAll() {
    this.openLevel(0);
  }
  /**
   * Expand all nodes in the tree view.
   */
  expandAll() {
    this.openLevel(this.maxLevel);
  }
  /**
   * Dispose of resources and clean up.
   */
  dispose() {
    this.model && (this.model.dispose(), this.model = null), this.tree = null, this.container = null, this.lastLabel = null, this.scrollContainer.removeEventListener("scroll", this.handleScroll);
  }
}
class Co {
  /**
   * Create a new Timer instance.
   *
   * @param prefix - Label prefix for log messages
   * @param timeit - If false, all timing operations are no-ops
   */
  constructor(e, t) {
    this.prefix = e, this.timeit = t, this.start = performance.now(), this.last = this.start, t && console.info(`three-cad-viewer: ${e}:timer start`);
  }
  /**
   * Log a split time (time since last split or start).
   *
   * @param msg - Message to include in the log output
   */
  split(e) {
    if (this.timeit) {
      const t = performance.now();
      console.info(`three-cad-viewer: ${this.prefix}:${e}:timer split ${(t - this.last).toFixed(1)} ms`), this.last = t;
    }
  }
  /**
   * Log total elapsed time and stop the timer.
   */
  stop() {
    if (this.timeit) {
      const e = performance.now();
      console.info(`three-cad-viewer: ${this.prefix}:timer stop ${(e - this.start).toFixed(1)} ms:`);
    }
  }
}
const xw = [0, 1, 2];
function Xp(r) {
  return r === 0 || r === 1 || r === 2;
}
var Jt;
(function(r) {
  r[r.LEAVES = -1] = "LEAVES", r[r.COLLAPSED = 0] = "COLLAPSED", r[r.ROOT = 1] = "ROOT", r[r.EXPANDED = 2] = "EXPANDED";
})(Jt || (Jt = {}));
function bw(r) {
  return r.triangles_per_face !== void 0;
}
function Sw(r) {
  return r.segments_per_edge !== void 0;
}
const _h = [
  new b(-1, 0, 0),
  new b(0, -1, 0),
  new b(0, 0, -1)
], Ro = {
  light: [16711680, 65280, 255],
  dark: [16729344, 3329330, 3907327]
}, Mw = {
  light: 0.1,
  dark: 0.2
};
class Po {
  /**
   * Create a plane helper material.
   * @param theme - The UI theme ('light' or 'dark').
   * @returns The plane helper material.
   */
  static createPlaneHelperMaterial(e) {
    return new Ht({
      opacity: Mw[e] || 0.1,
      transparent: !0,
      depthWrite: !1,
      toneMapped: !1,
      side: ri
    });
  }
  /**
   * Create a back stencil material.
   * Increments stencil buffer where back faces are visible (clipped region).
   * @returns The back stencil material.
   */
  static createBackStencilMaterial() {
    return new Ht({
      depthWrite: !1,
      depthTest: !1,
      colorWrite: !1,
      side: zt,
      stencilWrite: !0,
      stencilFunc: ca,
      stencilFail: Vo,
      stencilZFail: Vo,
      stencilZPass: Vo
    });
  }
  /**
   * Create a front stencil material.
   * Decrements stencil buffer where front faces are visible.
   * @returns The front stencil material.
   */
  static createFrontStencilMaterial() {
    return new Ht({
      depthWrite: !1,
      depthTest: !1,
      colorWrite: !1,
      side: Di,
      stencilWrite: !0,
      stencilFunc: ca,
      stencilFail: Go,
      stencilZFail: Go,
      stencilZPass: Go
    });
  }
  /**
   * Create a stencil plane material.
   * Draws plane where stencil buffer != 0 (clipped region).
   * @param color - The plane color as hex.
   * @param clippingPlanes - Other clipping planes to apply.
   * @returns The stencil plane material.
   */
  static createStencilPlaneMaterial(e, t) {
    return new Bn({
      color: new oe(e),
      metalness: 0.3,
      roughness: 0.65,
      opacity: 1,
      transparent: !1,
      side: ri,
      polygonOffset: !0,
      polygonOffsetFactor: 1,
      polygonOffsetUnits: 1,
      stencilWrite: !0,
      stencilRef: 0,
      stencilFunc: em,
      stencilFail: Ho,
      stencilZFail: Ho,
      stencilZPass: Ho,
      clippingPlanes: t
    });
  }
}
class qp extends $i {
  /**
   * Create a CenteredPlane.
   * @param normal - The plane normal vector.
   * @param constant - The centered constant value.
   * @param center - The center point [x, y, z].
   */
  constructor(e, t, i) {
    super(e, t), this.center = i, this.centeredConstant = t, this.setConstant(t);
  }
  /**
   * Set the constant relative to the center point.
   * @param value - The centered constant value.
   */
  setConstant(e) {
    this.centeredConstant = e;
    const t = this.distanceToPoint(new b(...this.center)), i = this.distanceToPoint(new b(0, 0, 0));
    this.constant = i - t + e;
  }
}
class Zp extends li {
}
class vr extends Je {
  /**
   * Create a PlaneMesh.
   * @param index - The plane index (0, 1, or 2).
   * @param plane - The clipping plane.
   * @param center - The center point [x, y, z].
   * @param size - The size of the plane mesh.
   * @param material - The material for the mesh.
   * @param color - The color as hex value.
   * @param type - The mesh type identifier.
   */
  constructor(e, t, i, n, s, a, o) {
    const l = new Vn(2, 2);
    l.computeBoundingSphere(), s.color.set(new oe(a)), super(l, s), this.onAfterRender = (c) => {
      this.type.startsWith("StencilPlane") && c.clearStencil();
    }, this.type = o, this.index = e, this.plane = t, this.size = n, this.center = i;
  }
  /**
   * Update the mesh's world matrix to align with the clipping plane.
   * @param force - Force update even if not needed.
   */
  updateMatrixWorld(e) {
    this.position.set(0, 0, 0), this.scale.set(0.5 * this.size, 0.5 * this.size, 1), vr.matrix.lookAt(this.position, this.plane.normal, this.up), this.quaternion.setFromRotationMatrix(vr.matrix), this.translateZ(this.plane.constant), super.updateMatrixWorld(e);
  }
}
vr.matrix = new Ne();
function Yp(r, e, t, i) {
  e.clippingPlanes = [i];
  const n = new Je(t, e);
  return n.name = r, n;
}
class ww extends li {
  /**
   * Create a Clipping instance.
   * @param center - The center point [x, y, z].
   * @param size - The size of the clipping region.
   * @param nestedGroup - The nested group containing objects to clip.
   * @param options - Configuration options.
   * @param theme - The UI theme ('light' or 'dark').
   */
  constructor(e, t, i, n, s) {
    super(), this.setNormal = (a, o) => {
      const l = o.clone();
      this.clipPlanes[a].normal = l, this.reverseClipPlanes[a].normal = l.clone().negate(), this.setConstant(a, this.distance), this.onNormalChange && this.onNormalChange(a, ji(l.toArray()));
    }, this.getObjectColorCaps = () => this.objectColorCaps, this.setObjectColorCaps = (a) => {
      if (!this._planeMeshGroup)
        return;
      let o = 0, l = -1;
      const c = this._planeMeshGroup.children.length / 3;
      for (const h of this._planeMeshGroup.children) {
        o % c === 0 && l++;
        const d = a ? this.objectColors[o] : Ro[this.theme][l];
        h.material.color.set(new oe(d)), o++;
      }
      this.objectColorCaps = a;
    }, this.setVisible = (a) => {
      if (this._planeMeshGroup)
        for (const o of this._planeMeshGroup.children)
          o.material.visible = a;
    }, this.center = e, this.distance = t / 2, this.onNormalChange = n.onNormalChange || null, this.theme = s, this.nestedGroup = i, this.size = t, this.clipPlanes = [], this.reverseClipPlanes = [], this.objectColors = [], this.objectColorCaps = !1, this._planeMeshGroup = null, this.name = "PlaneHelpers", this._createClipPlanes(e), this._createPlaneHelpers(e, t, s), this._createStencils(e, t, s);
  }
  /**
   * Create the three clipping planes and their reverse counterparts.
   * @param center - The center point.
   */
  _createClipPlanes(e) {
    for (const t of xw) {
      const i = new qp(_h[t], this.distance, e);
      this.clipPlanes.push(i);
      const n = new qp(_h[t].clone().negate(), -this.distance, e);
      this.reverseClipPlanes.push(n), this.onNormalChange && this.onNormalChange(t, ji(_h[t].toArray()));
    }
  }
  /**
   * Create the visual plane helpers.
   * @param center - The center point.
   * @param size - The size of the plane helpers.
   * @param theme - The UI theme.
   */
  _createPlaneHelpers(e, t, i) {
    this.planeHelpers = new Zp(), this.planeHelpers.name = "PlaneHelpers";
    for (let n = 0; n < 3; n++) {
      const s = Po.createPlaneHelperMaterial(i);
      this.planeHelpers.add(new vr(n, this.clipPlanes[n], e, t, s, Ro[i][n], "PlaneHelper"));
    }
    for (let n = 0; n < 3; n++) {
      const s = this.clipPlanes.filter((a, o) => o !== n);
      this.planeHelpers.children[n].material.clippingPlanes = s;
    }
    this.planeHelpers.visible = !1, this.add(this.planeHelpers);
  }
  /**
   * Create stencil meshes for solid objects.
   * @param center - The center point.
   * @param size - The size of the stencil planes.
   * @param theme - The UI theme.
   */
  _createStencils(e, t, i) {
    this._planeMeshGroup = new Zp(), this._planeMeshGroup.name = "PlaneMeshes";
    for (let n = 0; n < 3; n++) {
      const s = this.clipPlanes[n], a = this.clipPlanes.filter((l, c) => c !== n);
      let o = 0;
      for (const l in this.nestedGroup.groups) {
        const c = this.nestedGroup.groups[l];
        if (c instanceof Mi && c.subtype === "solid" && c.front) {
          const d = c.front.material;
          this.objectColors.push(d.color.getHex());
          const u = new li();
          u.name = `clipping-${n}`, u.add(Yp(`frontStencil-${n}-${o}`, Po.createFrontStencilMaterial(), c.shapeGeometry, s)), u.add(Yp(`backStencil-${n}-${o}`, Po.createBackStencilMaterial(), c.shapeGeometry, s)), c.addClipping(u, n);
          const p = Po.createStencilPlaneMaterial(Ro[i][n], a);
          this._planeMeshGroup.add(new vr(n, s, e, t, p, Ro[i][n], `StencilPlane-${n}-${o}`)), o++;
        }
      }
    }
    this.nestedGroup.rootGroup.add(this._planeMeshGroup);
  }
  /**
   * Rebuild stencil meshes after scene changes (part add/remove).
   * Clears existing stencils from all ObjectGroups and rebuilds from scratch.
   * Also updates clipping region size if center/size changed.
   * @param center - The new center point [x, y, z].
   * @param size - The new size of the clipping region.
   */
  rebuildStencils(e, t) {
    for (const i in this.nestedGroup.groups) {
      const n = this.nestedGroup.groups[i];
      n instanceof Mi && n.clearClipping();
    }
    this._planeMeshGroup && this.nestedGroup.rootGroup && (this.nestedGroup.rootGroup.remove(this._planeMeshGroup), ct(this._planeMeshGroup), this._planeMeshGroup = null), this.objectColors = [], this.center = e, this.size = t, this.distance = t / 2, this._createStencils(e, t, this.theme), this.objectColorCaps && this.setObjectColorCaps(!0);
  }
  /**
   * Set the constant (distance from center) for a clipping plane.
   * @param index - The plane index (0, 1, or 2).
   * @param value - The constant value relative to center.
   */
  setConstant(e, t) {
    this.clipPlanes[e].setConstant(t), this.reverseClipPlanes[e].setConstant(-t);
  }
  /**
   * Clean up resources.
   * Note: We don't null out arrays/references as GC handles cleanup when the Clipping object is collected.
   */
  dispose() {
    this.onNormalChange = null, this.center = null, this.planeHelpers = null, this._planeMeshGroup = null;
  }
}
function Ew(r, e) {
  const t = new ot();
  return t.setFromAxisAngle(gg[r], e / 180 * Math.PI), t;
}
class Tw {
  /**
   * Create an Animation manager.
   * @param delim - Path delimiter used in object selectors.
   */
  constructor(e) {
    this.delim = e, this.tracks = [], this.mixer = null, this.clip = null, this.clipAction = null, this.clock = new Ud(), this.duration = null, this._backup = null, this.root = null, this.speed = null, this.repeat = null;
  }
  /**
   * Prepare selector by replacing path delimiter.
   */
  _prepareSelector(e) {
    return e.replaceAll("/", this.delim);
  }
  /**
   * Validate that times and values arrays have the same length.
   */
  _validateArrayLengths(e, t) {
    return e.length !== t.length ? (ft.error("times and values arrays need to have the same length"), !1) : !0;
  }
  /**
   * Add a position track (full 3D translation).
   * @param selector - Object path selector (using "/" delimiter).
   * @param group - The object to animate.
   * @param times - Array of keyframe times.
   * @param positions - Array of [x, y, z] position offsets.
   */
  addPositionTrack(e, t, i, n) {
    if (!this._validateArrayLengths(i, n))
      return;
    const s = t.position, a = n.map((o) => s.clone().add(new b(...o)).toArray());
    this.tracks.push(new Ms(this._prepareSelector(e) + ".position", i, a.flat()));
  }
  /**
   * Add a single-axis translation track.
   * @param selector - Object path selector (using "/" delimiter).
   * @param group - The object to animate.
   * @param axis - Which axis to translate along ("x", "y", or "z").
   * @param times - Array of keyframe times.
   * @param values - Array of translation values along the axis.
   */
  addTranslationTrack(e, t, i, n, s) {
    if (!this._validateArrayLengths(n, s))
      return;
    const a = t.position, o = {
      x: (c) => new b(c, 0, 0),
      y: (c) => new b(0, c, 0),
      z: (c) => new b(0, 0, c)
    }, l = s.map((c) => a.clone().add(o[i](c)).toArray());
    this.tracks.push(new Ms(this._prepareSelector(e) + ".position", n, l.flat()));
  }
  /**
   * Add a quaternion rotation track.
   * @param selector - Object path selector (using "/" delimiter).
   * @param group - The object to animate.
   * @param times - Array of keyframe times.
   * @param quaternions - Array of [x, y, z, w] quaternion values.
   */
  addQuaternionTrack(e, t, i, n) {
    if (!this._validateArrayLengths(i, n))
      return;
    const s = t.quaternion, a = n.map((o) => s.clone().multiply(new ot(...o)).toArray());
    this.tracks.push(new Ss(this._prepareSelector(e) + ".quaternion", i, a.flat()));
  }
  /**
   * Add a single-axis rotation track.
   * @param selector - Object path selector (using "/" delimiter).
   * @param group - The object to animate.
   * @param axis - Which axis to rotate around ("x", "y", or "z").
   * @param times - Array of keyframe times.
   * @param angles - Array of rotation angles in degrees.
   */
  addRotationTrack(e, t, i, n, s) {
    if (!this._validateArrayLengths(n, s))
      return;
    const a = t.quaternion, o = s.map((l) => a.clone().multiply(Ew(i, l)).toArray());
    this.tracks.push(new Ss(this._prepareSelector(e) + ".quaternion", n, o.flat()));
  }
  /**
   * Store current animation state for later restoration.
   */
  backup() {
    this._backup = {
      tracks: this.tracks,
      root: this.root,
      duration: this.duration,
      speed: this.speed,
      repeat: this.repeat
    };
  }
  /**
   * Restore previously backed up animation state.
   */
  restore() {
    return this._backup === null ? { duration: null, speed: null, repeat: null } : (this.tracks = this._backup.tracks, {
      duration: this._backup.duration,
      speed: this._backup.speed,
      repeat: this._backup.repeat
    });
  }
  /**
   * Clear the backup state.
   */
  cleanBackup() {
    this._backup = null;
  }
  /**
   * Check if any animation tracks have been added.
   */
  hasTracks() {
    return this.tracks != null && this.tracks.length > 0;
  }
  /**
   * Check if a backup exists.
   */
  hasBackup() {
    return this._backup !== null;
  }
  /**
   * Create and start the animation.
   * @param root - Root object containing animated children.
   * @param duration - Animation duration in seconds.
   * @param speed - Playback speed multiplier.
   * @param repeat - Whether to loop (true) or ping-pong (false).
   * @returns The created animation action.
   */
  animate(e, t, i, n = !0) {
    return this.root = e, this.duration = t, this.speed = i, this.repeat = n, this.clip = new yr("track", t, this.tracks), this.mixer = new ng(e), this.mixer.timeScale = i, this.clipAction = this.mixer.clipAction(this.clip), this.clipAction.setLoop(n ? sd : rd, 1 / 0), this.clipAction;
  }
  /**
   * Set the animation to a specific relative time (0-1).
   * Pauses the animation at that point.
   */
  setRelativeTime(e) {
    if (!this.clipAction || !this.duration)
      return;
    this.clipAction.play(), this.clipAction.paused = !0;
    const t = this.duration * e;
    this.clipAction.time = t;
  }
  /**
   * Get the current relative time (0-1).
   */
  getRelativeTime() {
    return !this.clipAction || !this.duration ? 0 : this.clipAction.time / this.duration;
  }
  /**
   * Dispose of animation resources.
   */
  dispose() {
    this.mixer && (this.mixer.stopAllAction(), this.clip && this.mixer.uncacheClip(this.clip), this.root && this.mixer.uncacheRoot(this.root)), this.mixer = null, this.clipAction = null, this.clip = null, this.tracks = [], this.root = null;
  }
  /**
   * Update the animation mixer (call each frame when animating).
   */
  update() {
    this.mixer && this.mixer.update(this.clock.getDelta());
  }
}
function yh(r) {
  return typeof r == "string" ? r.startsWith("#") ? r : `#${r}` : `#${r.toString(16).padStart(6, "0")}`;
}
class Aw {
  constructor(e) {
    this._bbox = null, this.config = e;
  }
  /**
   * Get the computed bounding box (set after rendering if shapes.bb is defined).
   */
  get bbox() {
    return this._bbox;
  }
  /**
   * Update configuration (e.g., when state changes).
   */
  updateConfig(e) {
    this.config = { ...this.config, ...e };
  }
  /**
   * Render tessellated shapes of a CAD object.
   * @param shapes - The Shapes object representing the tessellated CAD object.
   * @returns A nested THREE.Group object.
   */
  _renderTessellatedShapes(e) {
    const t = new ow(e, this.config.cadWidth, this.config.height, this.config.edgeColor, this.config.transparent, this.config.defaultOpacity, this.config.metalness, this.config.roughness, this.config.normalLen);
    return e.bb && (this._bbox = new _s(new b(e.bb.xmin, e.bb.ymin, e.bb.zmin), new b(e.bb.xmax, e.bb.ymax, e.bb.zmax))), t.render(), t;
  }
  /**
   * Retrieve the navigation tree from a Shapes object.
   * @param shapes - The Shapes object.
   * @returns The navigation tree object.
   */
  _getTree(e) {
    const t = (n) => {
      const s = {};
      for (const a of n)
        a.parts != null ? s[a.name] = t(a.parts) : s[a.name] = a.state;
      return s;
    }, i = {};
    return i[e.name] = t(e.parts ?? []), i;
  }
  /**
   * Decompose a CAD object into faces, edges and vertices.
   * @param part - The part to decompose.
   * @returns A decomposed part object.
   */
  _decompose(e) {
    const t = e.shape;
    let i;
    if (e.parts = [], e.type === "shapes") {
      const a = {
        version: 2,
        name: "faces",
        id: `${e.id}/faces`,
        parts: [],
        loc: [
          [0, 0, 0],
          [0, 0, 0, 1]
        ]
      };
      let o;
      if (!(t.vertices instanceof Float32Array))
        throw new Error("_decompose requires shape.vertices to be Float32Array (call _convertArrays first)");
      if (!(t.normals instanceof Float32Array))
        throw new Error("_decompose requires shape.normals to be Float32Array (call _convertArrays first)");
      const l = t.vertices, c = t.normals;
      let h = 0;
      if (bw(t)) {
        if (!(t.triangles instanceof Uint32Array))
          throw new Error("Expected Uint32Array for triangles in binary format");
        const d = t.triangles, u = t.triangles_per_face, p = u.length;
        for (i = 0; i < p; i++) {
          o = d.subarray(h, h + 3 * u[i]), h += 3 * u[i];
          const m = new Float32Array(o.length * 3), _ = new Float32Array(o.length * 3);
          for (let f = 0; f < o.length; f++) {
            const v = o[f];
            m[3 * f] = l[3 * v], m[3 * f + 1] = l[3 * v + 1], m[3 * f + 2] = l[3 * v + 2], _[3 * f] = c[3 * v], _[3 * f + 1] = c[3 * v + 1], _[3 * f + 2] = c[3 * v + 2];
          }
          const g = {
            version: 2,
            loc: [
              [0, 0, 0],
              [0, 0, 0, 1]
            ],
            name: `faces_${i}`,
            id: `${e.id}/faces/faces_${i}`,
            type: "shapes",
            color: e.color,
            alpha: e.alpha,
            renderback: !0,
            state: [1, 3],
            accuracy: e.accuracy,
            bb: null,
            shape: {
              triangles: [...Array(o.length).keys()],
              vertices: Array.from(m),
              normals: Array.from(_),
              edges: [],
              obj_vertices: [],
              edge_types: [],
              face_types: [t.face_types[i]]
            }
          };
          e.texture && (g.texture = e.texture), g.geomtype = t.face_types[i], g.subtype = e.subtype, g.exploded = !0, a.parts.push(g);
        }
      } else {
        if (!Array.isArray(t.triangles) || !Array.isArray(t.triangles[0]))
          throw new Error("Expected nested array for triangles in non-binary format");
        const d = t.triangles, u = d.length;
        for (i = 0; i < u; i++) {
          o = d[i];
          const p = new Float32Array(o.length * 3), m = new Float32Array(o.length * 3);
          for (let g = 0; g < o.length; g++) {
            const f = o[g];
            p[3 * g] = l[3 * f], p[3 * g + 1] = l[3 * f + 1], p[3 * g + 2] = l[3 * f + 2], m[3 * g] = c[3 * f], m[3 * g + 1] = c[3 * f + 1], m[3 * g + 2] = c[3 * f + 2];
          }
          const _ = {
            version: 2,
            loc: [
              [0, 0, 0],
              [0, 0, 0, 1]
            ],
            name: `faces_${i}`,
            id: `${e.id}/faces/faces_${i}`,
            type: "shapes",
            color: e.color,
            alpha: e.alpha,
            renderback: !0,
            state: [1, 3],
            accuracy: e.accuracy,
            bb: null,
            shape: {
              triangles: [...Array(o.length).keys()],
              vertices: Array.from(p),
              normals: Array.from(m),
              edges: [],
              obj_vertices: [],
              edge_types: [],
              face_types: [t.face_types[i]]
            }
          };
          e.texture && (_.texture = e.texture), _.geomtype = t.face_types[i], _.subtype = e.subtype, _.exploded = !0, a.parts.push(_);
        }
      }
      e.parts.push(a);
    }
    if (e.type === "shapes" || e.type === "edges") {
      const a = {
        version: 2,
        parts: [],
        loc: [
          [0, 0, 0],
          [0, 0, 0, 1]
        ],
        name: "edges",
        id: `${e.id}/edges`
      }, o = Array.isArray(e.color) ? e.color : null;
      let l, c, h = 0;
      if (Sw(t)) {
        if (!(t.edges instanceof Float32Array))
          throw new Error("Expected Float32Array for edges in binary format");
        const d = t.edges, u = t.segments_per_edge, p = u.length;
        for (i = 0; i < p; i++) {
          c = d.subarray(h, h + 6 * u[i]), h += 6 * u[i], l = o ? o[i] : e.color;
          const m = {
            version: 2,
            loc: [
              [0, 0, 0],
              [0, 0, 0, 1]
            ],
            name: `edges_${i}`,
            id: `${e.id}/edges/edges_${i}`,
            type: "edges",
            color: e.type === "shapes" ? yh(this.config.edgeColor) : l,
            state: [3, 1],
            bb: null,
            shape: {
              edges: Array.from(c),
              vertices: [],
              normals: [],
              triangles: [],
              obj_vertices: [],
              edge_types: [t.edge_types[i]],
              face_types: []
            }
          };
          m.width = e.type === "shapes" ? 1 : e.width, m.geomtype = t.edge_types[i], a.parts.push(m);
        }
      } else {
        const d = t.edges;
        if (!Array.isArray(d) || d.length > 0 && !Array.isArray(d[0]))
          throw new Error("Expected nested array for edges in non-binary format");
        const u = d, p = u.length;
        for (i = 0; i < p; i++) {
          c = u[i], l = o ? o[i] : e.color;
          const m = {
            version: 2,
            loc: [
              [0, 0, 0],
              [0, 0, 0, 1]
            ],
            name: `edges_${i}`,
            id: `${e.id}/edges/edges_${i}`,
            type: "edges",
            color: e.type === "shapes" ? yh(this.config.edgeColor) : l,
            state: [3, 1],
            bb: null,
            shape: {
              edges: c,
              vertices: [],
              normals: [],
              triangles: [],
              obj_vertices: [],
              edge_types: [t.edge_types[i]],
              face_types: []
            }
          };
          m.width = e.type === "shapes" ? 1 : e.width, m.geomtype = t.edge_types[i], a.parts.push(m);
        }
      }
      a.parts.length > 0 && e.parts.push(a);
    }
    const n = {
      version: 2,
      parts: [],
      loc: [
        [0, 0, 0],
        [0, 0, 0, 1]
      ],
      name: "vertices",
      id: `${e.id}/vertices`
    }, s = t.obj_vertices;
    for (i = 0; i < s.length / 3; i++) {
      const a = {
        version: 2,
        loc: [
          [0, 0, 0],
          [0, 0, 0, 1]
        ],
        name: `vertices_${i}`,
        id: `${e.id}/vertices/vertices_${i}`,
        type: "vertices",
        color: e.type === "shapes" || e.type === "edges" ? yh(this.config.edgeColor) : e.color,
        state: [3, 1],
        bb: null,
        shape: {
          obj_vertices: [
            s[3 * i],
            s[3 * i + 1],
            s[3 * i + 2]
          ],
          vertices: [],
          normals: [],
          triangles: [],
          edges: [],
          edge_types: [],
          face_types: []
        }
      };
      a.size = e.type === "shapes" || e.type === "edges" ? 4 : e.size, n.parts.push(a);
    }
    return n.parts.length > 0 && e.parts.push(n), delete e.shape, delete e.color, delete e.alpha, delete e.accuracy, delete e.renderback, e;
  }
  /**
   * Convert Shape arrays to TypedArrays for efficient rendering.
   * Note: This mutates the shape in place.
   */
  _convertArrays(e) {
    const t = e;
    t.triangles != null && !(t.triangles instanceof Uint32Array) && t.triangles_per_face !== void 0 && (Array.isArray(t.triangles[0]) || (t.triangles = new Uint32Array(t.triangles))), t.edges != null && !(t.edges instanceof Float32Array) && t.segments_per_edge !== void 0 && (Array.isArray(t.edges[0]) || (t.edges = new Float32Array(t.edges))), t.vertices != null && !(t.vertices instanceof Float32Array) && (t.vertices = new Float32Array(t.vertices)), t.normals != null && !(t.normals instanceof Float32Array) && Array.isArray(t.normals) && t.normals.length > 0 && (Array.isArray(t.normals[0]) ? t.normals = new Float32Array(qh(t.normals, 2)) : t.normals = new Float32Array(t.normals)), t.obj_vertices != null && !(t.obj_vertices instanceof Float32Array) && (t.obj_vertices = new Float32Array(t.obj_vertices)), t.face_types != null && !(t.face_types instanceof Uint32Array) && (t.face_types = new Uint32Array(t.face_types)), t.edge_types != null && !(t.edge_types instanceof Uint32Array) && (t.edge_types instanceof Uint8Array ? t.edge_types = new Uint32Array(t.edge_types) : t.edge_types = new Uint32Array(t.edge_types)), t.triangles_per_face != null && !(t.triangles_per_face instanceof Uint32Array) && (t.triangles_per_face = new Uint32Array(t.triangles_per_face)), t.segments_per_edge != null && !(t.segments_per_edge instanceof Uint32Array) && (t.segments_per_edge = new Uint32Array(t.segments_per_edge));
  }
  /**
   * Recursively process shapes, converting arrays and decomposing parts.
   */
  _processShapes(e) {
    var t;
    if (e.version === 2 || e.version === 3) {
      const i = [];
      for (let n = 0; n < (((t = e.parts) == null ? void 0 : t.length) ?? 0); n++) {
        const s = e.parts[n];
        if (s.shape != null && this._convertArrays(s.shape), s.parts != null) {
          const a = this._processShapes(s);
          i.push(a);
        } else
          i.push(this._decompose(s));
      }
      e.parts = i;
    }
    return e;
  }
  /**
   * Render the shapes of the CAD object.
   * @param exploded - Whether to render the compact or exploded version
   * @param shapes - The Shapes object.
   * @returns A nested THREE.Group object and navigation tree.
   */
  render(e, t) {
    let i;
    e ? i = this._processShapes(structuredClone(t)) : i = structuredClone(t);
    const n = this._renderTessellatedShapes(i), s = this._getTree(i);
    return { group: n, tree: s };
  }
}
const jp = { type: "change" }, Xd = { type: "start" }, xg = { type: "end" }, Lo = new ws(), $p = new $i(), Cw = Math.cos(70 * da.DEG2RAD), Nt = new b(), di = 2 * Math.PI, mt = {
  NONE: -1,
  ROTATE: 0,
  DOLLY: 1,
  PAN: 2,
  TOUCH_ROTATE: 3,
  TOUCH_PAN: 4,
  TOUCH_DOLLY_PAN: 5,
  TOUCH_DOLLY_ROTATE: 6
}, vh = 1e-6;
class Rw extends zd {
  /**
   * Constructs a new controls instance.
   *
   * @param {Object3D} object - The object that is managed by the controls.
   * @param {?HTMLDOMElement} domElement - The HTML element used for event listeners.
   */
  constructor(e, t = null) {
    super(e, t), this.state = mt.NONE, this.target = new b(), this.cursor = new b(), this.minDistance = 0, this.maxDistance = 1 / 0, this.minZoom = 0, this.maxZoom = 1 / 0, this.minTargetRadius = 0, this.maxTargetRadius = 1 / 0, this.minPolarAngle = 0, this.maxPolarAngle = Math.PI, this.minAzimuthAngle = -1 / 0, this.maxAzimuthAngle = 1 / 0, this.enableDamping = !1, this.dampingFactor = 0.05, this.enableZoom = !0, this.zoomSpeed = 1, this.enableRotate = !0, this.rotateSpeed = 1, this.keyRotateSpeed = 1, this.enablePan = !0, this.panSpeed = 1, this.screenSpacePanning = !0, this.keyPanSpeed = 7, this.zoomToCursor = !1, this.autoRotate = !1, this.autoRotateSpeed = 2, this.keys = { LEFT: "ArrowLeft", UP: "ArrowUp", RIGHT: "ArrowRight", BOTTOM: "ArrowDown" }, this.mouseButtons = { LEFT: bt.ROTATE, MIDDLE: bt.DOLLY, RIGHT: bt.PAN }, this.touches = { ONE: hs.ROTATE, TWO: hs.DOLLY_PAN }, this.target0 = this.target.clone(), this.position0 = this.object.position.clone(), this.zoom0 = this.object.zoom, this._domElementKeyEvents = null, this._lastPosition = new b(), this._lastQuaternion = new ot(), this._lastTargetPosition = new b(), this._quat = new ot().setFromUnitVectors(e.up, new b(0, 1, 0)), this._quatInverse = this._quat.clone().invert(), this._spherical = new Vh(), this._sphericalDelta = new Vh(), this._scale = 1, this._panOffset = new b(), this._rotateStart = new H(), this._rotateEnd = new H(), this._rotateDelta = new H(), this._panStart = new H(), this._panEnd = new H(), this._panDelta = new H(), this._dollyStart = new H(), this._dollyEnd = new H(), this._dollyDelta = new H(), this._dollyDirection = new b(), this._mouse = new H(), this._performCursorZoom = !1, this._pointers = [], this._pointerPositions = {}, this._controlActive = !1, this._onPointerMove = Lw.bind(this), this._onPointerDown = Pw.bind(this), this._onPointerUp = Iw.bind(this), this._onContextMenu = kw.bind(this), this._onMouseWheel = Uw.bind(this), this._onKeyDown = Ow.bind(this), this._onTouchStart = Fw.bind(this), this._onTouchMove = Bw.bind(this), this._onMouseDown = Dw.bind(this), this._onMouseMove = Nw.bind(this), this._interceptControlDown = zw.bind(this), this._interceptControlUp = Hw.bind(this), this.domElement !== null && this.connect(this.domElement), this.update();
  }
  connect(e) {
    super.connect(e), this.domElement.addEventListener("pointerdown", this._onPointerDown), this.domElement.addEventListener("pointercancel", this._onPointerUp), this.domElement.addEventListener("contextmenu", this._onContextMenu), this.domElement.addEventListener("wheel", this._onMouseWheel, { passive: !1 }), this.domElement.getRootNode().addEventListener("keydown", this._interceptControlDown, { passive: !0, capture: !0 }), this.domElement.style.touchAction = "none";
  }
  disconnect() {
    this.domElement.removeEventListener("pointerdown", this._onPointerDown), this.domElement.removeEventListener("pointermove", this._onPointerMove), this.domElement.removeEventListener("pointerup", this._onPointerUp), this.domElement.removeEventListener("pointercancel", this._onPointerUp), this.domElement.removeEventListener("wheel", this._onMouseWheel), this.domElement.removeEventListener("contextmenu", this._onContextMenu), this.stopListenToKeyEvents(), this.domElement.getRootNode().removeEventListener("keydown", this._interceptControlDown, { capture: !0 }), this.domElement.style.touchAction = "auto";
  }
  dispose() {
    this.disconnect();
  }
  /**
   * Get the current vertical rotation, in radians.
   *
   * @return {number} The current vertical rotation, in radians.
   */
  getPolarAngle() {
    return this._spherical.phi;
  }
  /**
   * Get the current horizontal rotation, in radians.
   *
   * @return {number} The current horizontal rotation, in radians.
   */
  getAzimuthalAngle() {
    return this._spherical.theta;
  }
  /**
   * Returns the distance from the camera to the target.
   *
   * @return {number} The distance from the camera to the target.
   */
  getDistance() {
    return this.object.position.distanceTo(this.target);
  }
  /**
   * Adds key event listeners to the given DOM element.
   * `window` is a recommended argument for using this method.
   *
   * @param {HTMLDOMElement} domElement - The DOM element
   */
  listenToKeyEvents(e) {
    e.addEventListener("keydown", this._onKeyDown), this._domElementKeyEvents = e;
  }
  /**
   * Removes the key event listener previously defined with `listenToKeyEvents()`.
   */
  stopListenToKeyEvents() {
    this._domElementKeyEvents !== null && (this._domElementKeyEvents.removeEventListener("keydown", this._onKeyDown), this._domElementKeyEvents = null);
  }
  /**
   * Save the current state of the controls. This can later be recovered with `reset()`.
   */
  saveState() {
    this.target0.copy(this.target), this.position0.copy(this.object.position), this.zoom0 = this.object.zoom;
  }
  /**
   * Reset the controls to their state from either the last time the `saveState()`
   * was called, or the initial state.
   */
  reset() {
    this.target.copy(this.target0), this.object.position.copy(this.position0), this.object.zoom = this.zoom0, this.object.updateProjectionMatrix(), this.dispatchEvent(jp), this.update(), this.state = mt.NONE;
  }
  update(e = null) {
    const t = this.object.position;
    Nt.copy(t).sub(this.target), Nt.applyQuaternion(this._quat), this._spherical.setFromVector3(Nt), this.autoRotate && this.state === mt.NONE && this._rotateLeft(this._getAutoRotationAngle(e)), this.enableDamping ? (this._spherical.theta += this._sphericalDelta.theta * this.dampingFactor, this._spherical.phi += this._sphericalDelta.phi * this.dampingFactor) : (this._spherical.theta += this._sphericalDelta.theta, this._spherical.phi += this._sphericalDelta.phi);
    let i = this.minAzimuthAngle, n = this.maxAzimuthAngle;
    isFinite(i) && isFinite(n) && (i < -Math.PI ? i += di : i > Math.PI && (i -= di), n < -Math.PI ? n += di : n > Math.PI && (n -= di), i <= n ? this._spherical.theta = Math.max(i, Math.min(n, this._spherical.theta)) : this._spherical.theta = this._spherical.theta > (i + n) / 2 ? Math.max(i, this._spherical.theta) : Math.min(n, this._spherical.theta)), this._spherical.phi = Math.max(this.minPolarAngle, Math.min(this.maxPolarAngle, this._spherical.phi)), this._spherical.makeSafe(), this.enableDamping === !0 ? this.target.addScaledVector(this._panOffset, this.dampingFactor) : this.target.add(this._panOffset), this.target.sub(this.cursor), this.target.clampLength(this.minTargetRadius, this.maxTargetRadius), this.target.add(this.cursor);
    let s = !1;
    if (this.zoomToCursor && this._performCursorZoom || this.object.isOrthographicCamera)
      this._spherical.radius = this._clampDistance(this._spherical.radius);
    else {
      const a = this._spherical.radius;
      this._spherical.radius = this._clampDistance(this._spherical.radius * this._scale), s = a != this._spherical.radius;
    }
    if (Nt.setFromSpherical(this._spherical), Nt.applyQuaternion(this._quatInverse), t.copy(this.target).add(Nt), this.object.lookAt(this.target), this.enableDamping === !0 ? (this._sphericalDelta.theta *= 1 - this.dampingFactor, this._sphericalDelta.phi *= 1 - this.dampingFactor, this._panOffset.multiplyScalar(1 - this.dampingFactor)) : (this._sphericalDelta.set(0, 0, 0), this._panOffset.set(0, 0, 0)), this.zoomToCursor && this._performCursorZoom) {
      let a = null;
      if (this.object.isPerspectiveCamera) {
        const o = Nt.length();
        a = this._clampDistance(o * this._scale);
        const l = o - a;
        this.object.position.addScaledVector(this._dollyDirection, l), this.object.updateMatrixWorld(), s = !!l;
      } else if (this.object.isOrthographicCamera) {
        const o = new b(this._mouse.x, this._mouse.y, 0);
        o.unproject(this.object);
        const l = this.object.zoom;
        this.object.zoom = Math.max(this.minZoom, Math.min(this.maxZoom, this.object.zoom / this._scale)), this.object.updateProjectionMatrix(), s = l !== this.object.zoom;
        const c = new b(this._mouse.x, this._mouse.y, 0);
        c.unproject(this.object), this.object.position.sub(c).add(o), this.object.updateMatrixWorld(), a = Nt.length();
      } else
        console.warn("WARNING: OrbitControls.js encountered an unknown camera type - zoom to cursor disabled."), this.zoomToCursor = !1;
      a !== null && (this.screenSpacePanning ? this.target.set(0, 0, -1).transformDirection(this.object.matrix).multiplyScalar(a).add(this.object.position) : (Lo.origin.copy(this.object.position), Lo.direction.set(0, 0, -1).transformDirection(this.object.matrix), Math.abs(this.object.up.dot(Lo.direction)) < Cw ? this.object.lookAt(this.target) : ($p.setFromNormalAndCoplanarPoint(this.object.up, this.target), Lo.intersectPlane($p, this.target))));
    } else if (this.object.isOrthographicCamera) {
      const a = this.object.zoom;
      this.object.zoom = Math.max(this.minZoom, Math.min(this.maxZoom, this.object.zoom / this._scale)), a !== this.object.zoom && (this.object.updateProjectionMatrix(), s = !0);
    }
    return this._scale = 1, this._performCursorZoom = !1, s || this._lastPosition.distanceToSquared(this.object.position) > vh || 8 * (1 - this._lastQuaternion.dot(this.object.quaternion)) > vh || this._lastTargetPosition.distanceToSquared(this.target) > vh ? (this.dispatchEvent(jp), this._lastPosition.copy(this.object.position), this._lastQuaternion.copy(this.object.quaternion), this._lastTargetPosition.copy(this.target), !0) : !1;
  }
  _getAutoRotationAngle(e) {
    return e !== null ? di / 60 * this.autoRotateSpeed * e : di / 60 / 60 * this.autoRotateSpeed;
  }
  _getZoomScale(e) {
    const t = Math.abs(e * 0.01);
    return Math.pow(0.95, this.zoomSpeed * t);
  }
  _rotateLeft(e) {
    this._sphericalDelta.theta -= e;
  }
  _rotateUp(e) {
    this._sphericalDelta.phi -= e;
  }
  _panLeft(e, t) {
    Nt.setFromMatrixColumn(t, 0), Nt.multiplyScalar(-e), this._panOffset.add(Nt);
  }
  _panUp(e, t) {
    this.screenSpacePanning === !0 ? Nt.setFromMatrixColumn(t, 1) : (Nt.setFromMatrixColumn(t, 0), Nt.crossVectors(this.object.up, Nt)), Nt.multiplyScalar(e), this._panOffset.add(Nt);
  }
  // deltaX and deltaY are in pixels; right and down are positive
  _pan(e, t) {
    const i = this.domElement;
    if (this.object.isPerspectiveCamera) {
      const n = this.object.position;
      Nt.copy(n).sub(this.target);
      let s = Nt.length();
      s *= Math.tan(this.object.fov / 2 * Math.PI / 180), this._panLeft(2 * e * s / i.clientHeight, this.object.matrix), this._panUp(2 * t * s / i.clientHeight, this.object.matrix);
    } else this.object.isOrthographicCamera ? (this._panLeft(e * (this.object.right - this.object.left) / this.object.zoom / i.clientWidth, this.object.matrix), this._panUp(t * (this.object.top - this.object.bottom) / this.object.zoom / i.clientHeight, this.object.matrix)) : (console.warn("WARNING: OrbitControls.js encountered an unknown camera type - pan disabled."), this.enablePan = !1);
  }
  _dollyOut(e) {
    this.object.isPerspectiveCamera || this.object.isOrthographicCamera ? this._scale /= e : (console.warn("WARNING: OrbitControls.js encountered an unknown camera type - dolly/zoom disabled."), this.enableZoom = !1);
  }
  _dollyIn(e) {
    this.object.isPerspectiveCamera || this.object.isOrthographicCamera ? this._scale *= e : (console.warn("WARNING: OrbitControls.js encountered an unknown camera type - dolly/zoom disabled."), this.enableZoom = !1);
  }
  _updateZoomParameters(e, t) {
    if (!this.zoomToCursor)
      return;
    this._performCursorZoom = !0;
    const i = this.domElement.getBoundingClientRect(), n = e - i.left, s = t - i.top, a = i.width, o = i.height;
    this._mouse.x = n / a * 2 - 1, this._mouse.y = -(s / o) * 2 + 1, this._dollyDirection.set(this._mouse.x, this._mouse.y, 1).unproject(this.object).sub(this.object.position).normalize();
  }
  _clampDistance(e) {
    return Math.max(this.minDistance, Math.min(this.maxDistance, e));
  }
  //
  // event callbacks - update the object state
  //
  _handleMouseDownRotate(e) {
    this._rotateStart.set(e.clientX, e.clientY);
  }
  _handleMouseDownDolly(e) {
    this._updateZoomParameters(e.clientX, e.clientX), this._dollyStart.set(e.clientX, e.clientY);
  }
  _handleMouseDownPan(e) {
    this._panStart.set(e.clientX, e.clientY);
  }
  _handleMouseMoveRotate(e) {
    this._rotateEnd.set(e.clientX, e.clientY), this._rotateDelta.subVectors(this._rotateEnd, this._rotateStart).multiplyScalar(this.rotateSpeed);
    const t = this.domElement;
    this._rotateLeft(di * this._rotateDelta.x / t.clientHeight), this._rotateUp(di * this._rotateDelta.y / t.clientHeight), this._rotateStart.copy(this._rotateEnd), this.update();
  }
  _handleMouseMoveDolly(e) {
    this._dollyEnd.set(e.clientX, e.clientY), this._dollyDelta.subVectors(this._dollyEnd, this._dollyStart), this._dollyDelta.y > 0 ? this._dollyOut(this._getZoomScale(this._dollyDelta.y)) : this._dollyDelta.y < 0 && this._dollyIn(this._getZoomScale(this._dollyDelta.y)), this._dollyStart.copy(this._dollyEnd), this.update();
  }
  _handleMouseMovePan(e) {
    this._panEnd.set(e.clientX, e.clientY), this._panDelta.subVectors(this._panEnd, this._panStart).multiplyScalar(this.panSpeed), this._pan(this._panDelta.x, this._panDelta.y), this._panStart.copy(this._panEnd), this.update();
  }
  _handleMouseWheel(e) {
    this._updateZoomParameters(e.clientX, e.clientY), e.deltaY < 0 ? this._dollyIn(this._getZoomScale(e.deltaY)) : e.deltaY > 0 && this._dollyOut(this._getZoomScale(e.deltaY)), this.update();
  }
  _handleKeyDown(e) {
    let t = !1;
    switch (e.code) {
      case this.keys.UP:
        e.ctrlKey || e.metaKey || e.shiftKey ? this.enableRotate && this._rotateUp(di * this.keyRotateSpeed / this.domElement.clientHeight) : this.enablePan && this._pan(0, this.keyPanSpeed), t = !0;
        break;
      case this.keys.BOTTOM:
        e.ctrlKey || e.metaKey || e.shiftKey ? this.enableRotate && this._rotateUp(-di * this.keyRotateSpeed / this.domElement.clientHeight) : this.enablePan && this._pan(0, -this.keyPanSpeed), t = !0;
        break;
      case this.keys.LEFT:
        e.ctrlKey || e.metaKey || e.shiftKey ? this.enableRotate && this._rotateLeft(di * this.keyRotateSpeed / this.domElement.clientHeight) : this.enablePan && this._pan(this.keyPanSpeed, 0), t = !0;
        break;
      case this.keys.RIGHT:
        e.ctrlKey || e.metaKey || e.shiftKey ? this.enableRotate && this._rotateLeft(-di * this.keyRotateSpeed / this.domElement.clientHeight) : this.enablePan && this._pan(-this.keyPanSpeed, 0), t = !0;
        break;
    }
    t && (e.preventDefault(), this.update());
  }
  _handleTouchStartRotate(e) {
    if (this._pointers.length === 1)
      this._rotateStart.set(e.pageX, e.pageY);
    else {
      const t = this._getSecondPointerPosition(e), i = 0.5 * (e.pageX + t.x), n = 0.5 * (e.pageY + t.y);
      this._rotateStart.set(i, n);
    }
  }
  _handleTouchStartPan(e) {
    if (this._pointers.length === 1)
      this._panStart.set(e.pageX, e.pageY);
    else {
      const t = this._getSecondPointerPosition(e), i = 0.5 * (e.pageX + t.x), n = 0.5 * (e.pageY + t.y);
      this._panStart.set(i, n);
    }
  }
  _handleTouchStartDolly(e) {
    const t = this._getSecondPointerPosition(e), i = e.pageX - t.x, n = e.pageY - t.y, s = Math.sqrt(i * i + n * n);
    this._dollyStart.set(0, s);
  }
  _handleTouchStartDollyPan(e) {
    this.enableZoom && this._handleTouchStartDolly(e), this.enablePan && this._handleTouchStartPan(e);
  }
  _handleTouchStartDollyRotate(e) {
    this.enableZoom && this._handleTouchStartDolly(e), this.enableRotate && this._handleTouchStartRotate(e);
  }
  _handleTouchMoveRotate(e) {
    if (this._pointers.length == 1)
      this._rotateEnd.set(e.pageX, e.pageY);
    else {
      const i = this._getSecondPointerPosition(e), n = 0.5 * (e.pageX + i.x), s = 0.5 * (e.pageY + i.y);
      this._rotateEnd.set(n, s);
    }
    this._rotateDelta.subVectors(this._rotateEnd, this._rotateStart).multiplyScalar(this.rotateSpeed);
    const t = this.domElement;
    this._rotateLeft(di * this._rotateDelta.x / t.clientHeight), this._rotateUp(di * this._rotateDelta.y / t.clientHeight), this._rotateStart.copy(this._rotateEnd);
  }
  _handleTouchMovePan(e) {
    if (this._pointers.length === 1)
      this._panEnd.set(e.pageX, e.pageY);
    else {
      const t = this._getSecondPointerPosition(e), i = 0.5 * (e.pageX + t.x), n = 0.5 * (e.pageY + t.y);
      this._panEnd.set(i, n);
    }
    this._panDelta.subVectors(this._panEnd, this._panStart).multiplyScalar(this.panSpeed), this._pan(this._panDelta.x, this._panDelta.y), this._panStart.copy(this._panEnd);
  }
  _handleTouchMoveDolly(e) {
    const t = this._getSecondPointerPosition(e), i = e.pageX - t.x, n = e.pageY - t.y, s = Math.sqrt(i * i + n * n);
    this._dollyEnd.set(0, s), this._dollyDelta.set(0, Math.pow(this._dollyEnd.y / this._dollyStart.y, this.zoomSpeed)), this._dollyOut(this._dollyDelta.y), this._dollyStart.copy(this._dollyEnd);
    const a = (e.pageX + t.x) * 0.5, o = (e.pageY + t.y) * 0.5;
    this._updateZoomParameters(a, o);
  }
  _handleTouchMoveDollyPan(e) {
    this.enableZoom && this._handleTouchMoveDolly(e), this.enablePan && this._handleTouchMovePan(e);
  }
  _handleTouchMoveDollyRotate(e) {
    this.enableZoom && this._handleTouchMoveDolly(e), this.enableRotate && this._handleTouchMoveRotate(e);
  }
  // pointers
  _addPointer(e) {
    this._pointers.push(e.pointerId);
  }
  _removePointer(e) {
    delete this._pointerPositions[e.pointerId];
    for (let t = 0; t < this._pointers.length; t++)
      if (this._pointers[t] == e.pointerId) {
        this._pointers.splice(t, 1);
        return;
      }
  }
  _isTrackingPointer(e) {
    for (let t = 0; t < this._pointers.length; t++)
      if (this._pointers[t] == e.pointerId) return !0;
    return !1;
  }
  _trackPointer(e) {
    let t = this._pointerPositions[e.pointerId];
    t === void 0 && (t = new H(), this._pointerPositions[e.pointerId] = t), t.set(e.pageX, e.pageY);
  }
  _getSecondPointerPosition(e) {
    const t = e.pointerId === this._pointers[0] ? this._pointers[1] : this._pointers[0];
    return this._pointerPositions[t];
  }
  //
  _customWheelEvent(e) {
    const t = e.deltaMode, i = {
      clientX: e.clientX,
      clientY: e.clientY,
      deltaY: e.deltaY
    };
    switch (t) {
      case 1:
        i.deltaY *= 16;
        break;
      case 2:
        i.deltaY *= 100;
        break;
    }
    return e.ctrlKey && !this._controlActive && (i.deltaY *= 10), i;
  }
}
function Pw(r) {
  this.enabled !== !1 && (this._pointers.length === 0 && (this.domElement.setPointerCapture(r.pointerId), this.domElement.addEventListener("pointermove", this._onPointerMove), this.domElement.addEventListener("pointerup", this._onPointerUp)), !this._isTrackingPointer(r) && (this._addPointer(r), r.pointerType === "touch" ? this._onTouchStart(r) : this._onMouseDown(r)));
}
function Lw(r) {
  this.enabled !== !1 && (r.pointerType === "touch" ? this._onTouchMove(r) : this._onMouseMove(r));
}
function Iw(r) {
  switch (this._removePointer(r), this._pointers.length) {
    case 0:
      this.domElement.releasePointerCapture(r.pointerId), this.domElement.removeEventListener("pointermove", this._onPointerMove), this.domElement.removeEventListener("pointerup", this._onPointerUp), this.dispatchEvent(xg), this.state = mt.NONE;
      break;
    case 1:
      const e = this._pointers[0], t = this._pointerPositions[e];
      this._onTouchStart({ pointerId: e, pageX: t.x, pageY: t.y });
      break;
  }
}
function Dw(r) {
  let e;
  switch (r.button) {
    case 0:
      e = this.mouseButtons.LEFT;
      break;
    case 1:
      e = this.mouseButtons.MIDDLE;
      break;
    case 2:
      e = this.mouseButtons.RIGHT;
      break;
    default:
      e = -1;
  }
  switch (e) {
    case bt.DOLLY:
      if (this.enableZoom === !1) return;
      this._handleMouseDownDolly(r), this.state = mt.DOLLY;
      break;
    case bt.ROTATE:
      if (r.ctrlKey || r.metaKey || r.shiftKey) {
        if (this.enablePan === !1) return;
        this._handleMouseDownPan(r), this.state = mt.PAN;
      } else {
        if (this.enableRotate === !1) return;
        this._handleMouseDownRotate(r), this.state = mt.ROTATE;
      }
      break;
    case bt.PAN:
      if (r.ctrlKey || r.metaKey || r.shiftKey) {
        if (this.enableRotate === !1) return;
        this._handleMouseDownRotate(r), this.state = mt.ROTATE;
      } else {
        if (this.enablePan === !1) return;
        this._handleMouseDownPan(r), this.state = mt.PAN;
      }
      break;
    default:
      this.state = mt.NONE;
  }
  this.state !== mt.NONE && this.dispatchEvent(Xd);
}
function Nw(r) {
  switch (this.state) {
    case mt.ROTATE:
      if (this.enableRotate === !1) return;
      this._handleMouseMoveRotate(r);
      break;
    case mt.DOLLY:
      if (this.enableZoom === !1) return;
      this._handleMouseMoveDolly(r);
      break;
    case mt.PAN:
      if (this.enablePan === !1) return;
      this._handleMouseMovePan(r);
      break;
  }
}
function Uw(r) {
  this.enabled === !1 || this.enableZoom === !1 || this.state !== mt.NONE || (r.preventDefault(), this.dispatchEvent(Xd), this._handleMouseWheel(this._customWheelEvent(r)), this.dispatchEvent(xg));
}
function Ow(r) {
  this.enabled !== !1 && this._handleKeyDown(r);
}
function Fw(r) {
  switch (this._trackPointer(r), this._pointers.length) {
    case 1:
      switch (this.touches.ONE) {
        case hs.ROTATE:
          if (this.enableRotate === !1) return;
          this._handleTouchStartRotate(r), this.state = mt.TOUCH_ROTATE;
          break;
        case hs.PAN:
          if (this.enablePan === !1) return;
          this._handleTouchStartPan(r), this.state = mt.TOUCH_PAN;
          break;
        default:
          this.state = mt.NONE;
      }
      break;
    case 2:
      switch (this.touches.TWO) {
        case hs.DOLLY_PAN:
          if (this.enableZoom === !1 && this.enablePan === !1) return;
          this._handleTouchStartDollyPan(r), this.state = mt.TOUCH_DOLLY_PAN;
          break;
        case hs.DOLLY_ROTATE:
          if (this.enableZoom === !1 && this.enableRotate === !1) return;
          this._handleTouchStartDollyRotate(r), this.state = mt.TOUCH_DOLLY_ROTATE;
          break;
        default:
          this.state = mt.NONE;
      }
      break;
    default:
      this.state = mt.NONE;
  }
  this.state !== mt.NONE && this.dispatchEvent(Xd);
}
function Bw(r) {
  switch (this._trackPointer(r), this.state) {
    case mt.TOUCH_ROTATE:
      if (this.enableRotate === !1) return;
      this._handleTouchMoveRotate(r), this.update();
      break;
    case mt.TOUCH_PAN:
      if (this.enablePan === !1) return;
      this._handleTouchMovePan(r), this.update();
      break;
    case mt.TOUCH_DOLLY_PAN:
      if (this.enableZoom === !1 && this.enablePan === !1) return;
      this._handleTouchMoveDollyPan(r), this.update();
      break;
    case mt.TOUCH_DOLLY_ROTATE:
      if (this.enableZoom === !1 && this.enableRotate === !1) return;
      this._handleTouchMoveDollyRotate(r), this.update();
      break;
    default:
      this.state = mt.NONE;
  }
}
function kw(r) {
  this.enabled !== !1 && r.preventDefault();
}
function zw(r) {
  r.key === "Control" && (this._controlActive = !0, this.domElement.getRootNode().addEventListener("keyup", this._interceptControlUp, { passive: !0, capture: !0 }));
}
function Hw(r) {
  r.key === "Control" && (this._controlActive = !1, this.domElement.getRootNode().removeEventListener("keyup", this._interceptControlUp, { passive: !0, capture: !0 }));
}
const Qs = {
  NONE: -1,
  ROTATE: 0,
  DOLLY: 1,
  PAN: 2
};
class Kp extends Rw {
  /**
   * Constructs CAD-enhanced orbit controls.
   *
   * @param object - The camera to control.
   * @param domElement - The HTML element for event listeners.
   */
  constructor(e, t = null) {
    super(e, t), this.quaternion0 = this.object.quaternion.clone(), this._horizontalRotate = !0, this._verticalRotate = !0, t && (this._onCADPointerDown = this._handleCADPointerDown.bind(this), this._onCADPointerUp = this._handleCADPointerUp.bind(this), t.addEventListener("pointerdown", this._onCADPointerDown), t.addEventListener("pointerup", this._onCADPointerUp), t.addEventListener("pointercancel", this._onCADPointerUp)), this._onMouseDown = this._handleMouseDown.bind(this);
  }
  /**
   * Handle pointer down to check modifier keys for rotation restriction.
   */
  _handleCADPointerDown(e) {
    this._horizontalRotate = !_t.get(e, "ctrl"), this._verticalRotate = !_t.get(e, "meta");
  }
  /**
   * Handle pointer up to reset rotation restrictions.
   */
  _handleCADPointerUp() {
    this._horizontalRotate = !0, this._verticalRotate = !0;
  }
  /**
   * Override dispose to clean up our event listeners.
   */
  dispose() {
    this.domElement && this._onCADPointerDown && this._onCADPointerUp && (this.domElement.removeEventListener("pointerdown", this._onCADPointerDown), this.domElement.removeEventListener("pointerup", this._onCADPointerUp), this.domElement.removeEventListener("pointercancel", this._onCADPointerUp)), super.dispose();
  }
  /**
   * Custom mouse down handler for rotation restriction via modifier keys.
   *
   * Original OrbitControls: ctrl/meta/shift + left mouse = pan
   * CADOrbitControls: ctrl = vertical rotate only, meta = horizontal rotate only,
   *                   shift = pan (via KeyMapper)
   */
  _handleMouseDown(e) {
    let t;
    switch (e.button) {
      case 0:
        t = this.mouseButtons.LEFT;
        break;
      case 1:
        t = this.mouseButtons.MIDDLE;
        break;
      case 2:
        t = this.mouseButtons.RIGHT;
        break;
      default:
        t = -1;
    }
    switch (t) {
      case bt.DOLLY:
        if (this.enableZoom === !1)
          return;
        this._handleMouseDownDolly(e), this.state = Qs.DOLLY;
        break;
      case bt.ROTATE:
        if (_t.get(e, "shift")) {
          if (this.enablePan === !1)
            return;
          this._handleMouseDownPan(e), this.state = Qs.PAN;
        } else {
          if (this.enableRotate === !1)
            return;
          this._handleMouseDownRotate(e), this.state = Qs.ROTATE;
        }
        break;
      case bt.PAN:
        if (_t.get(e, "ctrl") || _t.get(e, "meta") || _t.get(e, "shift")) {
          if (this.enableRotate === !1)
            return;
          this._handleMouseDownRotate(e), this.state = Qs.ROTATE;
        } else {
          if (this.enablePan === !1)
            return;
          this._handleMouseDownPan(e), this.state = Qs.PAN;
        }
        break;
      default:
        this.state = Qs.NONE;
    }
  }
  /**
   * Override _rotateLeft to respect horizontal rotation restriction.
   */
  _rotateLeft(e) {
    this._horizontalRotate && (this._sphericalDelta.theta -= e);
  }
  /**
   * Override _rotateUp to respect vertical rotation restriction.
   */
  _rotateUp(e) {
    this._verticalRotate && (this._sphericalDelta.phi -= e);
  }
  /**
   * Save the current state including quaternion.
   */
  saveState() {
    super.saveState(), this.quaternion0.copy(this.object.quaternion);
  }
  /**
   * Reset to saved state including quaternion.
   */
  reset() {
    this.target.copy(this.target0), this.object.position.copy(this.position0), this.object.quaternion.copy(this.quaternion0), (ia(this.object) || or(this.object)) && (this.object.zoom = this.zoom0, this.object.updateProjectionMatrix()), this.dispatchEvent({ type: "change" }), this.update(), this.state = -1;
  }
  /**
   * Rotate camera left (around the up axis).
   * Programmatic rotation bypasses modifier key restrictions.
   */
  rotateLeft(e) {
    this._sphericalDelta.theta -= e;
  }
  /**
   * Rotate camera up (around the right axis).
   * Programmatic rotation bypasses modifier key restrictions.
   */
  rotateUp(e) {
    this._sphericalDelta.phi -= e;
  }
}
const xh = { type: "change" }, qd = { type: "start" }, Zd = { type: "end" }, Jp = 1e-6, at = { NONE: -1, ROTATE: 0, ZOOM: 1, PAN: 2, TOUCH_ROTATE: 3, TOUCH_ZOOM_PAN: 4 }, Io = new H(), Cn = new H(), Vw = new b(), Do = new b(), bh = new b(), er = new ot(), Qp = new b(), No = new b(), Sh = new b(), Uo = new b();
class Gw extends zd {
  /**
   * Constructs a new controls instance.
   *
   * @param {Object3D} object - The object that is managed by the controls.
   * @param {?HTMLDOMElement} domElement - The HTML element used for event listeners.
   */
  constructor(e, t = null) {
    super(e, t), this.screen = { left: 0, top: 0, width: 0, height: 0 }, this.rotateSpeed = 1, this.zoomSpeed = 1.2, this.panSpeed = 0.3, this.noRotate = !1, this.noZoom = !1, this.noPan = !1, this.staticMoving = !1, this.dynamicDampingFactor = 0.2, this.minDistance = 0, this.maxDistance = 1 / 0, this.minZoom = 0, this.maxZoom = 1 / 0, this.keys = [
      "KeyA",
      "KeyS",
      "KeyD"
      /*D*/
    ], this.mouseButtons = { LEFT: bt.ROTATE, MIDDLE: bt.DOLLY, RIGHT: bt.PAN }, this.target = new b(), this.state = at.NONE, this.keyState = at.NONE, this._lastPosition = new b(), this._lastZoom = 1, this._touchZoomDistanceStart = 0, this._touchZoomDistanceEnd = 0, this._lastAngle = 0, this._eye = new b(), this._movePrev = new H(), this._moveCurr = new H(), this._lastAxis = new b(), this._zoomStart = new H(), this._zoomEnd = new H(), this._panStart = new H(), this._panEnd = new H(), this._pointers = [], this._pointerPositions = {}, this._onPointerMove = Xw.bind(this), this._onPointerDown = Ww.bind(this), this._onPointerUp = qw.bind(this), this._onPointerCancel = Zw.bind(this), this._onContextMenu = eE.bind(this), this._onMouseWheel = Qw.bind(this), this._onKeyDown = jw.bind(this), this._onKeyUp = Yw.bind(this), this._onTouchStart = tE.bind(this), this._onTouchMove = iE.bind(this), this._onTouchEnd = nE.bind(this), this._onMouseDown = $w.bind(this), this._onMouseMove = Kw.bind(this), this._onMouseUp = Jw.bind(this), this._target0 = this.target.clone(), this._position0 = this.object.position.clone(), this._up0 = this.object.up.clone(), this._zoom0 = this.object.zoom, t !== null && (this.connect(t), this.handleResize()), this.update();
  }
  connect(e) {
    super.connect(e), window.addEventListener("keydown", this._onKeyDown), window.addEventListener("keyup", this._onKeyUp), this.domElement.addEventListener("pointerdown", this._onPointerDown), this.domElement.addEventListener("pointercancel", this._onPointerCancel), this.domElement.addEventListener("wheel", this._onMouseWheel, { passive: !1 }), this.domElement.addEventListener("contextmenu", this._onContextMenu), this.domElement.style.touchAction = "none";
  }
  disconnect() {
    window.removeEventListener("keydown", this._onKeyDown), window.removeEventListener("keyup", this._onKeyUp), this.domElement.removeEventListener("pointerdown", this._onPointerDown), this.domElement.removeEventListener("pointermove", this._onPointerMove), this.domElement.removeEventListener("pointerup", this._onPointerUp), this.domElement.removeEventListener("pointercancel", this._onPointerCancel), this.domElement.removeEventListener("wheel", this._onMouseWheel), this.domElement.removeEventListener("contextmenu", this._onContextMenu), this.domElement.style.touchAction = "auto";
  }
  dispose() {
    this.disconnect();
  }
  /**
   * Must be called if the application window is resized.
   */
  handleResize() {
    const e = this.domElement.getBoundingClientRect(), t = this.domElement.ownerDocument.documentElement;
    this.screen.left = e.left + window.pageXOffset - t.clientLeft, this.screen.top = e.top + window.pageYOffset - t.clientTop, this.screen.width = e.width, this.screen.height = e.height;
  }
  update() {
    this._eye.subVectors(this.object.position, this.target), this.noRotate || this._rotateCamera(), this.noZoom || this._zoomCamera(), this.noPan || this._panCamera(), this.object.position.addVectors(this.target, this._eye), this.object.isPerspectiveCamera ? (this._checkDistances(), this.object.lookAt(this.target), this._lastPosition.distanceToSquared(this.object.position) > Jp && (this.dispatchEvent(xh), this._lastPosition.copy(this.object.position))) : this.object.isOrthographicCamera ? (this.object.lookAt(this.target), (this._lastPosition.distanceToSquared(this.object.position) > Jp || this._lastZoom !== this.object.zoom) && (this.dispatchEvent(xh), this._lastPosition.copy(this.object.position), this._lastZoom = this.object.zoom)) : console.warn("THREE.TrackballControls: Unsupported camera type.");
  }
  /**
   * Resets the controls to its initial state.
   */
  reset() {
    this.state = at.NONE, this.keyState = at.NONE, this.target.copy(this._target0), this.object.position.copy(this._position0), this.object.up.copy(this._up0), this.object.zoom = this._zoom0, this.object.updateProjectionMatrix(), this._eye.subVectors(this.object.position, this.target), this.object.lookAt(this.target), this.dispatchEvent(xh), this._lastPosition.copy(this.object.position), this._lastZoom = this.object.zoom;
  }
  _panCamera() {
    if (Cn.copy(this._panEnd).sub(this._panStart), Cn.lengthSq()) {
      if (this.object.isOrthographicCamera) {
        const e = (this.object.right - this.object.left) / this.object.zoom / this.domElement.clientWidth, t = (this.object.top - this.object.bottom) / this.object.zoom / this.domElement.clientWidth;
        Cn.x *= e, Cn.y *= t;
      }
      Cn.multiplyScalar(this._eye.length() * this.panSpeed), Do.copy(this._eye).cross(this.object.up).setLength(Cn.x), Do.add(Vw.copy(this.object.up).setLength(Cn.y)), this.object.position.add(Do), this.target.add(Do), this.staticMoving ? this._panStart.copy(this._panEnd) : this._panStart.add(Cn.subVectors(this._panEnd, this._panStart).multiplyScalar(this.dynamicDampingFactor));
    }
  }
  _rotateCamera() {
    Uo.set(this._moveCurr.x - this._movePrev.x, this._moveCurr.y - this._movePrev.y, 0);
    let e = Uo.length();
    e ? (this._eye.copy(this.object.position).sub(this.target), Qp.copy(this._eye).normalize(), No.copy(this.object.up).normalize(), Sh.crossVectors(No, Qp).normalize(), No.setLength(this._moveCurr.y - this._movePrev.y), Sh.setLength(this._moveCurr.x - this._movePrev.x), Uo.copy(No.add(Sh)), bh.crossVectors(Uo, this._eye).normalize(), e *= this.rotateSpeed, er.setFromAxisAngle(bh, e), this._eye.applyQuaternion(er), this.object.up.applyQuaternion(er), this._lastAxis.copy(bh), this._lastAngle = e) : !this.staticMoving && this._lastAngle && (this._lastAngle *= Math.sqrt(1 - this.dynamicDampingFactor), this._eye.copy(this.object.position).sub(this.target), er.setFromAxisAngle(this._lastAxis, this._lastAngle), this._eye.applyQuaternion(er), this.object.up.applyQuaternion(er)), this._movePrev.copy(this._moveCurr);
  }
  _zoomCamera() {
    let e;
    this.state === at.TOUCH_ZOOM_PAN ? (e = this._touchZoomDistanceStart / this._touchZoomDistanceEnd, this._touchZoomDistanceStart = this._touchZoomDistanceEnd, this.object.isPerspectiveCamera ? this._eye.multiplyScalar(e) : this.object.isOrthographicCamera ? (this.object.zoom = da.clamp(this.object.zoom / e, this.minZoom, this.maxZoom), this._lastZoom !== this.object.zoom && this.object.updateProjectionMatrix()) : console.warn("THREE.TrackballControls: Unsupported camera type")) : (e = 1 + (this._zoomEnd.y - this._zoomStart.y) * this.zoomSpeed, e !== 1 && e > 0 && (this.object.isPerspectiveCamera ? this._eye.multiplyScalar(e) : this.object.isOrthographicCamera ? (this.object.zoom = da.clamp(this.object.zoom / e, this.minZoom, this.maxZoom), this._lastZoom !== this.object.zoom && this.object.updateProjectionMatrix()) : console.warn("THREE.TrackballControls: Unsupported camera type")), this.staticMoving ? this._zoomStart.copy(this._zoomEnd) : this._zoomStart.y += (this._zoomEnd.y - this._zoomStart.y) * this.dynamicDampingFactor);
  }
  _getMouseOnScreen(e, t) {
    return Io.set(
      (e - this.screen.left) / this.screen.width,
      (t - this.screen.top) / this.screen.height
    ), Io;
  }
  _getMouseOnCircle(e, t) {
    return Io.set(
      (e - this.screen.width * 0.5 - this.screen.left) / (this.screen.width * 0.5),
      (this.screen.height + 2 * (this.screen.top - t)) / this.screen.width
      // screen.width intentional
    ), Io;
  }
  _addPointer(e) {
    this._pointers.push(e);
  }
  _removePointer(e) {
    delete this._pointerPositions[e.pointerId];
    for (let t = 0; t < this._pointers.length; t++)
      if (this._pointers[t].pointerId == e.pointerId) {
        this._pointers.splice(t, 1);
        return;
      }
  }
  _trackPointer(e) {
    let t = this._pointerPositions[e.pointerId];
    t === void 0 && (t = new H(), this._pointerPositions[e.pointerId] = t), t.set(e.pageX, e.pageY);
  }
  _getSecondPointerPosition(e) {
    const t = e.pointerId === this._pointers[0].pointerId ? this._pointers[1] : this._pointers[0];
    return this._pointerPositions[t.pointerId];
  }
  _checkDistances() {
    (!this.noZoom || !this.noPan) && (this._eye.lengthSq() > this.maxDistance * this.maxDistance && (this.object.position.addVectors(this.target, this._eye.setLength(this.maxDistance)), this._zoomStart.copy(this._zoomEnd)), this._eye.lengthSq() < this.minDistance * this.minDistance && (this.object.position.addVectors(this.target, this._eye.setLength(this.minDistance)), this._zoomStart.copy(this._zoomEnd)));
  }
}
function Ww(r) {
  this.enabled !== !1 && (this._pointers.length === 0 && (this.domElement.setPointerCapture(r.pointerId), this.domElement.addEventListener("pointermove", this._onPointerMove), this.domElement.addEventListener("pointerup", this._onPointerUp)), this._addPointer(r), r.pointerType === "touch" ? this._onTouchStart(r) : this._onMouseDown(r));
}
function Xw(r) {
  this.enabled !== !1 && (r.pointerType === "touch" ? this._onTouchMove(r) : this._onMouseMove(r));
}
function qw(r) {
  this.enabled !== !1 && (r.pointerType === "touch" ? this._onTouchEnd(r) : this._onMouseUp(), this._removePointer(r), this._pointers.length === 0 && (this.domElement.releasePointerCapture(r.pointerId), this.domElement.removeEventListener("pointermove", this._onPointerMove), this.domElement.removeEventListener("pointerup", this._onPointerUp)));
}
function Zw(r) {
  this._removePointer(r);
}
function Yw() {
  this.enabled !== !1 && (this.keyState = at.NONE, window.addEventListener("keydown", this._onKeyDown));
}
function jw(r) {
  this.enabled !== !1 && (window.removeEventListener("keydown", this._onKeyDown), this.keyState === at.NONE && (r.code === this.keys[at.ROTATE] && !this.noRotate ? this.keyState = at.ROTATE : r.code === this.keys[at.ZOOM] && !this.noZoom ? this.keyState = at.ZOOM : r.code === this.keys[at.PAN] && !this.noPan && (this.keyState = at.PAN)));
}
function $w(r) {
  let e;
  switch (r.button) {
    case 0:
      e = this.mouseButtons.LEFT;
      break;
    case 1:
      e = this.mouseButtons.MIDDLE;
      break;
    case 2:
      e = this.mouseButtons.RIGHT;
      break;
    default:
      e = -1;
  }
  switch (e) {
    case bt.DOLLY:
      this.state = at.ZOOM;
      break;
    case bt.ROTATE:
      this.state = at.ROTATE;
      break;
    case bt.PAN:
      this.state = at.PAN;
      break;
    default:
      this.state = at.NONE;
  }
  const t = this.keyState !== at.NONE ? this.keyState : this.state;
  t === at.ROTATE && !this.noRotate ? (this._moveCurr.copy(this._getMouseOnCircle(r.pageX, r.pageY)), this._movePrev.copy(this._moveCurr)) : t === at.ZOOM && !this.noZoom ? (this._zoomStart.copy(this._getMouseOnScreen(r.pageX, r.pageY)), this._zoomEnd.copy(this._zoomStart)) : t === at.PAN && !this.noPan && (this._panStart.copy(this._getMouseOnScreen(r.pageX, r.pageY)), this._panEnd.copy(this._panStart)), this.dispatchEvent(qd);
}
function Kw(r) {
  const e = this.keyState !== at.NONE ? this.keyState : this.state;
  e === at.ROTATE && !this.noRotate ? (this._movePrev.copy(this._moveCurr), this._moveCurr.copy(this._getMouseOnCircle(r.pageX, r.pageY))) : e === at.ZOOM && !this.noZoom ? this._zoomEnd.copy(this._getMouseOnScreen(r.pageX, r.pageY)) : e === at.PAN && !this.noPan && this._panEnd.copy(this._getMouseOnScreen(r.pageX, r.pageY));
}
function Jw() {
  this.state = at.NONE, this.dispatchEvent(Zd);
}
function Qw(r) {
  if (this.enabled !== !1 && this.noZoom !== !0) {
    switch (r.preventDefault(), r.deltaMode) {
      case 2:
        this._zoomStart.y -= r.deltaY * 0.025;
        break;
      case 1:
        this._zoomStart.y -= r.deltaY * 0.01;
        break;
      default:
        this._zoomStart.y -= r.deltaY * 25e-5;
        break;
    }
    this.dispatchEvent(qd), this.dispatchEvent(Zd);
  }
}
function eE(r) {
  this.enabled !== !1 && r.preventDefault();
}
function tE(r) {
  switch (this._trackPointer(r), this._pointers.length) {
    case 1:
      this.state = at.TOUCH_ROTATE, this._moveCurr.copy(this._getMouseOnCircle(this._pointers[0].pageX, this._pointers[0].pageY)), this._movePrev.copy(this._moveCurr);
      break;
    default:
      this.state = at.TOUCH_ZOOM_PAN;
      const e = this._pointers[0].pageX - this._pointers[1].pageX, t = this._pointers[0].pageY - this._pointers[1].pageY;
      this._touchZoomDistanceEnd = this._touchZoomDistanceStart = Math.sqrt(e * e + t * t);
      const i = (this._pointers[0].pageX + this._pointers[1].pageX) / 2, n = (this._pointers[0].pageY + this._pointers[1].pageY) / 2;
      this._panStart.copy(this._getMouseOnScreen(i, n)), this._panEnd.copy(this._panStart);
      break;
  }
  this.dispatchEvent(qd);
}
function iE(r) {
  switch (this._trackPointer(r), this._pointers.length) {
    case 1:
      this._movePrev.copy(this._moveCurr), this._moveCurr.copy(this._getMouseOnCircle(r.pageX, r.pageY));
      break;
    default:
      const e = this._getSecondPointerPosition(r), t = r.pageX - e.x, i = r.pageY - e.y;
      this._touchZoomDistanceEnd = Math.sqrt(t * t + i * i);
      const n = (r.pageX + e.x) / 2, s = (r.pageY + e.y) / 2;
      this._panEnd.copy(this._getMouseOnScreen(n, s));
      break;
  }
}
function nE(r) {
  switch (this._pointers.length) {
    case 0:
      this.state = at.NONE;
      break;
    case 1:
      this.state = at.TOUCH_ROTATE, this._moveCurr.copy(this._getMouseOnCircle(r.pageX, r.pageY)), this._movePrev.copy(this._moveCurr);
      break;
    case 2:
      this.state = at.TOUCH_ZOOM_PAN;
      for (let e = 0; e < this._pointers.length; e++)
        if (this._pointers[e].pointerId !== r.pointerId) {
          const t = this._pointerPositions[this._pointers[e].pointerId];
          this._moveCurr.copy(this._getMouseOnCircle(t.x, t.y)), this._movePrev.copy(this._moveCurr);
          break;
        }
      break;
  }
  this.dispatchEvent(Zd);
}
const Rn = {
  NONE: -1,
  ROTATE: 0,
  ZOOM: 1,
  PAN: 2
}, ef = new ot();
let tf = 1;
const tr = new ot(), Vr = new b(), Mh = new b(), wh = new b(), sE = new b(), Oo = new b(), Fo = new b();
class Eh extends Gw {
  /**
   * Constructs CAD-enhanced trackball controls.
   *
   * @param object - The camera to control.
   * @param domElement - The HTML element for event listeners.
   */
  constructor(e, t = null) {
    super(e, t), this.holroyd = !0, this.radius = 0.9, this.quaternion0 = this.object.quaternion.clone(), this._holroydStart = new H(), this._holroydEnd = new H(), this._holroydActive = !1, this._horizontalRotate = !0, this._verticalRotate = !0, t && (this._holroydPointerDown = this._onHolroydPointerDown.bind(this), this._holroydPointerMove = this._onHolroydPointerMove.bind(this), this._holroydPointerUp = this._onHolroydPointerUp.bind(this), this._holroydWheel = this._onHolroydWheel.bind(this), t.addEventListener("pointerdown", this._holroydPointerDown), t.addEventListener("pointermove", this._holroydPointerMove), t.addEventListener("pointerup", this._holroydPointerUp), t.addEventListener("pointercancel", this._holroydPointerUp), t.addEventListener("wheel", this._holroydWheel, {
      passive: !1
    })), this._parentOnMouseDown = this._onMouseDown, this._onMouseDown = this._handleMouseDown.bind(this);
  }
  /**
   * Custom mouse down handler to support shift+drag for pan.
   * When holroyd=false, delegates to parent for pure Three.js behavior.
   */
  _handleMouseDown(e) {
    if (!this.holroyd) {
      this._parentOnMouseDown(e);
      return;
    }
    let t;
    switch (e.button) {
      case 0:
        t = this.mouseButtons.LEFT;
        break;
      case 1:
        t = this.mouseButtons.MIDDLE;
        break;
      case 2:
        t = this.mouseButtons.RIGHT;
        break;
      default:
        t = -1;
    }
    switch (t === bt.ROTATE && _t.get(e, "shift") && (t = bt.PAN), t) {
      case bt.DOLLY:
        this.state = Rn.ZOOM;
        break;
      case bt.ROTATE:
        this.state = Rn.ROTATE;
        break;
      case bt.PAN:
        this.state = Rn.PAN;
        break;
      default:
        this.state = Rn.NONE;
    }
    const i = this.keyState !== Rn.NONE ? this.keyState : this.state;
    i === Rn.ROTATE && !this.noRotate ? (this._moveCurr.copy(this._getMouseOnCircle(e.pageX, e.pageY)), this._movePrev.copy(this._moveCurr)) : i === Rn.ZOOM && !this.noZoom ? (this._zoomStart.copy(this._getMouseOnScreen(e.pageX, e.pageY)), this._zoomEnd.copy(this._zoomStart)) : i === Rn.PAN && !this.noPan && (this._panStart.copy(this._getMouseOnScreen(e.pageX, e.pageY)), this._panEnd.copy(this._panStart)), this.dispatchEvent({ type: "start" });
  }
  /**
   * Capture raw pointer coordinates on pointer down for holroyd.
   * Works for all pointer types (mouse, touch, pen, trackpad).
   * Also checks modifier keys for rotation axis restriction.
   */
  _onHolroydPointerDown(e) {
    this.holroyd && e.button === 0 && (_t.get(e, "shift") || (this._holroydStart.set(e.pageX, e.pageY), this._holroydEnd.set(e.pageX, e.pageY), this._holroydActive = !0, this._horizontalRotate = !_t.get(e, "ctrl"), this._verticalRotate = !_t.get(e, "meta")));
  }
  /**
   * Capture raw pointer coordinates on pointer move for holroyd.
   * Only captures when actively dragging.
   * Works for all pointer types (mouse, touch, pen, trackpad).
   */
  _onHolroydPointerMove(e) {
    this.holroyd && this._holroydActive && this._holroydEnd.set(e.pageX, e.pageY), this.state !== -1 && this.update();
  }
  /**
   * Reset holroyd active state and rotation restrictions on pointer up.
   */
  _onHolroydPointerUp() {
    this._holroydActive = !1, this._horizontalRotate = !0, this._verticalRotate = !0;
  }
  /**
   * Handle wheel events for zoom - call update after parent processes wheel.
   * This enables change-listener mode (non-animation loop) to work for zoom.
   */
  _onHolroydWheel() {
    this.update();
  }
  /**
   * Override dispose to clean up our event listeners.
   */
  dispose() {
    this.domElement && this._holroydPointerDown && this._holroydPointerMove && this._holroydPointerUp && this._holroydWheel && (this.domElement.removeEventListener("pointerdown", this._holroydPointerDown), this.domElement.removeEventListener("pointermove", this._holroydPointerMove), this.domElement.removeEventListener("pointerup", this._holroydPointerUp), this.domElement.removeEventListener("pointercancel", this._holroydPointerUp), this.domElement.removeEventListener("wheel", this._holroydWheel)), super.dispose();
  }
  /**
   * Save the current state including quaternion.
   */
  saveState() {
    this._target0.copy(this.target), this._position0.copy(this.object.position), this._up0.copy(this.object.up), (ia(this.object) || or(this.object)) && (this._zoom0 = this.object.zoom), this.quaternion0.copy(this.object.quaternion);
  }
  /**
   * Reset to saved state including quaternion.
   */
  reset() {
    super.reset(), this.object.quaternion.copy(this.quaternion0);
  }
  // Expose saved state properties for compatibility with controls.js
  get target0() {
    return this._target0;
  }
  get position0() {
    return this._position0;
  }
  get zoom0() {
    return this._zoom0;
  }
  set zoom0(e) {
    this._zoom0 = e;
  }
  /**
   * Project page coordinates onto the holroyd trackball sphere.
   * Uses the original CameraControls coordinate system:
   * - NDC x: -1 (left) to +1 (right)
   * - NDC y: -1 (bottom) to +1 (top)
   */
  _getMouseOnSphere(e, t, i) {
    const n = this.domElement.getBoundingClientRect(), s = this._horizontalRotate ? (e - n.left) / (n.width / 2) - 1 : 0, a = this._verticalRotate ? 1 - (t - n.top) / (n.height / 2) : 0, o = this.radius * this.radius, l = s * s + a * a;
    return l <= o / 2 ? i.set(s, a, Math.sqrt(o - l)) : i.set(s, a, o / (2 * Math.sqrt(l))), i;
  }
  /**
   * Override update to skip lookAt in holroyd mode.
   *
   * Standard TrackballControls calls lookAt() which recomputes the quaternion
   * from position and up. In holroyd mode, we set the quaternion directly,
   * so lookAt() would destroy the tilted rotation axis effect.
   *
   * When holroyd=false, delegates to parent for pure Three.js behavior.
   */
  update() {
    if (!this.holroyd) {
      super.update();
      return;
    }
    this._eye.subVectors(this.object.position, this.target), this.noRotate || this._rotateCamera(), this.noZoom || this._zoomCamera(), this.noPan || this._panCamera(), this.object.position.addVectors(this.target, this._eye);
    const e = ia(this.object) || or(this.object) ? this.object.zoom : 1, t = Math.abs(e - tf) > 1e-6;
    (this._lastPosition.distanceToSquared(this.object.position) > 1e-6 || ef.dot(this.object.quaternion) < 0.999999 || t) && (this.dispatchEvent({ type: "change" }), this._lastPosition.copy(this.object.position), ef.copy(this.object.quaternion), tf = e);
  }
  /**
   * Override rotation to support holroyd mode.
   *
   * The key difference from standard TrackballControls:
   * - Standard: uses delta-based rotation from _moveCurr - _movePrev
   * - Holroyd: projects absolute positions onto a virtual sphere
   *
   * This gives the "grab and rotate" feel where the rotation axis
   * depends on WHERE you grab, not just HOW you move.
   */
  _rotateCamera() {
    if (!this.holroyd) {
      super._rotateCamera();
      return;
    }
    if (this._holroydStart.x === this._holroydEnd.x && this._holroydStart.y === this._holroydEnd.y) {
      this._movePrev.copy(this._moveCurr);
      return;
    }
    this._getMouseOnSphere(this._holroydStart.x, this._holroydStart.y, Mh), this._getMouseOnSphere(this._holroydEnd.x, this._holroydEnd.y, wh), Vr.crossVectors(Mh, wh);
    const e = Math.atan(Vr.length() / Mh.dot(wh));
    if (e) {
      Vr.normalize(), Vr.applyQuaternion(this.object.quaternion);
      const t = -2 * e * this.rotateSpeed;
      tr.setFromAxisAngle(Vr, t), this.object.quaternion.premultiply(tr), this._eye.applyQuaternion(tr);
    }
    this._holroydStart.copy(this._holroydEnd), this._movePrev.copy(this._moveCurr);
  }
  /**
   * Override pan to use quaternion-based camera orientation in holroyd mode.
   *
   * The parent TrackballControls uses this.object.up for pan direction,
   * but in holroyd mode we rotate via quaternion without updating up.
   * This calculates pan direction from the camera's actual orientation.
   */
  _panCamera() {
    if (!this.holroyd) {
      super._panCamera();
      return;
    }
    const e = sE.set(this._panEnd.x - this._panStart.x, this._panEnd.y - this._panStart.y, 0);
    if (e.lengthSq() !== 0) {
      if (or(this.object)) {
        const t = (this.object.right - this.object.left) / this.object.zoom, i = (this.object.top - this.object.bottom) / this.object.zoom;
        e.x *= t * this.panSpeed * 4, e.y *= i * this.panSpeed * 4;
      } else if (ia(this.object) && this.domElement) {
        const t = this.domElement.clientWidth / this.domElement.clientHeight;
        e.x *= t, e.multiplyScalar(this._eye.length() * this.panSpeed * 1.6);
      } else
        e.multiplyScalar(this._eye.length() * this.panSpeed * 2);
      Fo.set(1, 0, 0).applyQuaternion(this.object.quaternion), Oo.set(0, 1, 0).applyQuaternion(this.object.quaternion), Fo.multiplyScalar(-e.x), Oo.multiplyScalar(e.y), this.object.position.add(Fo).add(Oo), this.target.add(Fo).add(Oo), this._panStart.copy(this._panEnd);
    }
  }
  /**
   * Rotate camera around world X-axis.
   */
  rotateX(e) {
    this._rotateAroundAxis("x", e);
  }
  /**
   * Rotate camera around world Y-axis.
   */
  rotateY(e) {
    this._rotateAroundAxis("y", e);
  }
  /**
   * Rotate camera around world Z-axis.
   */
  rotateZ(e) {
    this._rotateAroundAxis("z", e);
  }
  /**
   * Internal method to rotate around a world axis.
   */
  _rotateAroundAxis(e, t) {
    const i = gg[e];
    tr.setFromAxisAngle(i, t), this.object.quaternion.premultiply(tr), this.object.position.sub(this.target).applyQuaternion(tr).add(this.target);
  }
}
const rE = {
  trackball: {
    pan: 0.22,
    rotate: 1,
    zoom: 0.5
  },
  orbit: {
    pan: 1,
    rotate: 1,
    zoom: 1
  }
};
class aE {
  /**
   * Create Camera Controls.
   * @param type - Type of controls: "orbit", "trackball".
   * @param camera - The camera object.
   * @param target - The lookAt target for the camera.
   * @param domElement - The dom element of the rendering canvas.
   * @param rotateSpeed - Speed for rotating.
   * @param zoomSpeed - Speed for zooming.
   * @param panSpeed - Speed for panning.
   * @param holroyd - Enable holroyd (non-tumbling) mode for trackball.
   */
  constructor(e, t, i, n, s = 1, a = 1, o = 1, l = !0) {
    switch (this.getResetLocation = () => ({
      target0: this.controls.target0.clone(),
      position0: this.controls.position0.clone(),
      quaternion0: this.controls.quaternion0.clone(),
      zoom0: this.controls.zoom0
    }), this.setResetLocation = (c, h, d, u) => {
      this.controls.target0.copy(c), this.controls.position0.copy(h), this.controls.quaternion0.copy(d), this.controls.zoom0 = u;
    }, this.type = e, this.camera = t, this.target = i, this.target0 = i.clone(), this.domElement = n, this.rotateSpeed = s, this.zoomSpeed = a, this.panSpeed = o, this.holroyd = l, e) {
      case "orbit":
        this.initOrbitControls();
        break;
      case "trackball":
        this.initTrackballControls(l);
        break;
    }
    this.controls.target.copy(this.target), this._applySpeedFactors(), this.currentUpdateCallback = null, this.saveState(), this.update();
  }
  /**
   * Get the speed factors for the current control type.
   */
  _getSpeedFactors() {
    return rE[this.type];
  }
  /**
   * Apply speed factors to controls.
   */
  _applySpeedFactors() {
    const e = this._getSpeedFactors();
    this.controls.rotateSpeed = this.rotateSpeed * e.rotate, this.controls.zoomSpeed = this.zoomSpeed * e.zoom, this.controls.panSpeed = this.panSpeed * e.pan;
  }
  /**
   * Remove assets and event handlers.
   */
  dispose() {
    this.controls.dispose();
  }
  /**
   * Save state for reset.
   */
  saveState() {
    this.controls.saveState();
  }
  /**
   * Initialize Trackball Controls.
   * @param holroyd - enable holroyd (non tumbling) mode.
   */
  initTrackballControls(e = !0) {
    this.controls = new Eh(this.camera, this.domElement), this.setHolroydTrackball(e);
  }
  /**
   * Initialize Orbit Controls.
   */
  initOrbitControls() {
    this.controls = new Kp(this.camera, this.domElement);
  }
  /**
   * Add an event listener callback for the "change" event.
   * @param callback - the callback function.
   */
  addChangeListener(e) {
    this.currentUpdateCallback == null && (this.currentUpdateCallback = e, this.controls.addEventListener("change", e));
  }
  /**
   * Remove the event listener callback for the "change" event.
   */
  removeChangeListener() {
    this.currentUpdateCallback != null && (this.controls.removeEventListener("change", this.currentUpdateCallback), this.currentUpdateCallback = null);
  }
  /**
   * Update controls after camera position, zoom or quaternion changes.
   */
  update() {
    this.controls.update();
  }
  /**
   * Update screen dimensions after canvas resize.
   * Only applies to TrackballControls which caches screen dimensions.
   */
  handleResize() {
    this.controls instanceof Eh && this.controls.handleResize();
  }
  /**
   * Reset camera to initial (automatically saved) state of position, up, quaternion and zoom.
   */
  reset() {
    this.controls.reset();
  }
  /**
   * Set the camera to be controlled.
   * @param camera - a threejs Camera object.
   */
  setCamera(e) {
    this.controls.object = e;
  }
  /**
   * Change the trackball holroyd (non tumbling) flag.
   * @param flag - holroyd mode enabled.
   */
  setHolroydTrackball(e) {
    this.getTrackballControls().holroyd = e;
  }
  /**
   * Get the lookAt target of the camera.
   * @returns The lookAt target
   */
  getTarget() {
    return this.controls.target;
  }
  /**
   * Check if the user is currently interacting with the controls (rotating, panning, zooming).
   * @returns true if user is dragging/interacting, false otherwise.
   */
  isInteracting() {
    return this.controls.state !== -1;
  }
  /**
   * Get the initial zoom value of the camera.
   */
  getZoom0() {
    return this.controls.zoom0;
  }
  /**
   * Set the lookAt target of the camera.
   * @param target - camera target as THREE.Vector3.
   */
  setTarget(e) {
    this.controls.target.copy(e);
  }
  /**
   * Set the zoom speed.
   * @param val - the speed value (1.0 = default).
   */
  setZoomSpeed(e) {
    this.zoomSpeed = e, this.controls.zoomSpeed = e * this._getSpeedFactors().zoom;
  }
  /**
   * Set the pan speed.
   * @param val - the speed value (1.0 = default).
   */
  setPanSpeed(e) {
    this.panSpeed = e, this.controls.panSpeed = e * this._getSpeedFactors().pan;
  }
  /**
   * Set the rotate speed.
   * @param val - the speed value (1.0 = default).
   */
  setRotateSpeed(e) {
    this.rotateSpeed = e, this.controls.rotateSpeed = e * this._getSpeedFactors().rotate;
  }
  // Type-safe accessors for control-specific methods
  getOrbitControls() {
    if (!(this.controls instanceof Kp))
      throw new Error("Operation requires OrbitControls");
    return this.controls;
  }
  getTrackballControls() {
    if (!(this.controls instanceof Eh))
      throw new Error("Operation requires TrackballControls");
    return this.controls;
  }
  // Rotations for OrbitControls
  /**
   * Rotate camera up (OrbitControls only)
   * @param angle - the angle to rotate.
   */
  rotateUp(e) {
    this.getOrbitControls().rotateUp(-e / 180 * Math.PI), this.update();
  }
  /**
   * Rotate camera left (OrbitControls only)
   * @param angle - the angle to rotate.
   */
  rotateLeft(e) {
    this.getOrbitControls().rotateLeft(e / 180 * Math.PI), this.update();
  }
  // Rotations for TrackballControls
  /**
   * Rotate camera around x-axis (TrackballControls only)
   * @param angle - the angle to rotate.
   */
  rotateX(e) {
    this.getTrackballControls().rotateX(e / 180 * Math.PI), this.update();
  }
  /**
   * Rotate camera around y-axis (TrackballControls only)
   * @param angle - the angle to rotate.
   */
  rotateY(e) {
    this.getTrackballControls().rotateY(e / 180 * Math.PI), this.update();
  }
  /**
   * Rotate camera around z-axis (TrackballControls only)
   * @param angle - the angle to rotate.
   */
  rotateZ(e) {
    this.getTrackballControls().rotateZ(e / 180 * Math.PI), this.update();
  }
}
const nf = {
  y_up: {
    // compatible to fusion 360
    iso: { pos: new b(1, 1, 1), quat: null },
    front: { pos: new b(0, 0, 1), quat: null },
    rear: { pos: new b(0, 0, -1), quat: null },
    left: { pos: new b(-1, 0, 0), quat: null },
    right: { pos: new b(1, 0, 0), quat: null },
    top: { pos: new b(0, 1, 0), quat: null },
    bottom: { pos: new b(0, -1, 0), quat: null }
  },
  z_up: {
    // compatible to FreeCAD, OnShape
    iso: { pos: new b(1, -1, 1), quat: null },
    front: { pos: new b(0, -1, 0), quat: null },
    rear: { pos: new b(0, 1, 0), quat: null },
    left: { pos: new b(-1, 0, 0), quat: null },
    right: { pos: new b(1, 0, 0), quat: null },
    top: { pos: new b(0, 0, 1), quat: new ot(0, 0, 0, 1) },
    bottom: { pos: new b(0, 0, -1), quat: new ot(1, 0, 0, 0) }
  },
  legacy: {
    // legacy Z up
    iso: { pos: new b(1, 1, 1), quat: null },
    front: { pos: new b(1, 0, 0), quat: null },
    rear: { pos: new b(-1, 0, 0), quat: null },
    left: { pos: new b(0, 1, 0), quat: null },
    right: { pos: new b(0, -1, 0), quat: null },
    top: { pos: new b(0, 0, 1), quat: null },
    bottom: { pos: new b(0, 0, -1), quat: null }
  }
}, Th = {
  y_up: [0, 1, 0],
  z_up: [0, 0, 1],
  legacy: [0, 0, 1]
};
class va {
  /**
   * Create a combined camera (orthographic and perspective).
   * @param width - canvas width.
   * @param height - canvas height.
   * @param distance - distance from the lookAt point.
   * @param target - target (Vector3) to look at.
   * @param ortho - flag whether the initial camera should be orthographic.
   * @param up - Z or Y to define whether Z or Y direction is camera up.
   */
  constructor(e, t, i, n, s, a) {
    const o = {
      Y: "y_up",
      Z: "z_up",
      L: "legacy"
    };
    this.target = new b(...n), this.ortho = s, this.up = o[a] || "z_up", this.yaxis = new b(0, 1, 0), this.zaxis = new b(0, 0, 1);
    const l = e / t, c = 22;
    this.camera_distance = va.DISTANCE_FACTOR * i, this.pCamera = new kt(c, l, 0.1, 100 * i), this.pCamera.up.set(...Th[this.up]), this.pCamera.lookAt(this.target);
    const h = this.projectSize(i, l);
    this.oCamera = new kn(-h[0], h[0], h[1], -h[1], 0.1, 100 * i), this.oCamera.up.set(...Th[this.up]), this.oCamera.lookAt(this.target), this.camera = s ? this.oCamera : this.pCamera, this.camera.up.set(...Th[this.up]);
  }
  /**
   * Update the far clipping plane for both cameras.
   * @param distance - The new bounding radius to base the far plane on.
   */
  updateFarPlane(e) {
    const t = 100 * e;
    this.pCamera.far = t, this.oCamera.far = t, this.camera.updateProjectionMatrix();
  }
  /**
   * Recalculate camera_distance from a new bounding radius.
   * Uses the same factor as the constructor so that zoom 1.0 frames the scene.
   * @param distance - The new bounding radius (bb_radius).
   */
  updateCameraDistance(e) {
    this.camera_distance = va.DISTANCE_FACTOR * e;
  }
  /**
   * Remove assets.
   */
  dispose() {
  }
  /**
   * Get the current camera.
   * @returns Camera object.
   */
  getCamera() {
    return this.camera;
  }
  /**
   * Set the lookAt point for the camera to the provided target.
   */
  lookAtTarget() {
    this.camera.lookAt(this.target);
  }
  /**
   * Update current camera's projection matrix.
   */
  updateProjectionMatrix() {
    this.camera.updateProjectionMatrix();
  }
  /**
   * Switch between orthographic and perspective camera.
   * @param ortho_flag - true for orthographic camera, else perspective camera.
   */
  switchCamera(e) {
    const t = this.getPosition().clone(), i = this.getZoom(), n = this.getQuaternion().clone();
    e ? (this.camera = this.oCamera, this.ortho = !0) : (this.camera = this.pCamera, this.ortho = !1), this.setPosition(t, !1), this.setZoom(i), this.setQuaternion(n), this.updateProjectionMatrix();
  }
  /**
   * Calculate projected size for orthographic camera.
   * @param frustum - View frustum size.
   * @param aspect - Viewer aspect ratio (width / height).
   * @returns Width and height [w, h] for the orthographic camera.
   */
  projectSize(e, t) {
    let i, n;
    return t < 1 ? (i = e, n = i / t) : (n = e, i = n * t), [i, n];
  }
  /**
   * Setup the current camera.
   * @param relative - flag whether the position is a relative (e.g. [1,1,1] for iso) or absolute point.
   * @param position - the camera position (relative or absolute).
   * @param quaternion - the camera rotation expressed by a quaternion.
   * @param zoom - zoom value.
   */
  setupCamera(e, t = null, i = null, n = null) {
    if (t != null) {
      const s = e ? t.clone().normalize().multiplyScalar(this.camera_distance).add(this.target) : t;
      this.camera.position.set(...s.toArray());
    }
    i != null && this.camera.quaternion.set(...i.toArray()), n != null && this.setZoom(n), this.updateProjectionMatrix();
  }
  /**
   * Move the camera to a given preset.
   * @param dir - can be "iso", "top", "bottom", "front", "rear", "left", "right"
   */
  presetCamera(e, t = null) {
    t == null && (t = this.camera.zoom), this.setupCamera(!0, nf[this.up][e].pos, null, t), this.lookAtTarget();
    const i = nf[this.up][e].quat;
    i != null && this.setQuaternion(i);
  }
  /**
   * Return current zoom value.
   * @returns zoom value.
   */
  getZoom() {
    if (this.ortho)
      return this.camera.zoom;
    {
      const e = this.camera.position.clone().sub(this.target);
      return this.camera_distance / e.length();
    }
  }
  /**
   * Set zoom value.
   * @param val - float zoom value.
   */
  setZoom(e) {
    this.ortho ? this.camera.zoom = e : this.camera.position.sub(this.target).setLength(this.camera_distance / e).add(this.target), this.updateProjectionMatrix();
  }
  /**
   * Get the current camera position.
   * @returns camera position.
   */
  getPosition() {
    return this.camera.position;
  }
  /**
   * Set camera position.
   * @param position - position as 3 dim Array [x,y,z] or as Vector3.
   * @param relative - flag whether the position is a relative (e.g. [1,1,1] for iso) or absolute point.
   */
  setPosition(e, t) {
    Array.isArray(e) && e.length === 3 ? this.setupCamera(t, new b(...e)) : e instanceof b ? this.setupCamera(t, e) : ft.error("wrong type for position", e);
  }
  /**
   * Get the current camera quaternion.
   * @returns camera quaternion.
   */
  getQuaternion() {
    return this.camera.quaternion;
  }
  /**
   * Set camera quaternion.
   * @param quaternion - quaternion as 4 dim Array or as Quaternion.
   */
  setQuaternion(e) {
    Array.isArray(e) && e.length === 4 ? this.setupCamera(!1, null, new ot(...e)) : e instanceof ot ? this.setupCamera(!1, null, e) : ft.error("wrong type for quaternion", e), this.updateProjectionMatrix();
  }
  /**
   * Get the current camera rotation.
   * @returns camera rotation.
   */
  getRotation() {
    return this.camera.rotation;
  }
  /**
   * Get the visible area dimensions at the target plane.
   * @returns The visible width and height.
   */
  getVisibleArea() {
    if (this.ortho && this.oCamera) {
      const e = (this.oCamera.top - this.oCamera.bottom) / this.oCamera.zoom;
      return { width: (this.oCamera.right - this.oCamera.left) / this.oCamera.zoom, height: e };
    } else if (this.pCamera) {
      const e = this.pCamera.position.distanceTo(this.target), t = this.pCamera.fov * Math.PI / 180, i = 2 * Math.tan(t / 2) * e;
      return { width: i * this.pCamera.aspect, height: i };
    }
    return { width: 0, height: 0 };
  }
  /**
   * Update camera dimensions when viewport size changes.
   * @param distance - Distance used for orthographic frustum calculation.
   * @param width - New viewport width in pixels.
   * @param height - New viewport height in pixels.
   */
  changeDimensions(e, t, i) {
    const n = t / i, s = this.projectSize(e, n);
    this.oCamera && (this.oCamera.left = -s[0], this.oCamera.right = s[0], this.oCamera.top = s[1], this.oCamera.bottom = -s[1]), this.pCamera && (this.pCamera.aspect = n), this.camera && this.camera.updateProjectionMatrix();
  }
}
va.DISTANCE_FACTOR = 5;
const ys = {
  none: null,
  vertex: "vertex",
  edge: "edge",
  face: "face",
  solid: "solid"
};
class oE {
  /**
   * Create a PickedObject.
   * @param objectGroup - The picked ObjectGroup.
   * @param fromSolid - Whether this pick is from a solid selection.
   */
  constructor(e, t) {
    this.obj = e, this.fromSolid = t;
  }
  /**
   * Returns all the faces ObjectGroups that define the solid from the picked object.
   */
  _getSolidObjectGroups(e) {
    const t = e.parent.parent;
    let i;
    for (let n = 0; n < t.children.length; n++) {
      const s = t.children[n];
      if (s.name === t.name + "|faces") {
        i = s;
        break;
      }
    }
    return ((i == null ? void 0 : i.children) || []).filter(fs);
  }
  /**
   * If the picked object is part of a solid, returns all the faces ObjectGroups that define the solid.
   * Otherwise, returns the picked object.
   */
  objs() {
    return this.fromSolid ? this._getSolidObjectGroups(this.obj) : [this.obj];
  }
}
class sf {
  /**
   * Create a Raycaster for object picking.
   * @param camera - The camera used for ray projection.
   * @param domElement - The DOM element to listen for events.
   * @param width - Viewport width in pixels.
   * @param height - Viewport height in pixels.
   * @param threshold - Point picking threshold in world units.
   * @param group - The scene group to raycast against.
   * @param callback - Callback for pick events.
   */
  constructor(e, t, i, n, s, a, o) {
    this.onMouseKeyDown = (l) => {
      this.raycastMode && this.camera && (l.button == bt.LEFT || l.button == bt.RIGHT) && (this.lastPosition = this.camera.getPosition().clone());
    }, this.onMouseKeyUp = (l) => {
      this.raycastMode && this.camera && this.lastPosition && (l.button == bt.LEFT ? this.lastPosition.distanceTo(this.camera.getPosition()) < 1e-6 && this.callback({ mouse: "left", shift: _t.get(l, "shift") }) : l.button == bt.RIGHT && this.lastPosition.distanceTo(this.camera.getPosition()) < 1e-6 && this.callback({ mouse: "right" }));
    }, this.onKeyDown = (l) => {
      this.raycastMode && (l.key == "Backspace" ? this.callback({ key: "Backspace" }) : l.key == "Escape" && this.callback({ key: "Escape" }));
    }, this.onPointerMove = (l) => {
      if (!this.domElement)
        return;
      const c = this.domElement.getBoundingClientRect(), h = c.x + window.scrollX, d = c.y + window.scrollY;
      this.mouse.x = (l.pageX - h) / this.width * 2 - 1, this.mouse.y = -((l.pageY - d) / this.height) * 2 + 1, this.mouseMoved = !0;
    }, this.camera = e, this.group = a, this.domElement = t, this.width = i, this.height = n, this.threshold = s, this.callback = o, this.raycaster = new sg(), this.raycastMode = !1, this.lastPosition = null, this.mouse = new H(), this.mouseMoved = !1, this.filters = {
      topoFilter: [ys.none]
    };
  }
  /**
   * Dispose of event listeners and clean up resources.
   */
  dispose() {
    this.domElement && (this.domElement.removeEventListener("mousemove", this.onPointerMove), this.domElement.removeEventListener("mouseup", this.onMouseKeyUp), this.domElement.removeEventListener("mousedown", this.onMouseKeyDown)), document.removeEventListener("keydown", this.onKeyDown), this.raycastMode = !1, this.group = null, this.domElement = null, this.camera = null;
  }
  /**
   * Initialize event listeners and enable raycast mode.
   */
  init() {
    this.domElement && (this.domElement.addEventListener("mousemove", this.onPointerMove), this.domElement.addEventListener("mouseup", this.onMouseKeyUp, !1), this.domElement.addEventListener("mousedown", this.onMouseKeyDown, !1), document.addEventListener("keydown", this.onKeyDown, !1), this.raycastMode = !0);
  }
  /**
   * Retrieve all the valid intersected objects by a ray caster from the mouse.
   */
  getIntersectedObjs() {
    if (!this.camera || !this.group)
      return [];
    this.raycaster.setFromCamera(this.mouse, this.camera.getCamera()), this.raycaster.params.Points.threshold = this.threshold / this.camera.getZoom(), this.raycaster.params.Line2 = { threshold: 4 };
    const e = this.raycaster.intersectObjects([this.group], !0), t = [];
    for (const i of e) {
      const n = i.object;
      ($t(n) || zp(n) || kp(n)) && !Array.isArray(n.material) && n.material.visible && t.push(i);
    }
    return t;
  }
  /**
   * Retrieve all the valid intersected objects by a ray caster from the mouse.
   * The objects are sorted by their distance from the ray. (The closest first)
   */
  getValidIntersectedObjs() {
    const e = [];
    if (this.mouseMoved) {
      const t = this.getIntersectedObjs();
      for (const i of t) {
        const n = i.object;
        if (!($t(n) || zp(n) || kp(n)) || Array.isArray(n.material) || !n.material.visible)
          continue;
        const a = i.object.parent;
        if (!fs(a) || !a.shapeInfo)
          continue;
        const o = a.shapeInfo.topo, l = a.subtype === "solid", c = this.filters.topoFilter.includes(ys.solid) && l, h = this.filters.topoFilter.some((u) => u === o);
        (c || this.filters.topoFilter.includes(ys.none) || h) && e.push(i);
      }
    }
    return e;
  }
}
function bg(r, e) {
  return Array.isArray(r) && r.length === e && r.every((t) => typeof t == "number");
}
function lE(r) {
  return typeof r != "object" || r === null || Array.isArray(r) ? !1 : Object.values(r).every((e) => bg(e, 3));
}
function Yd(r) {
  return r.toLowerCase().replace(/(\D)(\d+)$/, "$1 $2");
}
function rf(r, e) {
  const t = [
    "tcv_x_measure_val",
    "tcv_y_measure_val",
    "tcv_z_measure_val"
  ], i = document.createElement("tr"), n = document.createElement("th");
  n.textContent = Yd(r), n.classList.add("tcv_measure_key"), n.classList.add("tcv_measure_cell"), i.appendChild(n);
  const s = document.createElement("td");
  s.textContent = "(", s.classList.add("tcv_measure_cell_bracket"), i.appendChild(s);
  for (let o = 0; o < 3; ++o) {
    const l = document.createElement("td");
    l.textContent = e[o].toFixed(3), l.classList.add("tcv_measure_val"), l.classList.add("tcv_measure_cell"), l.classList.add(t[o]), i.appendChild(l);
  }
  const a = document.createElement("td");
  return a.textContent = ")", a.classList.add("tcv_measure_cell_bracket"), i.appendChild(a), i;
}
function cE(r, e) {
  const t = document.createElement("tr"), i = document.createElement("th"), n = document.createElement("td");
  return i.textContent = Yd(r), i.classList.add("tcv_measure_key"), i.classList.add("tcv_measure_cell"), t.appendChild(i), n.textContent = e, n.classList.add("tcv_measure_val_center"), n.classList.add("tcv_measure_cell"), n.colSpan = 5, t.appendChild(n), t;
}
function af(r, e, t = null) {
  const i = document.createElement("tr"), n = document.createElement("th"), s = document.createElement("td");
  n.textContent = Yd(r), n.classList.add("tcv_measure_key"), n.classList.add("tcv_measure_cell"), i.appendChild(n);
  for (let a = 0; a < 2; a++) {
    const o = document.createElement("td");
    i.appendChild(o);
  }
  if (s.textContent = e.toFixed(3), s.classList.add("tcv_measure_val"), s.classList.add("tcv_measure_cell"), i.appendChild(s), t == null)
    for (let a = 0; a < 2; a++) {
      const o = document.createElement("td");
      i.appendChild(o);
    }
  else {
    const a = document.createElement("td");
    a.textContent = `(${t})`, a.classList.add("tcv_measure_cell"), i.appendChild(a);
    const o = document.createElement("td");
    i.appendChild(o);
  }
  return i;
}
class Sg {
  constructor(e) {
    this.show = (t) => {
      this.html.style.display = t ? "inline-block" : "none";
    }, this.isVisible = () => this.html.style.display == "inline-block", this.relocate = (t, i) => {
      this.html.style.left = `${t}px`, this.html.style.top = `${i}px`;
    }, this.display = e, this.html = this.getHtmlElement(), this.finished = !1, this.callbacks = [], this.html.addEventListener("contextmenu", (t) => {
      t.preventDefault();
    });
  }
  removeTable() {
    const e = this.html.getElementsByTagName("table");
    e.length > 0 && e[0].remove(), this.finished = !1;
  }
  resetTable() {
    this.removeTable();
  }
  /**
   * Register a callback for a specific event type
   */
  registerCallback(e, t) {
    this.callbacks.push({ callback: t, type: e }), this.html.addEventListener(e, t);
  }
  dispose() {
    for (const e of this.callbacks)
      this.html.removeEventListener(e.type, e.callback);
  }
}
const hE = [
  "type",
  "tool_type",
  "subtype",
  "info",
  "refpoint",
  "refpoint1",
  "refpoint2",
  "shape_type",
  "geom_type",
  "groups",
  "result"
];
function of(r, e, t) {
  let i = !0;
  for (const n in r) {
    if (!Object.prototype.hasOwnProperty.call(r, n) || hE.includes(n.toLowerCase()))
      continue;
    const s = r[n];
    let a;
    if (n.toLowerCase() === "bb" && lE(s))
      for (const o in s) {
        const l = rf(`bb ${o}`, s[o]);
        t && i && (l.classList.add("tcv_measure_cell_top_border"), i = !1), e.appendChild(l);
      }
    else if (bg(s, 3))
      a = rf(n, s);
    else if (typeof s == "number")
      if (n.toLowerCase() === "distance") {
        const o = typeof r.info == "string" ? r.info : void 0;
        a = af(n, s, o ?? null);
      } else
        a = af(n, s);
    else typeof s == "string" && (a = cE(n, s));
    a && (t && i && a.classList.add("tcv_measure_cell_top_border"), e.appendChild(a), i = !1);
  }
}
function Mg(r, e) {
  const t = r.result ?? r.groups;
  if (Array.isArray(t))
    for (let i = 0; i < t.length; i++)
      of(t[i], e, i > 0);
  else
    of(r, e, !1);
}
class wg extends Sg {
  constructor(e) {
    super(e);
  }
  getHtmlElement() {
    return this.display.measurementPanels.distancePanel;
  }
  createTable(e) {
    if (this.finished)
      return;
    this.resetTable();
    const t = document.createElement("table");
    t.classList.add("tcv_properties_table");
    const i = document.createElement("tbody");
    Mg(e, i), t.appendChild(i), this.html.append(t), this.finished = !0;
  }
}
class Eg extends Sg {
  constructor(e) {
    super(e);
  }
  getHtmlElement() {
    return this.display.measurementPanels.propertiesPanel;
  }
  setSubHeader(e) {
    this.html.getElementsByClassName("tcv_measure_subheader")[0].textContent = e;
  }
  createTable(e) {
    if (this.finished)
      return;
    this.resetTable(), this.setSubHeader(`${e.shape_type ?? ""} / ${e.geom_type ?? ""}`);
    const t = document.createElement("table");
    t.classList.add("tcv_properties_table");
    const i = document.createElement("tbody");
    Mg(e, i), t.appendChild(i), this.html.append(t), this.finished = !0;
  }
}
class dE {
  /**
   * Initialize a new filter drop down menu, it needs the raycast to update interactively the filter mode
   */
  constructor(e) {
    this.setValue = (t) => {
      if (this.raycaster != null) {
        this.elements.value.innerText = t;
        const i = t.toLowerCase();
        i === "none" ? this.raycaster.filters.topoFilter = [ys.none] : i in ys && (this.raycaster.filters.topoFilter = [
          ys[i]
        ]);
      }
    }, this.toggleDropdown = (t) => {
      t != null && t.stopPropagation(), this.elements.dropdown.classList.contains("tcv_filter_dropdown_active") ? (this.elements.dropdown.classList.remove("tcv_filter_dropdown_active"), this.elements.icon.innerText = "⏶") : (this.elements.dropdown.classList.add("tcv_filter_dropdown_active"), this.elements.icon.innerText = "⏷");
    }, this.closeDropdown = (t) => {
      this.elements.dropdown.classList.contains("tcv_filter_dropdown_active") && this.toggleDropdown(t);
    }, this.handleSelection = (t) => {
      const i = t.target;
      i instanceof HTMLElement && (this.setValue(i.innerText), this.toggleDropdown(t));
    }, this.reset = () => {
      this.setValue("None");
    }, this.keybindSelect = (t) => {
      ["n", "v", "e", "f", "s", "Escape"].indexOf(t.key) !== -1 && (t.key == "n" ? this.setValue("None") : t.key == "v" ? this.setValue("Vertex") : t.key == "e" ? this.setValue("Edge") : t.key == "f" ? this.setValue("Face") : t.key == "s" ? this.setValue("Solid") : t.key == "Escape" && this.closeDropdown(t));
    }, this.display = e, this.elements = e.filterDropdown, this.elements.container.style.display = "none", this.raycaster = null;
  }
  /**
   * Set the raycaster to update the filter mode
   */
  setRaycaster(e) {
    this.raycaster = e;
  }
  getOptionElements() {
    const e = this.elements.options;
    return [e.none, e.vertex, e.edge, e.face, e.solid];
  }
  /**
   * Show or hide the drop down menu
   */
  show(e) {
    if (e) {
      document.addEventListener("keydown", this.keybindSelect), this.display.container.addEventListener("click", this.closeDropdown), this.elements.content.addEventListener("click", this.toggleDropdown);
      for (const t of this.getOptionElements())
        t.addEventListener("click", this.handleSelection);
    } else {
      document.removeEventListener("keydown", this.keybindSelect), this.display.container.removeEventListener("click", this.closeDropdown), this.elements.content.removeEventListener("click", this.toggleDropdown);
      for (const t of this.getOptionElements())
        t.removeEventListener("click", this.handleSelection);
    }
    this.elements.container.style.display = e ? "block" : "none";
  }
}
class lr extends li {
  constructor(e, t, i, n, s, a = !0, o = !0) {
    super(), this.coneLength = e, this.point1 = t, this.point2 = i, this.linewidth = n, this.color = s, this.arrowStart = a, this.arrowEnd = o, this.type = "DistanceLineArrow", this.mode = "inward", this.renderMode = "arrows", this.initialize();
  }
  initialize() {
    const e = this.coneLength * 0.8, t = this.point1.distanceTo(this.point2);
    if (t < 1e-9) {
      this.renderMode = "dot";
      const _ = new Ts(e / 6, 16, 12), g = new Ht({ color: this.color }), f = new Je(_, g);
      f.name = "dot", f.position.copy(this.point1), this.add(f);
      return;
    }
    this.renderMode = "arrows", this.lineVec = this.point1.clone().sub(this.point2.clone()).normalize(), t < e ? this.mode = "outward" : this.mode = "inward";
    const i = this.mode === "inward" ? 1 : -1;
    let n, s;
    this.arrowStart ? n = this.point1.clone().sub(this.lineVec.clone().multiplyScalar(i * e * 0.3)) : n = this.point1.clone(), this.arrowEnd ? s = this.point2.clone().sub(this.lineVec.clone().multiplyScalar(-i * e * 0.3)) : s = this.point2.clone();
    const a = new _c({
      linewidth: this.linewidth,
      color: this.color
    }), o = new Vd();
    o.setPositions([...n.toArray(), ...s.toArray()]);
    const l = new Gd(o, a), c = new wr(e / 4, e * 0.6, 10), h = new Ht({ color: this.color }), d = new Je(c, h), u = new Je(c, h);
    d.name = "startCone", u.name = "endCone";
    const p = new Ne(), m = new ot();
    this.mode === "inward" ? (p.lookAt(this.point1, this.point2, d.up), m.setFromRotationMatrix(p), d.setRotationFromQuaternion(m), p.lookAt(this.point2, this.point1, u.up), m.setFromRotationMatrix(p), u.setRotationFromQuaternion(m)) : (p.lookAt(this.point2, this.point1, d.up), m.setFromRotationMatrix(p), d.setRotationFromQuaternion(m), p.lookAt(this.point1, this.point2, u.up), m.setFromRotationMatrix(p), u.setRotationFromQuaternion(m)), d.rotateX(90 * Math.PI / 180), u.rotateX(90 * Math.PI / 180), d.position.copy(n), u.position.copy(s), this.arrowStart && this.add(d), this.arrowEnd && this.add(u), this.add(l);
  }
  /**
   * Update the arrow so it keeps the same size on the screen.
   */
  update(e) {
    if (this.renderMode === "dot") {
      const o = this.children.find((l) => $t(l) && l.name === "dot");
      o && $t(o) && o.scale.set(e, e, e);
      return;
    }
    const t = this.coneLength * 0.8, i = this.mode === "inward" ? 1 : -1, n = this.point1.clone().sub(this.lineVec.clone().multiplyScalar(i * e * t * 0.3)), s = this.point2.clone().sub(this.lineVec.clone().multiplyScalar(-i * e * t * 0.3)), a = this.children.find((o) => en(o));
    if (a && en(a) && a.geometry.setPositions([
      ...this.arrowStart ? n.toArray() : this.point1.toArray(),
      ...this.arrowEnd ? s.toArray() : this.point2.toArray()
    ]), this.arrowStart) {
      const o = this.children.find((l) => $t(l) && l.name === "startCone");
      o && $t(o) && (o.position.copy(n), o.scale.set(e, e, e));
    }
    if (this.arrowEnd) {
      const o = this.children.find((l) => $t(l) && l.name === "endCone");
      o && $t(o) && (o.position.copy(s), o.scale.set(e, e, e));
    }
  }
  /**
   * Dispose of all geometries and materials.
   * Handles shared geometry/material between cones.
   */
  dispose() {
    const e = this.children.find((n) => en(n));
    e && en(e) && (e.geometry.dispose(), e.material.dispose());
    const t = this.children.find((n) => $t(n) && n.name === "startCone");
    if (t && $t(t)) {
      t.geometry.dispose();
      const n = t.material;
      Array.isArray(n) ? n.forEach((s) => s.dispose()) : n.dispose();
    }
    const i = this.children.find((n) => $t(n) && n.name === "dot");
    if (i && $t(i)) {
      i.geometry.dispose();
      const n = i.material;
      Array.isArray(n) ? n.forEach((s) => s.dispose()) : n.dispose();
    }
    this.clear();
  }
}
class Tg {
  constructor(e, t) {
    this.handleSelection = (i, n = !1) => {
      this.shift = n, this.selectedShapes.find((s) => s.obj.name === i.obj.name) !== void 0 ? this.selectedShapes.splice(this.selectedShapes.indexOf(i), 1) : this.selectedShapes.push(i), this.panel && (this.panel.finished = !1), this._updateMeasurement();
    }, this._mouseup = (i) => {
      this.panelDragData.clicked = !1, i.stopPropagation();
    }, this._movePanel = () => {
      if (!this.panel || !this.viewer || !this.viewer.camera || !this.panel.isVisible())
        return;
      const i = this.viewer.renderer.domElement.getBoundingClientRect(), n = this.panel.html.getBoundingClientRect();
      if (this.panelX == null && this.middlePoint != null) {
        const u = this.middlePoint.clone().project(this.viewer.camera.getCamera()), p = (u.x + 1) * (i.width / 2), m = (1 - u.y) * (i.height / 2);
        p < i.width / 2 ? this.panelX = p + n.width / 2 : this.panelX = p - n.width - n.width / 2, this.panelX = Math.max(0, Math.min(i.width - n.width, this.panelX)), this.panelY = m, this.panelY = Math.max(0, Math.min(i.height - n.height, this.panelY));
      }
      if (this.panel.relocate(this.panelX, this.panelY), this.panelX == null || this.panelY == null)
        return;
      const s = this.panelX + n.width / 2, a = this.panelY + n.height / 2, o = s / (i.width / 2) - 1, l = 1 - a / (i.height / 2), c = this.viewer.ortho ? -0.9 : 1, h = new b(o, l, c), d = this.viewer.camera.getCamera();
      (ia(d) || or(d)) && (d.updateProjectionMatrix(), d.updateMatrixWorld(), this.panelCenter = h.unproject(d)), this.scene && this.scene.children.length > 0 && this._updateConnectionLine();
    }, this._dragPanel = (i) => {
      if (!this.panelDragData.clicked || !this.panel || !this.viewer || this.panelDragData.x == null || this.panelDragData.y == null)
        return;
      const n = this.panel.html.getBoundingClientRect(), s = this.viewer.renderer.domElement.getBoundingClientRect(), a = i.clientX - this.panelDragData.x, o = i.clientY - this.panelDragData.y;
      n.x + a < s.x && i.movementX <= 0 || n.x + a > s.x + s.width - n.width && i.movementX >= 0 || this.panelX !== null && (this.panelX += a), n.y + o < s.y && i.movementY <= 0 || n.y + o > s.y + s.height - n.height && i.movementY >= 0 || this.panelY !== null && (this.panelY += o), this._updateMeasurement(), this.panelDragData.x = i.clientX, this.panelDragData.y = i.clientY;
    }, this.selectedShapes = [], this.point1 = null, this.point2 = null, this.middlePoint = null, this.contextEnabled = !1, this.viewer = e, this.scene = new Ma(), this.panel = t, this.panelCenter = null, this.panelX = null, this.panelY = null, this.panelShown = !1, this.responseData = null, this.measurementLineColor = 0, this.connectingLineColor = 8388736, this.coneLength = void 0, this.debug = !1, this.panelDragData = { x: null, y: null, clicked: !1 }, this.panel.registerCallback("mousedown", (i) => {
      this.panelDragData.clicked = !0, this.panelDragData.x = i.clientX, this.panelDragData.y = i.clientY, i.stopPropagation();
    }), this.shift = !1;
  }
  enableContext() {
    this.contextEnabled = !0, this.panelCenter = new b(1, 0, 0), document.addEventListener("mouseup", this._mouseup), document.addEventListener("mousemove", this._dragPanel);
  }
  disableContext() {
    var e;
    this._hideMeasurement(), this.contextEnabled = !1, this.responseData = null;
    for (const t of this.selectedShapes)
      t.obj.clearHighlights();
    this.selectedShapes = [], document.removeEventListener("mouseup", this._mouseup), document.removeEventListener("mousemove", this._dragPanel), (e = this.viewer) == null || e.checkChanges({ selectedShapeIDs: [] });
  }
  _hideMeasurement() {
    var e, t;
    (e = this.panel) == null || e.show(!1), this.disposeArrows(), (t = this.scene) == null || t.clear();
  }
  /**
   * Response handler for the measure context
   */
  handleResponse(e) {
  }
  _createPanel() {
    throw new Error("Subclass needs to override this method");
  }
  _makeLines() {
    throw new Error("Subclass needs to override this method");
  }
  _updateConnectionLine() {
    throw new Error("Subclass needs to override this method");
  }
  /**
   * Get the maximum number of selected obj this measurement can handle
   */
  _getMaxObjSelected() {
    throw new Error("Subclass needs to override this method");
  }
  /**
   * Wait for the backend to send the data needed to display the real BREP measurement.
   */
  _waitResponse(e, t) {
    this.responseData ? e(this.responseData) : setTimeout(() => {
      this._waitResponse(e, t);
    }, 100);
  }
  /**
   * Update the measurement panel, if enough shapes have been selected for the current tool,
   * ask the backend for the real measurement data and display it.
   */
  _updateMeasurement() {
    var n;
    const e = (s) => s.fromSolid ? s.obj.name.replace(/\|faces.*$/, "").replace(/\|edges.*$/, "").replace(/\|vertices.*$/, "").replaceAll("|", "/") : s.obj.name.replaceAll("|", "/"), t = this.selectedShapes.map(e);
    if (this.responseData = null, this.debug) {
      const s = 50 + Math.floor(Math.random() * 200);
      setTimeout(() => {
        if (this.selectedShapes.length == 0)
          return;
        const a = (l) => {
          var h;
          const c = l.children[0];
          return c && $t(c) ? (c.geometry.computeBoundingSphere(), ((h = c.geometry.boundingSphere) == null ? void 0 : h.center.clone()) ?? null) : null;
        };
        let o;
        if (this instanceof Ag) {
          if (this.selectedShapes.length < 2)
            return;
          const l = this.selectedShapes[0].obj, c = this.selectedShapes[1].obj, h = a(l), d = a(c);
          if (!h || !d)
            return;
          this.point1 = l.localToWorld(h), this.point2 = c.localToWorld(d), o = {
            groups: [
              { distance: 2.345, info: "center" },
              { "point 1": this.point1.toArray(), "point 2": this.point2.toArray() },
              { angle: 43.21, "reference 1": "Plane (Face)", "reference 2": "Plane (Face)" }
            ],
            type: "backend_response",
            refpoint1: this.point1.toArray(),
            refpoint2: this.point2.toArray()
          };
        } else if (this instanceof Cg) {
          const l = this.selectedShapes[0].obj, c = a(l);
          if (!c)
            return;
          this.point1 = l.localToWorld(c), o = {
            type: "backend_response",
            shape_type: "Edge",
            geom_type: "EllipseArc",
            refpoint: this.point1.toArray(),
            groups: [
              { center: this.point1.toArray(), "major radius": 0.4, "minor radius": 0.2 },
              { start: [2.4, -1, 0], end: [1.8, -0.8267949192431111, 0] },
              { length: 0.6868592404716374 },
              { bb: { min: [1.8, -1, 0], center: [2.1, -0.9, 0], max: [2.4, -0.8, 0], size: [0.56, 0.2, 0] } }
            ]
          };
        } else
          return;
        this.handleResponse(o);
      }, s);
    } else
      (n = this.viewer) == null || n.checkChanges({
        selectedShapeIDs: [...t, this.shift]
      });
    if (this.selectedShapes.length != this._getMaxObjSelected()) {
      this._hideMeasurement();
      return;
    }
    new Promise((s, a) => {
      this._waitResponse(s, a);
    }).then((s) => {
      var a;
      this._createPanel(), this._makeLines(), (a = this.panel) == null || a.show(!0), this._movePanel();
    });
  }
  removeLastSelectedObj(e = !1) {
    if (e || this.selectedShapes.length == this._getMaxObjSelected()) {
      const t = this.selectedShapes.pop();
      if (t) {
        const i = t.objs();
        for (const n of i)
          n.clearHighlights();
      }
      this._updateMeasurement();
    }
  }
  /**
   * Adjust the arrow cones scale factor to ensure they keep the same size on the screen.
   */
  _adjustArrowsScaleFactor(e) {
    if (!this.scene)
      return;
    const t = 1 / e;
    this.scene.children.forEach((i) => {
      i instanceof lr && i.update(t);
    });
  }
  update() {
    if (!this.viewer || !this.viewer.camera || !this.scene)
      return;
    const e = this.viewer.camera.getCamera(), t = this.viewer.camera.getZoom(), i = this.viewer.state.get("cadWidth"), n = this.viewer.state.get("height");
    typeof i == "number" && typeof n == "number" && (this.coneLength = this.viewer.bb_radius / (Math.max(i, n) / 60)), this._adjustArrowsScaleFactor(t), this.viewer.renderer.clearDepth(), this._movePanel(), this.viewer.renderer.render(this.scene, e);
  }
  disposeArrows() {
    this.scene && (ct(this.scene), this.scene.clear());
  }
  dispose() {
    this.panel && (this.panel.show(!1), ct(this.panel)), this.disposeArrows(), this.panel = null, this.viewer = null, this.scene = null;
  }
}
function uE(r) {
  return r instanceof wg;
}
function pE(r) {
  return r instanceof Eg;
}
function lf(r) {
  return r !== null && "refpoint1" in r && "refpoint2" in r;
}
function cf(r) {
  return r !== null && "refpoint" in r;
}
class Ag extends Tg {
  constructor(e, t) {
    super(e, new wg(e.display)), this.point1 = null, this.point2 = null, this.middlePoint = null, this.debug = t;
  }
  _createPanel() {
    uE(this.panel) && lf(this.responseData) && this.panel.createTable(this.responseData);
  }
  _getMaxObjSelected() {
    return 2;
  }
  _getPoints() {
    lf(this.responseData) && (this.responseData.refpoint1 && (this.point1 = new b(...this.responseData.refpoint1)), this.responseData.refpoint2 && (this.point2 = new b(...this.responseData.refpoint2)));
  }
  _makeLines() {
    if (!this.scene || this.scene.children.length !== 0 || !this.coneLength || !this.point1 || !this.point2 || !this.panelCenter)
      return;
    const e = 1.5, t = new lr(this.coneLength, this.point1, this.point2, e, this.measurementLineColor);
    this.scene.add(t), this.middlePoint = new b().addVectors(this.point1, this.point2).multiplyScalar(0.5);
    const i = new lr(this.coneLength, this.panelCenter, this.middlePoint, e, this.connectingLineColor, !1, !1);
    this.scene.add(i);
  }
  _updateConnectionLine() {
    if (!this.scene || !this.middlePoint || !this.panelCenter)
      return;
    const e = this.scene.children[1];
    if (!(e instanceof lr))
      return;
    const t = e.children.find((i) => en(i));
    t && en(t) && t.geometry.setPositions([
      ...this.middlePoint.toArray(),
      ...this.panelCenter.toArray()
    ]);
  }
  /**
   * Handle the response from the backend.
   */
  handleResponse(e) {
    this.responseData = { ...e }, this._getPoints();
  }
}
class Cg extends Tg {
  constructor(e, t) {
    super(e, new Eg(e.display)), this.middlePoint = null, this.debug = t;
  }
  _createPanel() {
    pE(this.panel) && cf(this.responseData) && this.panel.createTable(this.responseData);
  }
  _getMaxObjSelected() {
    return 1;
  }
  _getPoint() {
    cf(this.responseData) && this.responseData.refpoint && (this.point1 = new b(...this.responseData.refpoint));
  }
  _makeLines() {
    if (!this.scene || this.scene.children.length !== 0 || !this.coneLength || !this.panelCenter || !this.point1)
      return;
    this.middlePoint = this.point1;
    const e = 1.5, t = new lr(this.coneLength, this.panelCenter, this.middlePoint, e, this.connectingLineColor, !1, !1);
    this.scene.add(t);
  }
  _updateConnectionLine() {
    if (!this.scene || !this.middlePoint || !this.panelCenter)
      return;
    const e = this.scene.children[0];
    if (!(e instanceof lr))
      return;
    const t = e.children.find((i) => en(i));
    t && en(t) && t.geometry.setPositions([
      ...this.middlePoint.toArray(),
      ...this.panelCenter.toArray()
    ]);
  }
  /**
   * Handle the response from the backend.
   */
  handleResponse(e) {
    this.responseData = { ...e }, this._getPoint();
  }
}
class fE {
  constructor(e) {
    this.viewer = e, this.selectedShapes = [], this.contextEnabled = !1;
  }
  enableContext() {
    this.contextEnabled = !0;
  }
  disableContext() {
    this.contextEnabled = !1;
    for (const e of this.selectedShapes)
      e.obj.clearHighlights();
    this.selectedShapes = [];
  }
  _getMaxObjSelected() {
    return null;
  }
  _getIndex(e) {
    const t = e.split("|");
    return t[t.length - 1].split("_")[1];
  }
  _includes(e) {
    for (const t of this.selectedShapes)
      if (e === t.obj.name)
        return !0;
    return !1;
  }
  notify() {
    const e = [];
    for (const t of this.selectedShapes) {
      const i = t.obj.name;
      e.push(this._getIndex(i));
    }
    this.viewer.checkChanges({ selected: e }, !0);
  }
  handleSelection(e) {
    if (!e)
      return;
    const t = e.obj.name;
    this._includes(t) ? this.selectedShapes = this.selectedShapes.filter((i) => i.obj.name !== t) : this.selectedShapes.push(e), this.notify();
  }
  _removeLastSelectedObj(e) {
    if (e) {
      const t = e.objs();
      for (const i of t)
        i.clearHighlights();
    }
    this.notify();
  }
  removeLastSelectedObj(e) {
    if (e) {
      for (const t of this.selectedShapes)
        this._removeLastSelectedObj(t);
      this.selectedShapes = [];
    } else {
      const t = this.selectedShapes.pop();
      this._removeLastSelectedObj(t), this.notify();
    }
  }
  update() {
  }
  handleResponse(e) {
  }
  dispose() {
    this.disableContext();
  }
}
const Kt = {
  NONE: "None",
  DISTANCE: "DistanceMeasurement",
  PROPERTIES: "PropertiesMeasurement",
  SELECT: "SelectObjects"
};
class mE {
  constructor(e, t) {
    this.viewer = e, this.distanceMeasurement = new Ag(e, t), this.propertiesMeasurement = new Cg(e, t), this.selectObject = new fE(e), this.enabledTool = null;
  }
  /**
   * Enables a specific tool. (Disables the currently enabled tool if any)
   */
  enable(e) {
    switch (this.enabledTool && this.disable(), e) {
      case Kt.DISTANCE:
        this.distanceMeasurement.enableContext();
        break;
      case Kt.PROPERTIES:
        this.propertiesMeasurement.enableContext();
        break;
      case Kt.SELECT:
        this.selectObject.enableContext();
        break;
      default:
        throw new Error(`Unknown tool type: ${e}`);
    }
    this.enabledTool = e;
  }
  disable() {
    this.enabledTool && (this.viewer.display.shapeFilterDropDownMenu.reset(), this._disable());
  }
  /**
   * Disables the currently enabled tool.
   */
  _disable() {
    if (this.enabledTool) {
      switch (this.enabledTool) {
        case Kt.DISTANCE:
          this.distanceMeasurement.disableContext();
          break;
        case Kt.PROPERTIES:
          this.propertiesMeasurement.disableContext();
          break;
        case Kt.SELECT:
          this.selectObject.disableContext();
          break;
        default:
          throw new Error(`Unknown tool type: ${this.enabledTool}`);
      }
      this.enabledTool = null;
    }
  }
  handleRemoveLastSelection(e = !1) {
    this.distanceMeasurement.contextEnabled ? this.distanceMeasurement.removeLastSelectedObj(e) : this.propertiesMeasurement.contextEnabled ? this.propertiesMeasurement.removeLastSelectedObj(e) : this.selectObject.contextEnabled && this.selectObject.removeLastSelectedObj(!1);
  }
  /**
   * Handle selected object from raycaster.
   */
  handleSelectedObj(e, t, i) {
    this.distanceMeasurement.contextEnabled ? (t && this.distanceMeasurement.removeLastSelectedObj(), this.distanceMeasurement.handleSelection(e, i)) : this.propertiesMeasurement.contextEnabled ? (t && this.propertiesMeasurement.removeLastSelectedObj(), this.propertiesMeasurement.handleSelection(e)) : this.selectObject.contextEnabled && this.selectObject.handleSelection(e);
  }
  handleResetSelection() {
    this.distanceMeasurement.contextEnabled ? (this.distanceMeasurement.removeLastSelectedObj(!0), this.distanceMeasurement.removeLastSelectedObj(!0)) : this.propertiesMeasurement.contextEnabled ? this.propertiesMeasurement.removeLastSelectedObj(!0) : this.selectObject.contextEnabled && this.selectObject.removeLastSelectedObj(!0);
  }
  /**
   * Handle the response from the backend.
   */
  handleResponse(e) {
    switch (e.tool_type) {
      case Kt.DISTANCE:
        this.distanceMeasurement.handleResponse(e);
        break;
      case Kt.PROPERTIES:
        this.propertiesMeasurement.handleResponse(e);
        break;
      case Kt.SELECT:
        this.selectObject.handleResponse(e);
        break;
    }
  }
  /**
   * This is called each time the viewer gets updated
   */
  update() {
    this.distanceMeasurement.contextEnabled ? this.distanceMeasurement.update() : this.propertiesMeasurement.contextEnabled ? this.propertiesMeasurement.update() : this.selectObject.contextEnabled && this.selectObject.update();
  }
  dispose() {
    this.distanceMeasurement.dispose(), this.propertiesMeasurement.dispose(), this.selectObject.dispose();
  }
}
const hf = "4.1.0", gE = /* @__PURE__ */ new Set([
  // Display
  "theme",
  "cadWidth",
  "treeWidth",
  "treeHeight",
  "height",
  "pinning",
  "glass",
  "tools",
  "keymap",
  "newTreeBehavior",
  "measureTools",
  "selectTool",
  "explodeTool",
  "zscaleTool",
  "zebraTool",
  "measurementDebug",
  // Render
  "ambientIntensity",
  "directIntensity",
  "metalness",
  "roughness",
  "defaultOpacity",
  "edgeColor",
  "normalLen",
  // Viewer
  "axes",
  "axes0",
  "grid",
  "ortho",
  "transparent",
  "blackEdges",
  "collapse",
  "clipIntersection",
  "clipPlaneHelpers",
  "clipObjectColors",
  "clipNormal0",
  "clipNormal1",
  "clipNormal2",
  "clipSlider0",
  "clipSlider1",
  "clipSlider2",
  "control",
  "holroyd",
  "up",
  "ticks",
  "gridFontSize",
  "centerGrid",
  "position",
  "quaternion",
  "target",
  "zoom",
  "panSpeed",
  "rotateSpeed",
  "zoomSpeed",
  "timeit",
  // Zebra
  "zebraCount",
  "zebraOpacity",
  "zebraDirection",
  "zebraColorScheme",
  "zebraMappingMode",
  // Runtime
  "activeTool",
  "animationMode",
  "animationSliderValue",
  "zscaleActive",
  "highlightedButton",
  "activeTab"
]);
function Ah(r) {
  return gE.has(r);
}
const df = {
  // View settings
  axes: "axes",
  axes0: "axes0",
  grid: "grid",
  ortho: "ortho",
  transparent: "transparent",
  blackEdges: "black_edges",
  tools: "tools",
  glass: "glass",
  centerGrid: "center_grid",
  collapse: "collapse",
  activeTab: "tab",
  // Render settings
  ambientIntensity: "ambient_intensity",
  directIntensity: "direct_intensity",
  metalness: "metalness",
  roughness: "roughness",
  edgeColor: "default_edgecolor",
  defaultOpacity: "default_opacity",
  // Control settings
  zoomSpeed: "zoom_speed",
  panSpeed: "pan_speed",
  rotateSpeed: "rotate_speed",
  holroyd: "holroyd",
  // Clipping settings
  clipIntersection: "clip_intersection",
  clipObjectColors: "clip_object_colors",
  clipPlaneHelpers: "clip_planes",
  clipSlider0: "clip_slider_0",
  clipSlider1: "clip_slider_1",
  clipSlider2: "clip_slider_2",
  clipNormal0: "clip_normal_0",
  clipNormal1: "clip_normal_1",
  clipNormal2: "clip_normal_2",
  // Zebra settings
  zebraCount: "zebra_count",
  zebraOpacity: "zebra_opacity",
  zebraDirection: "zebra_direction",
  zebraColorScheme: "zebra_color_scheme",
  zebraMappingMode: "zebra_mapping_mode",
  // Animation/Explode slider (shared state, mutually exclusive modes)
  animationSliderValue: "relative_time"
}, uf = {
  // Slider stores 0-1000, but notifications should be 0-1
  animationSliderValue: (r) => r / 1e3
};
function Ch(r, e) {
  return r === e ? !0 : Array.isArray(r) && Array.isArray(e) ? r.length === e.length && r.every((t, i) => t === e[i]) : !1;
}
function pf(r) {
  if (r === "dark")
    return "dark";
  if (r === "light")
    return "light";
  if (r === "browser" && typeof window < "u" && window.matchMedia("(prefers-color-scheme: dark)").matches)
    return "dark";
}
class dt {
  /**
   * Create a ViewerState instance
   */
  constructor(e = {}) {
    this._externalNotifyCallback = null, this._state = {
      ...dt.DISPLAY_DEFAULTS,
      ...dt.RENDER_DEFAULTS,
      ...dt.VIEWER_DEFAULTS,
      ...dt.ZEBRA_DEFAULTS,
      ...dt.RUNTIME_DEFAULTS
    };
    const t = pf(e.theme);
    t && (this._state.theme = t), this._applyOptions(e), this._listeners = /* @__PURE__ */ new Map(), this._globalListeners = [];
  }
  /**
   * Apply options to state, validating keys
   */
  _applyOptions(e) {
    for (const t of Object.keys(e)) {
      if (t === "theme")
        continue;
      if (!Ah(t)) {
        ft.warn(`Unknown option "${t}" - ignored`);
        continue;
      }
      const i = e[t];
      i != null && Object.assign(this._state, { [t]: i });
    }
  }
  /**
   * Get a state value
   */
  get(e) {
    return this._state[e];
  }
  /**
   * Set a state value and notify listeners
   */
  set(e, t, i = !0) {
    const n = this._state[e];
    Ch(n, t) || (this._state[e] = t, i && this._notify(e, { old: n, new: t }));
  }
  /**
   * Update multiple state values at once
   */
  _update(e, t = !0) {
    const i = [];
    for (const n of Object.keys(e)) {
      if (!Ah(n))
        continue;
      const s = e[n];
      if (s === void 0 || s === null && !["position", "quaternion", "target"].includes(n))
        continue;
      const o = this._state[n];
      Ch(o, s) || (Object.assign(this._state, { [n]: s }), i.push({ key: n, change: { old: o, new: s } }));
    }
    if (t)
      for (const { key: n, change: s } of i)
        this._notify(n, s);
  }
  /**
   * Update render state from RenderOptions.
   * RenderOptions types are directly compatible with StateShape.
   */
  updateRenderState(e, t = !0) {
    this._update(e, t);
  }
  /**
   * Update viewer state from ViewerOptions.
   * Converts Vector3Tuple/QuaternionTuple to THREE objects.
   */
  updateViewerState(e, t = !0) {
    const { clipNormal0: i, clipNormal1: n, clipNormal2: s, position: a, quaternion: o, target: l, ...c } = e, h = { ...c };
    i !== void 0 && (h.clipNormal0 = new b(...i)), n !== void 0 && (h.clipNormal1 = new b(...n)), s !== void 0 && (h.clipNormal2 = new b(...s)), a !== void 0 && (h.position = a ? new b(...a) : null), o !== void 0 && (h.quaternion = o ? new ot(...o) : null), l !== void 0 && (h.target = l ? new b(...l) : null), this._update(h, t);
  }
  /**
   * Get all state as a plain object (for serialization)
   */
  getAll() {
    return { ...this._state };
  }
  /**
   * Subscribe to changes for a specific state key
   */
  subscribe(e, t, i = {}) {
    if (this._listeners.has(e) || this._listeners.set(e, []), this._listeners.get(e).push(t), i.immediate) {
      const n = this._state[e];
      t({ old: void 0, new: n });
    }
    return () => {
      const n = this._listeners.get(e);
      if (n) {
        const s = n.indexOf(t);
        s > -1 && n.splice(s, 1);
      }
    };
  }
  /**
   * Subscribe to all state changes
   */
  subscribeAll(e) {
    return this._globalListeners.push(e), () => {
      const t = this._globalListeners.indexOf(e);
      t > -1 && this._globalListeners.splice(t, 1);
    };
  }
  /**
   * Set a callback for external notifications (e.g., to notify external clients).
   * The callback receives the notification key (snake_case) and the change object.
   */
  setExternalNotifyCallback(e) {
    this._externalNotifyCallback = e;
  }
  /**
   * Get all notifiable state values in external format.
   * Returns a dictionary with snake_case keys and StateChange values.
   * Used for initial config sync to external clients.
   */
  getAllNotifiable() {
    const e = {};
    for (const [t, i] of Object.entries(df)) {
      const n = this._state[t], s = uf[t], a = s ? s(n) : n instanceof b ? n.toArray() : n;
      e[i] = { old: null, new: a };
    }
    return e;
  }
  _notify(e, t) {
    const i = this._listeners.get(e);
    if (i)
      for (const n of i)
        n(t);
    for (const n of this._globalListeners)
      n(e, t);
    if (this._externalNotifyCallback) {
      const n = df[e];
      if (n) {
        const s = uf[e], a = s ? { old: t.old != null ? s(t.old) : null, new: s(t.new) } : t;
        this._externalNotifyCallback({ key: n, change: a });
      }
    }
  }
  /**
   * Reset state to default values
   */
  reset(e = {}) {
    const t = { ...this._state };
    this._state = {
      ...dt.DISPLAY_DEFAULTS,
      ...dt.RENDER_DEFAULTS,
      ...dt.VIEWER_DEFAULTS,
      ...dt.ZEBRA_DEFAULTS,
      ...dt.RUNTIME_DEFAULTS
    };
    const i = pf(e.theme);
    i && (this._state.theme = i), this._applyOptions(e);
    for (const n of Object.keys(this._state))
      Ah(n) && (Ch(t[n], this._state[n]) || this._notify(n, { old: t[n], new: this._state[n] }));
  }
  /**
   * Get all default values (useful for documentation/debugging)
   */
  static getDefaults() {
    return {
      ...dt.DISPLAY_DEFAULTS,
      ...dt.RENDER_DEFAULTS,
      ...dt.VIEWER_DEFAULTS,
      ...dt.ZEBRA_DEFAULTS,
      ...dt.RUNTIME_DEFAULTS
    };
  }
  /**
   * Dump all state values to console, organized by category
   */
  dump() {
    const e = (t, i) => {
      ft.info(`${t}:`);
      for (const n of Object.keys(i))
        ft.info(`- ${n}`, this._state[n]);
    };
    e("Display", dt.DISPLAY_DEFAULTS), e("Render", dt.RENDER_DEFAULTS), e("View", dt.VIEWER_DEFAULTS), e("Zebra", dt.ZEBRA_DEFAULTS), e("Runtime", dt.RUNTIME_DEFAULTS);
  }
}
dt.DISPLAY_DEFAULTS = {
  theme: "light",
  cadWidth: 800,
  treeWidth: 250,
  treeHeight: 400,
  height: 600,
  pinning: !1,
  glass: !1,
  tools: !0,
  keymap: {
    shift: "shiftKey",
    ctrl: "ctrlKey",
    meta: "metaKey",
    alt: "altKey",
    axes: "a",
    axes0: "A",
    grid: "g",
    gridxy: "G",
    perspective: "p",
    transparent: "t",
    blackedges: "b",
    reset: "R",
    resize: "r",
    iso: "5",
    front: "1",
    rear: "3",
    top: "8",
    bottom: "2",
    left: "4",
    right: "6",
    explode: "x",
    zscale: "L",
    distance: "D",
    properties: "P",
    select: "S",
    help: "h",
    play: " ",
    stop: "Escape",
    tree: "T",
    clip: "C",
    material: "M",
    zebra: "Z"
  },
  newTreeBehavior: !0,
  measureTools: !0,
  selectTool: !0,
  explodeTool: !0,
  zscaleTool: !1,
  zebraTool: !0,
  measurementDebug: !1
};
dt.RENDER_DEFAULTS = {
  ambientIntensity: 1,
  directIntensity: 1.1,
  metalness: 0.3,
  roughness: 0.65,
  defaultOpacity: 0.5,
  edgeColor: 7368816,
  normalLen: 0
};
dt.VIEWER_DEFAULTS = {
  axes: !1,
  axes0: !1,
  grid: [!1, !1, !1],
  ortho: !0,
  transparent: !1,
  blackEdges: !1,
  collapse: Jt.COLLAPSED,
  clipIntersection: !1,
  clipPlaneHelpers: !1,
  clipObjectColors: !1,
  clipNormal0: new b(-1, 0, 0),
  clipNormal1: new b(0, -1, 0),
  clipNormal2: new b(0, 0, -1),
  clipSlider0: -1,
  clipSlider1: -1,
  clipSlider2: -1,
  control: "orbit",
  holroyd: !0,
  up: "Z",
  ticks: 10,
  gridFontSize: 10,
  centerGrid: !1,
  position: null,
  quaternion: null,
  target: null,
  zoom: 1,
  panSpeed: 1,
  rotateSpeed: 1,
  zoomSpeed: 1,
  timeit: !1
};
dt.ZEBRA_DEFAULTS = {
  zebraCount: 9,
  zebraOpacity: 1,
  zebraDirection: 0,
  zebraColorScheme: "blackwhite",
  zebraMappingMode: "reflection"
};
dt.RUNTIME_DEFAULTS = {
  activeTool: null,
  animationMode: "none",
  animationSliderValue: 0,
  zscaleActive: !1,
  highlightedButton: null,
  activeTab: "tree"
};
function Rh(r) {
  return Array.isArray(r);
}
function Bo(r) {
  return !Array.isArray(r);
}
function ff(r) {
  return "isMesh" in r && r.isMesh === !0 && "index" in r && typeof r.index == "number";
}
function mf(r) {
  return !Array.isArray(r) && "clippingPlanes" in r;
}
function _E(r) {
  return r.subtype === "tool_response" && "tool_type" in r;
}
class yE {
  /**
   * Get rendered state, throwing if not yet rendered.
   */
  get rendered() {
    if (!this._rendered)
      throw new Error("Viewer.render() must be called before this operation");
    return this._rendered;
  }
  // ---------------------------------------------------------------------------
  // Constructor & Initialization
  // ---------------------------------------------------------------------------
  /**
   * Create Viewer.
   * @param display - The Display object.
   * @param options - configuration parameters.
   * @param notifyCallback - The callback to receive changes of viewer parameters.
   * @param pinAsPngCallback - Optional callback for PNG pinning.
   * @param updateMarker - enforce to redraw orientation marker after every ui activity
   */
  constructor(e, t, i, n = null, s = !0) {
    this.checkChanges = (a, o = !0) => {
      const l = {};
      Object.keys(a).forEach((c) => {
        if (!Zh(this.lastNotification[c], a[c])) {
          const h = structuredClone(a[c]);
          l[c] = {
            new: h,
            // map undefined in lastNotification to null to enable JSON exchange
            old: this.lastNotification[c] == null ? null : structuredClone(this.lastNotification[c])
          }, this.lastNotification[c] = h;
        }
      }), Object.keys(l).includes("position") && (this.keepHighlight ? this.keepHighlight = !1 : this.state.set("highlightedButton", null)), o && this.notifyCallback && Object.keys(l).length && this.notifyCallback(l);
    }, this.notifyStates = () => {
      this.checkChanges({ states: this.getStates() }, !0);
    }, this.update = (a, o = !0) => {
      this.ready && (this.renderer.clear(), this.raycaster && this.raycaster.raycastMode && !this.rendered.controls.isInteracting() && this.handleRaycast(), this.rendered.gridHelper.update(this.rendered.camera.getZoom()), this.renderer.setViewport(0, 0, this.state.get("cadWidth"), this.state.get("height")), this.renderer.render(this.rendered.scene, this.rendered.camera.getCamera()), this.cadTools.update(), this.rendered.directLight.position.copy(this.rendered.camera.getCamera().position), this.lastBbox != null && (this.lastBbox.needsUpdate || this.bboxNeedsUpdate) && (console.debug("updated bbox"), this.lastBbox.bbox.update(), this.lastBbox.needsUpdate = !1), a && (this.renderer.clearDepth(), this.rendered.orientationMarker.update(this.rendered.camera.getPosition().clone().sub(this.rendered.controls.getTarget()), this.rendered.camera.getQuaternion()), this.rendered.orientationMarker.render(this.renderer)), this.animation && this.animation.update(), this.checkChanges({
        zoom: this.rendered.camera.getZoom(),
        position: this.rendered.camera.getPosition().toArray(),
        quaternion: this.rendered.camera.getQuaternion().toArray(),
        target: this.rendered.controls.getTarget().toArray()
      }, o));
    }, this.animate = () => {
      this.continueAnimation ? (requestAnimationFrame(this.animate), this.rendered.controls.update(), this.update(!0, !0)) : console.debug("three-cad-viewer: Animation loop stopped");
    }, this.syncTreeStates = (a, o, l, c) => {
      if (Rh(a)) {
        if (!Bo(o))
          return;
        const h = o;
        if (l)
          for (const d in h) {
            const u = h[d];
            if (Bo(u))
              for (const p in u) {
                const m = u[p];
                if (!Rh(m))
                  continue;
                const _ = `${c}/${d}/${p}`, g = this.expandedNestedGroup.groups[_];
                fs(g) && (g.setShapeVisible(a[0] === 1), g.setEdgesVisible(a[1] === 1), m[0] !== 3 && (m[0] = a[0]), m[1] !== 3 && (m[1] = a[1]));
              }
          }
        else {
          const d = this.compactNestedGroup.groups[c];
          if (!fs(d))
            return;
          let u = !1, p = !1;
          for (const m in h) {
            const _ = h[m];
            if (Bo(_))
              for (const g in _) {
                const f = _[g];
                Rh(f) && (f[0] === 1 && (u = !0), f[1] === 1 && (p = !0));
              }
          }
          d.setShapeVisible(u), d.setEdgesVisible(p), a[0] !== 3 && (a[0] = u ? 1 : 0), a[1] !== 3 && (a[1] = p ? 1 : 0);
        }
      } else {
        if (!Bo(o))
          return;
        const h = o;
        for (const d in a) {
          const u = `${c}/${d}`;
          this.syncTreeStates(a[d], h[d], l, u);
        }
      }
    }, this.getNodeColor = (a) => {
      if (!this._rendered)
        return null;
      const o = this._rendered.nestedGroup.groups["/" + a];
      return o instanceof Mi && o.front ? "#" + o.front.material.color.getHexString() : null;
    }, this.setCamera = (a, o, l = null, c = null, h = !0) => {
      this.rendered.camera.setupCamera(a, o, l, c), this.update(!0, h);
    }, this.presetCamera = (a, o = null, l = !0) => {
      this.rendered.camera.target = new b(...this.bbox.center()), this.rendered.camera.presetCamera(a, o), this.rendered.controls.setTarget(this.rendered.camera.target), this.update(!0, l);
    }, this.getResetLocation = () => this.rendered.controls.getResetLocation(), this.setResetLocation = (a, o, l, c, h = !0) => {
      const d = this.getResetLocation();
      this.rendered.controls.setResetLocation(new b(...a), new b(...o), new ot(...l), c), h && this.notifyCallback && this.notifyCallback({
        target0: {
          old: ji(d.target0.toArray()),
          new: a
        },
        position0: {
          old: ji(d.position0.toArray()),
          new: o
        },
        quaternion0: {
          old: Fp(d.quaternion0.toArray()),
          new: l
        },
        zoom0: { old: d.zoom0, new: c }
      });
    }, this.resize = () => {
      this.rendered.camera.changeDimensions(this.bb_radius, this.state.get("cadWidth"), this.state.get("height")), this.rendered.camera.setZoom(1), this.rendered.camera.updateProjectionMatrix(), this.update(!0);
    }, this.reset = () => {
      this.rendered.camera.changeDimensions(this.bb_radius, this.state.get("cadWidth"), this.state.get("height")), this.rendered.controls.reset(), this.update(!0);
    }, this.setObject = (a, o, l, c = !0, h = !0) => {
      const d = this.rendered.nestedGroup.groups[a];
      d != null && d instanceof Mi && (l === 0 ? d.setShapeVisible(o === 1) : d.setEdgesVisible(o === 1), c && this.getState(a), h && this.update(this.updateMarker));
    }, this.setBoundingBox = (a) => {
      const o = this.rendered.nestedGroup.groups[a];
      if (o != null) {
        if (this.lastBbox != null) {
          this.rendered.scene.remove(this.lastBbox.bbox), this.lastBbox.bbox.geometry.dispose();
          const l = this.lastBbox.bbox.material;
          Array.isArray(l) ? l.forEach((c) => c.dispose()) : l.dispose();
        }
        this.lastBbox == null || this.lastBbox != null && a !== this.lastBbox.id ? (this.lastBbox = {
          id: a,
          bbox: new sw(o, 16711935),
          needsUpdate: !1
        }, this.rendered.scene.add(this.lastBbox.bbox)) : this.lastBbox = null, this.update(!1, !1);
      }
    }, this.refreshPlane = (a, o) => {
      if (!this.ready)
        return;
      const l = ["clipSlider0", "clipSlider1", "clipSlider2"];
      this.state.set(l[a], o), this.rendered.clipping.setConstant(a, o), this.update(this.updateMarker);
    }, this.controlAnimation = (a) => {
      if (this.clipAction)
        switch (a) {
          case "play":
            this.clipAction.paused && (this.clipAction.paused = !1), this.clipAction.play();
            break;
          case "pause":
            this.clipAction.paused = !this.clipAction.paused;
            break;
          case "stop":
            this.clipAction.stop();
            break;
        }
    }, this.setState = (a, o, l = "leaf", c = !0) => {
      this.rendered.treeview.setState(a, o), this.update(this.updateMarker, c);
    }, this.handlePick = (a, o, l, c, h, d, u = "leaf", p = !1) => {
      var f;
      const m = `${a}/${o}`, _ = this.rendered.nestedGroup.groups[m];
      if (_ == null)
        return;
      let g;
      if (_.parent != null)
        g = new _s().setFromObject(_, !0);
      else {
        g = new _s();
        for (let v = 0; v < _.children.length - 1; v++)
          g = g.expandByObject(_.children[v]);
      }
      if (this.lastBbox != null && this.lastBbox.id === m && !l && !c)
        this.removeLastBbox(), this.rendered.treeview.toggleLabelColor(null, m);
      else if (this.checkChanges({
        lastPick: {
          path: a,
          name: o,
          boundingBox: g,
          boundingSphere: g.boundingSphere()
        }
      }), (f = this.animation.clipAction) != null && f.isRunning() && (this.bboxNeedsUpdate = !0), c && l)
        if (this.removeLastBbox(), p)
          this.rendered.treeview.hideAll(), this.setState(m, [1, 1], u ?? "leaf");
        else {
          const v = g.center();
          this.setCameraTarget(d ?? new b(...v)), this.display.showCenterInfo(v);
        }
      else if (c) {
        this.removeLastBbox(), this.rendered.treeview.hideAll(), this.setState(m, [1, 1], u ?? "leaf");
        const v = g.center();
        this.setCameraTarget(new b(...v)), this.display.showCenterInfo(v);
      } else l ? this.setState(m, [0, 0], u ?? "leaf") : (this.display.showBoundingBoxInfo(a, o, g), this.setBoundingBox(m), this.rendered.treeview.openPath(m));
      this.update(!0);
    }, this.pick = (a) => {
      var _, g;
      const o = new sf(this.rendered.camera, this.renderer.domElement, this.state.get("cadWidth"), this.state.get("height"), this.bb_max / 30, this.rendered.scene.children[0], () => {
      });
      o.init(), o.onPointerMove(a);
      const l = o.getIntersectedObjs();
      if (l.length === 0)
        return;
      let c = null, h = null;
      for (const f of l)
        if (f.object instanceof Je) {
          c = f.object, h = f;
          break;
        }
      if (c == null || h == null)
        return;
      const d = h.point, u = (_ = this.shapes) == null ? void 0 : _.format, p = (g = c.parent) == null ? void 0 : g.parent, m = {
        path: p ? p.name.replaceAll("|", "/") : "",
        name: c.name,
        boundingBox: u === "GDS" ? new Tt(d.clone().subScalar(10), d.clone().addScalar(10)) : c.geometry.boundingBox,
        boundingSphere: u === "GDS" ? new Lt(d, 1) : c.geometry.boundingSphere,
        objectGroup: c.parent
      };
      this.handlePick(m.path, m.name, _t.get(a, "meta"), _t.get(a, "shift"), _t.get(a, "alt"), h.point, null, !1), o.dispose();
    }, this.clearSelection = () => {
      this.rendered.nestedGroup.clearSelection(), this.cadTools.handleResetSelection();
    }, this._releaseLastSelected = () => {
      if (this.lastObject != null) {
        const a = this.lastObject.objs();
        for (const o of a)
          o.unhighlight(!0);
      }
    }, this._removeLastSelected = () => {
      if (this.lastSelection != null) {
        const a = this.lastSelection.objs();
        for (const o of a)
          o.unhighlight(!1), this.rendered.treeview.toggleLabelColor(null, o.name.replaceAll(this.rendered.nestedGroup.delim, "/"));
        this.lastSelection = null, this.lastObject = null;
      }
      this.cadTools.handleRemoveLastSelection(!0);
    }, this.handleRaycast = () => {
      const a = this.raycaster.getValidIntersectedObjs();
      if (a.length > 0)
        for (const o of a) {
          const l = o.object.parent;
          if (!fs(l))
            break;
          const c = l.name, h = this.lastObject ? this.lastObject.obj.name : null;
          if (c !== h) {
            this._releaseLastSelected();
            const d = this.raycaster.filters.topoFilter.includes(ys.solid), u = new oE(l, d);
            for (const p of u.objs())
              p.highlight(!0);
            this.lastObject = u;
          }
          break;
        }
      else
        this.lastObject != null && (this._releaseLastSelected(), this.lastObject = null);
    }, this.handleRaycastEvent = (a) => {
      var o;
      if (a.key)
        switch (a.key) {
          case "Escape":
            this.clearSelection();
            break;
          case "Backspace":
            this._removeLastSelected();
            break;
        }
      else
        switch (a.mouse) {
          case "left":
            if (this.lastObject != null) {
              const l = this.lastObject.objs();
              for (const c of l)
                c.toggleSelection();
              this.cadTools.handleSelectedObj(this.lastObject, ((o = this.lastSelection) == null ? void 0 : o.obj.name) !== this.lastObject.obj.name, a.shift ?? !1), this.lastSelection = this.lastObject;
            }
            break;
          case "right":
            this._removeLastSelected();
            break;
        }
    }, this.handleBackendResponse = (a) => {
      _E(a) && this.cadTools.handleResponse(a);
    }, this.setAxes = (a, o = !0) => {
      this.ready && (this.state.set("axes", a, o), this.rendered.axesHelper.setVisible(a), this.update(this.updateMarker));
    }, this.setGrid = (a, o, l = !0) => {
      this.rendered.gridHelper.setGrid(a, o);
      const [c, h, d] = this.rendered.gridHelper.grid;
      this.state.set("grid", [c, h, d], l), this.update(this.updateMarker);
    }, this.setGrids = (a, o = !0) => {
      this.rendered.gridHelper.setGrids(...a);
      const [l, c, h] = this.rendered.gridHelper.grid;
      this.state.set("grid", [l, c, h], o), this.update(this.updateMarker);
    }, this.setGridCenter = (a, o = !0) => {
      this.state.set("centerGrid", a, o), this.rendered.gridHelper.centerGrid = a, this.rendered.gridHelper.setCenter(this.state.get("axes0"), this.state.get("up") === "Z"), this.update(this.updateMarker);
    }, this.setAxes0 = (a, o = !0) => {
      this.ready && (this.state.set("axes0", a, o), this.rendered.gridHelper.setCenter(a, this.state.get("up") === "Z"), this.rendered.axesHelper.setCenter(a), this.update(this.updateMarker));
    }, this.setTransparent = (a, o = !0) => {
      this.state.set("transparent", a, o), this.rendered.nestedGroup.setTransparent(a), this.update(this.updateMarker);
    }, this.setBlackEdges = (a, o = !0) => {
      this.state.set("blackEdges", a, o), this.rendered.nestedGroup.setBlackEdges(a), this.update(this.updateMarker);
    }, this.setTools = (a, o = !0) => {
      this.state.set("tools", a, o);
    }, this.setGlass = (a, o = !0) => {
      this.state.set("glass", a, o);
    }, this.setEdgeColor = (a, o = !0) => {
      this.state.set("edgeColor", a, o), this.rendered.nestedGroup.setEdgeColor(a), this.update(this.updateMarker);
    }, this.setOpacity = (a, o = !0) => {
      this.state.set("defaultOpacity", a, o), this.rendered.nestedGroup.setOpacity(a), this.update(this.updateMarker);
    }, this.showTools = (a, o = !0) => {
      this.state.set("tools", a, o), this.update(this.updateMarker);
    }, this.setAmbientLight = (a, o = !0) => {
      this.ready && (a = Math.max(0, Math.min(4, a)), this.state.set("ambientIntensity", a, o), this.rendered.ambientLight.intensity = Eo(a), this.update(this.updateMarker));
    }, this.setDirectLight = (a, o = !0) => {
      this.ready && (a = Math.max(0, Math.min(4, a)), this.state.set("directIntensity", a, o), this.rendered.directLight.intensity = Eo(a), this.update(this.updateMarker));
    }, this.getMetalness = () => this.state.get("metalness"), this.setMetalness = (a, o = !0) => {
      a = Math.max(0, Math.min(1, a)), this.state.set("metalness", a, o), this.rendered.nestedGroup.setMetalness(a), this.update(this.updateMarker);
    }, this.getRoughness = () => this.state.get("roughness"), this.setRoughness = (a, o = !0) => {
      a = Math.max(0, Math.min(1, a)), this.state.set("roughness", a, o), this.rendered.nestedGroup.setRoughness(a), this.update(this.updateMarker);
    }, this.resetMaterial = () => {
      this.materialSettings && (this.setMetalness(this.materialSettings.metalness, !0), this.setRoughness(this.materialSettings.roughness, !0), this.setAmbientLight(this.materialSettings.ambientIntensity, !0), this.setDirectLight(this.materialSettings.directIntensity, !0));
    }, this.enableZebraTool = (a) => {
      this.rendered.nestedGroup.setZebra(a), this.update(!0, !0), this.rendered.treeview.update();
    }, this.setZebraCount = (a) => {
      a = Math.max(2, Math.min(50, a)), this.state.set("zebraCount", a), this.rendered.nestedGroup.setZebraCount(a), this.update(this.updateMarker);
    }, this.setZebraOpacity = (a) => {
      a = Math.max(0, Math.min(1, a)), this.state.set("zebraOpacity", a), this.rendered.nestedGroup.setZebraOpacity(a), this.update(this.updateMarker);
    }, this.setZebraDirection = (a) => {
      a = Math.max(0, Math.min(90, a)), this.state.set("zebraDirection", a), this.rendered.nestedGroup.setZebraDirection(a), this.update(this.updateMarker);
    }, this.setZebraColorScheme = (a) => {
      this.state.set("zebraColorScheme", a), this.rendered.nestedGroup.setZebraColorScheme(a), this.update(this.updateMarker);
    }, this.setZebraMappingMode = (a) => {
      this.state.set("zebraMappingMode", a), this.rendered.nestedGroup.setZebraMappingMode(a), this.update(this.updateMarker);
    }, this.getZebraCount = () => this.state.get("zebraCount"), this.getZebraOpacity = () => this.state.get("zebraOpacity"), this.getZebraDirection = () => this.state.get("zebraDirection"), this.getZebraColorScheme = () => this.state.get("zebraColorScheme"), this.getZebraMappingMode = () => this.state.get("zebraMappingMode"), this.setStates = (a) => {
      this._rendered && this._rendered.treeview.setStates(a);
    }, this.setZoomSpeed = (a, o = !0) => {
      this.state.set("zoomSpeed", a, o), this.rendered.controls.setZoomSpeed(a);
    }, this.setPanSpeed = (a, o = !0) => {
      this.state.set("panSpeed", a, o), this.rendered.controls.setPanSpeed(a);
    }, this.setRotateSpeed = (a, o = !0) => {
      this.state.set("rotateSpeed", a, o), this.rendered.controls.setRotateSpeed(a);
    }, this.setHolroyd = (a, o = !0) => {
      this.state.set("holroyd", a, o), this.rendered.controls.setHolroydTrackball(a);
    }, this.setClipIntersection = (a, o = !0) => {
      if (a == null || !this.ready)
        return;
      this.state.set("clipIntersection", a, o), this.rendered.nestedGroup.setClipIntersection(a);
      const l = a ? this.rendered.clipping.reverseClipPlanes : this.rendered.clipping.clipPlanes;
      for (const c of this.rendered.nestedGroup.rootGroup.children)
        if (c.name === "PlaneMeshes")
          for (const h of c.children)
            ff(h) && mf(h.material) && (h.material.clippingPlanes = l.filter((d, u) => u !== h.index));
      for (const c of this.rendered.scene.children)
        if (c.name === "PlaneHelpers")
          for (const h of c.children[0].children)
            ff(h) && mf(h.material) && (h.material.clippingPlanes = l.filter((d, u) => u !== h.index));
      this.update(this.updateMarker);
    }, this.getObjectColorCaps = () => {
      var a;
      return ((a = this._rendered) == null ? void 0 : a.clipping.getObjectColorCaps()) ?? !1;
    }, this.setClipObjectColorCaps = (a, o = !0) => {
      a == null || !this.ready || (this.state.set("clipObjectColors", a, o), this.rendered.clipping.setObjectColorCaps(a), this.update(this.updateMarker));
    }, this.setClipPlaneHelpers = (a, o = !0) => {
      if (a == null || !this.ready)
        return;
      this.state.set("clipPlaneHelpers", a, o);
      const l = this.state.get("activeTab") === "clip";
      this.rendered.clipping.planeHelpers.visible = a && l, this.update(this.updateMarker);
    }, this.setClipNormalFromPosition = (a, o = !0) => {
      if (!this.ready)
        return;
      const l = this.rendered.camera.getPosition().clone(), c = ji(l.sub(this.rendered.controls.getTarget()).normalize().negate().toArray());
      this.setClipNormal(a, c, null, o);
    }, this.getClipSlider = (a) => {
      const o = ["clipSlider0", "clipSlider1", "clipSlider2"];
      return this.state.get(o[a]);
    }, this.setClipSlider = (a, o, l = !0) => {
      if (o === -1 || o == null)
        return;
      const c = ["clipSlider0", "clipSlider1", "clipSlider2"];
      this.state.set(c[a], o, l), this.ready && (this.rendered.clipping.setConstant(a, o), this.update(this.updateMarker));
    }, this.pinAsPng = () => {
      this.getImage("screenshot").then((o) => {
        if (typeof o.dataUrl != "string") {
          ft.error("Screenshot dataUrl is not a string");
          return;
        }
        const l = document.createElement("img");
        l.width = this.state.get("cadWidth"), l.height = this.state.get("height"), l.src = o.dataUrl, this.pinAsPngCallback == null && this.display.replaceWithImage(l);
      });
    }, this.getImage = (a) => {
      if (!this.ready)
        return Promise.resolve({ task: a, dataUrl: null });
      const o = this.hasAnimationLoop;
      return o || this.toggleAnimationLoop(!0), this.rendered.orientationMarker.setVisible(!1), this.update(!0), this.display.captureCanvas({
        taskId: a,
        render: () => {
          this.renderer.setViewport(0, 0, this.state.get("cadWidth"), this.state.get("height")), this.renderer.render(this.rendered.scene, this.rendered.camera.getCamera());
        },
        onComplete: () => {
          o || this.toggleAnimationLoop(!1), this.rendered.orientationMarker.setVisible(!0), this.update(!0);
        }
      });
    }, this.setView = (a, o = !1) => {
      this.display.setView(a, o);
    }, this.glassMode = (a, o = !0) => {
      this.state.set("glass", a, o), this.display.glassMode(a);
    }, this.collapseNodes = (a, o = !0) => {
      if (this.state.set("collapse", a, o), !!this.treeview)
        switch (a) {
          case Jt.COLLAPSED:
            this.treeview.collapseAll();
            break;
          case Jt.ROOT:
            this.treeview.openLevel(1);
            break;
          case Jt.LEAVES:
            this.treeview.openLevel(-1);
            break;
          case Jt.EXPANDED:
            this.treeview.expandAll();
            break;
        }
    }, this.setTheme = (a) => this.display.setTheme(a), this.showHelp = (a) => {
      this.display.showHelp(a);
    }, this.showInfo = (a) => {
      this.display.showInfo(a);
    }, this.showPinning = (a) => {
      this.display.showPinning(a);
    }, this.showMeasureTools = (a) => {
      this.display.showMeasureTools(a);
    }, this.showSelectTool = (a) => {
      this.display.showSelectTool(a);
    }, this.showExplodeTool = (a) => {
      this.display.showExplodeTool(a);
    }, this.showZScaleTool = (a) => {
      this.display.showZScaleTool(a);
    }, this.getCanvas = () => this.display.getCanvas(), this.state = new dt(t), this.state.setExternalNotifyCallback((a) => {
      const o = Array.isArray(a) ? a : [a], l = {};
      for (const { key: c, change: h } of o) {
        const d = h.new instanceof b ? h.new.toArray() : h.new;
        l[c] = d;
      }
      this.checkChanges(l, !0);
    }), this.notifyCallback = i, this.pinAsPngCallback = n, this.updateMarker = s, this.hasAnimationLoop = !1, this.display = e, t.keymap ? this.setKeyMap({ ...dt.DISPLAY_DEFAULTS.keymap, ...t.keymap }) : this.setKeyMap(dt.DISPLAY_DEFAULTS.keymap), window.THREE = GM, this._rendered = null, this.tree = null, this.bbox = null, this.bb_max = 0, this._stencilCSize = 0, this._treeNeedsRebuild = !1, this._pendingDisposal = [], this.cadTools = new mE(this, t.measurementDebug ?? !1), this.ready = !1, this.mixer = null, this.clipAction = null, this.animation = new Tw("|"), this.continueAnimation = !0, this.shapeRenderer = null, this.materialSettings = null, this.renderOptions = null, this.clipNormals = [
      new b(-1, 0, 0),
      new b(0, -1, 0),
      new b(0, 0, -1)
    ], this.camera_distance = 0, this.mouse = new H(), this.renderer = new fg({
      alpha: !0,
      antialias: !0,
      stencil: !0
    }), this.renderer.setPixelRatio(window.devicePixelRatio), this.renderer.setSize(this.state.get("cadWidth"), this.state.get("height")), this.renderer.setClearColor(16777215, 0), this.renderer.autoClear = !1, this.lastNotification = {}, this.lastBbox = null, this.expandedTree = null, this.compactTree = null, this.expandedNestedGroup = null, this.compactNestedGroup = null, this.lastObject = null, this.lastSelection = null, this.lastPosition = null, this.bboxNeedsUpdate = !1, this.keepHighlight = !1, this.shapes = null, this.raycaster = null, this.clipNormal0 = null, this.clipNormal1 = null, this.clipNormal2 = null, this.keymap = null, this.info = null, this.setPickHandler(!0), this.renderer.domElement.addEventListener("contextmenu", (a) => a.stopPropagation()), this.display.setupUI(this, this.renderer.domElement), console.debug("three-cad-viewer: WebGL Renderer created");
  }
  /**
   * Return three-cad-viewer version as semver string.
   * @returns semver version
   * @public
   */
  version() {
    return hf;
  }
  /**
   * Apply render options and build materialSettings object.
   * Called by render() after state is populated with render options.
   * @param options - The provided options object for rendering.
   */
  setRenderDefaults(e) {
    this.state.updateRenderState(e, !0), this.materialSettings = {
      ambientIntensity: this.state.get("ambientIntensity"),
      directIntensity: this.state.get("directIntensity"),
      metalness: this.state.get("metalness"),
      roughness: this.state.get("roughness")
    };
  }
  /**
   * Apply view options to state.
   * Called by render() after state is populated.
   * @param options - The provided options object for the view.
   */
  setViewerDefaults(e) {
    this.state.updateViewerState(e);
  }
  /**
   * @deprecated Use state properties directly. Kept for backwards compatibility.
   */
  setDisplayDefaults() {
  }
  dumpOptions() {
    this.state.dump();
  }
  // ---------------------------------------------------------------------------
  // Shape Tessellation & Decomposition
  // ---------------------------------------------------------------------------
  /**
   * Get or create the ShapeRenderer instance with current configuration.
   */
  getShapeRenderer() {
    const e = {
      cadWidth: this.state.get("cadWidth"),
      height: this.state.get("height"),
      edgeColor: this.state.get("edgeColor"),
      transparent: this.state.get("transparent"),
      defaultOpacity: this.state.get("defaultOpacity"),
      metalness: this.state.get("metalness"),
      roughness: this.state.get("roughness"),
      normalLen: this.state.get("normalLen")
    };
    return this.shapeRenderer ? this.shapeRenderer.updateConfig(e) : this.shapeRenderer = new Aw(e), this.shapeRenderer;
  }
  /**
   * Render the shapes of the CAD object.
   * @param exploded - Whether to render the compact or exploded version
   * @param shapes - The Shapes object.
   * @returns A nested THREE.Group object and navigation tree.
   */
  renderTessellatedShapes(e, t) {
    const i = this.getShapeRenderer(), n = i.render(e, t);
    return i.bbox && (this.bbox = i.bbox), n;
  }
  // ---------------------------------------------------------------------------
  // Animation Control
  // ---------------------------------------------------------------------------
  /**
   * Add a position animation track (full 3D translation).
   * @param selector - path/id of group to be animated.
   * @param times - array of keyframe times.
   * @param positions - array of [x, y, z] position offsets.
   */
  addPositionTrack(e, t, i) {
    this.animation.addPositionTrack(e, this.rendered.nestedGroup.groups[e], t, i);
  }
  /**
   * Add a single-axis translation animation track.
   * @param selector - path/id of group to be animated.
   * @param axis - which axis to translate along ("x", "y", or "z").
   * @param times - array of keyframe times.
   * @param values - array of translation values along the axis.
   */
  addTranslationTrack(e, t, i, n) {
    this.animation.addTranslationTrack(e, this.rendered.nestedGroup.groups[e], t, i, n);
  }
  /**
   * Add a quaternion rotation animation track.
   * @param selector - path/id of group to be animated.
   * @param times - array of keyframe times.
   * @param quaternions - array of [x, y, z, w] quaternion values.
   */
  addQuaternionTrack(e, t, i) {
    this.animation.addQuaternionTrack(e, this.rendered.nestedGroup.groups[e], t, i);
  }
  /**
   * Add a single-axis rotation animation track.
   * @param selector - path/id of group to be animated.
   * @param axis - which axis to rotate around ("x", "y", or "z").
   * @param times - array of keyframe times.
   * @param angles - array of rotation angles in degrees.
   */
  addRotationTrack(e, t, i, n) {
    this.animation.addRotationTrack(e, this.rendered.nestedGroup.groups[e], t, i, n);
  }
  /**
   * Initialize the animation.
   * @param duration - overall duration of the animation.
   * @param speed - speed of the animation.
   * @param label - animation label.
   * @param repeat - whether to repeat the animation.
   */
  initAnimation(e, t, i = "A", n = !0) {
    if (this.animation == null || this.animation.tracks.length === 0) {
      ft.error("Animation does not have tracks");
      return;
    }
    ft.debug("Animation initialized"), this.hasAnimationLoop || this.toggleAnimationLoop(!0), this.state.set("animationMode", i === "E" ? "explode" : "animation"), this.clipAction = this.animation.animate(this.rendered.nestedGroup.rootGroup, e, t, n), this.state.set("animationSliderValue", 0);
  }
  /**
   * Check whether animation object exists
   */
  hasAnimation() {
    return !!this.animation.clipAction;
  }
  /**
   * Clear the animation object and dispose dependent objects
   */
  clearAnimation() {
    this.animation && ct(this.animation), this.state.set("animationMode", "none"), this.toggleAnimationLoop(!1);
  }
  /**
   * Set the animation to a specific relative time (0-1).
   * Pauses the animation at that point.
   * @param fraction - relative time between 0 and 1.
   */
  setRelativeTime(e) {
    this.animation.setRelativeTime(e), this.state.set("animationSliderValue", e * 1e3);
  }
  /**
   * Get the current relative animation time (0-1).
   * @returns relative time between 0 and 1.
   */
  getRelativeTime() {
    return this.animation.getRelativeTime();
  }
  toggleAnimationLoop(e) {
    e ? (this.continueAnimation = !0, this.hasAnimationLoop = !0, this.rendered.controls.removeChangeListener(), console.debug("three-cad-viewer: Change listener removed"), this.animate(), console.debug("three-cad-viewer: Animation loop started")) : (this.hasAnimationLoop && console.debug("three-cad-viewer: Turning animation loop off"), this.continueAnimation = !1, this.hasAnimationLoop = !1, this.rendered.controls.addChangeListener(() => this.update(!0, !0)), console.debug("three-cad-viewer: Change listener registered"), setTimeout(() => this.update(!0, !0), 50));
  }
  // ---------------------------------------------------------------------------
  // Cleanup & Disposal
  // ---------------------------------------------------------------------------
  /**
   * Remove all assets and event handlers. Call when done with the viewer.
   *
   * This disposes:
   * - WebGL renderer and context
   * - All Three.js objects (geometries, materials, textures)
   * - Event listeners
   * - CAD tools and raycaster
   *
   * After calling dispose(), the viewer instance should not be used.
   *
   * @public
   */
  dispose() {
    this.clear(), this.renderer.renderLists.dispose(), this.renderer.dispose(), typeof this.renderer.forceContextLoss == "function" && this.renderer.forceContextLoss(), console.debug("three-cad-viewer: WebGL context disposed"), this.materialSettings = null, this.compactTree = null, ct(this.cadTools), this.clipAction = null, this.lastNotification = {}, this.clipNormal0 = null, this.clipNormal1 = null, this.clipNormal2 = null, this.renderOptions = null, this.tree = null, this.bbox = null, this._stencilCSize = 0, this._treeNeedsRebuild = !1;
    for (const e of this._pendingDisposal)
      ct(e);
    this._pendingDisposal = [], this.keymap = null, this.raycaster && (this.raycaster.dispose(), this.raycaster = null);
  }
  /**
   * Clear the current CAD view without disposing the renderer.
   *
   * Use this to remove shapes before rendering new ones.
   * The viewer remains usable after clear().
   *
   * @public
   */
  clear() {
    var e;
    if (this._rendered) {
      if (this.hasAnimationLoop = !1, this.continueAnimation = !1, this._rendered.controls.removeChangeListener(), console.debug("three-cad-viewer: Change listener removed"), this.hasAnimationLoop = !1, this.state.set("animationMode", "none"), this.animation != null && ct(this.animation), ((e = this.shapes) == null ? void 0 : e.format) === "GDS" && this.state.set("zscaleActive", !1), this.state.set("activeTab", "tree"), this.renderer.clear(), this.cadTools) {
        this.cadTools.disable();
        const t = this.state.get("activeTool");
        t != null && (this.state.set("activeTool", null), this.display.setTool(t, !1));
      }
      ct(this._rendered.scene), ct(this._rendered.gridHelper), ct(this._rendered.clipping), ct(this._rendered.camera), ct(this._rendered.controls), ct(this._rendered.treeview), this.display.clearCadTree(), ct(this.info), this._rendered = null, this.ready = !1;
    }
    this.shapes != null && (this.shapes = null), this.expandedNestedGroup != null && (ct(this.expandedNestedGroup), this.expandedNestedGroup = null), this.compactNestedGroup != null && (ct(this.compactNestedGroup), this.compactNestedGroup = null);
  }
  /**
   * Build nestedGroup and treeview for initial render.
   * @param scene - The scene to add the group to
   * @param expanded - whether to render the exploded or compact version
   * @returns The nestedGroup and treeview
   */
  buildInitialGroup(e, t) {
    const i = new Co("buildInitialGroup", this.state.get("timeit"));
    this.setRenderDefaults(this.renderOptions);
    const n = this.renderTessellatedShapes(t, this.shapes), s = n.group;
    if (t ? (this.expandedNestedGroup = n.group, this.expandedTree = n.tree) : (this.compactNestedGroup = n.group, this.compactTree = n.tree), s.setTransparent(this.state.get("transparent")), s.setBlackEdges(this.state.get("blackEdges")), s.setMetalness(this.state.get("metalness")), s.setRoughness(this.state.get("roughness")), s.setPolygonOffset(2), i.split(`rendered${t ? " exploded" : " compact"} shapes`), this.tree = t ? this.expandedTree : this.compactTree, e.children[0] = s.rootGroup, i.split("added shapes to scene"), !this.tree)
      throw new Error("Tree not initialized");
    const a = new gh(this.tree, this.display.cadTreeScrollContainer, this.setObject, this.handlePick, this.update, this.notifyStates, this.getNodeColor, this.state.get("theme"), this.state.get("newTreeBehavior"), !1);
    this.display.clearCadTree();
    const o = a.create();
    return i.split("created tree"), this.display.addCadTree(o), a.render(), i.split("rendered tree"), i.stop(), { nestedGroup: s, treeview: a };
  }
  /**
   * Toggle the two version of the NestedGroup.
   * Must only be called after render() has completed.
   * @param expanded - whether to render the exploded or compact version
   */
  toggleGroup(e) {
    if (!this.rendered)
      throw new Error("toggleGroup called before render()");
    const t = new Co("toggleGroup", this.state.get("timeit")), i = (o) => {
      o.setTransparent(this.state.get("transparent")), o.setBlackEdges(this.state.get("blackEdges")), o.setMetalness(this.state.get("metalness")), o.setRoughness(this.state.get("roughness")), o.setPolygonOffset(2);
    };
    let n;
    if (this.compactNestedGroup == null && !e || this.expandedNestedGroup == null && e) {
      this.setRenderDefaults(this.renderOptions);
      const o = this.renderTessellatedShapes(e, this.shapes);
      n = o.group, e ? (this.expandedNestedGroup = o.group, this.expandedTree = o.tree) : (this.compactNestedGroup = o.group, this.compactTree = o.tree), i(n), t.split(`rendered${e ? " exploded" : " compact"} shapes`);
    } else
      n = e ? this.expandedNestedGroup : this.compactNestedGroup, i(n);
    if (this.expandedTree && this.syncTreeStates(this.compactTree, this.expandedTree, e, ""), t.split("synched tree states"), this.tree = e ? this.expandedTree : this.compactTree, this.rendered.scene.children[0] = n.rootGroup, this.rendered.nestedGroup = n, t.split("added shapes to scene"), ct(this.rendered.treeview), !this.tree)
      throw new Error("Tree not initialized");
    const s = new gh(this.tree, this.display.cadTreeScrollContainer, this.setObject, this.handlePick, this.update, this.notifyStates, this.getNodeColor, this.state.get("theme"), this.state.get("newTreeBehavior"), !1);
    this.rendered.treeview = s, this.display.clearCadTree();
    const a = s.create();
    t.split("created tree"), this.display.addCadTree(a), s.render(), t.split("rendered tree"), t.stop();
  }
  /**
   * Set the active sidebar tab.
   * @param tabName - Tab name: "tree", "clip", "material", or "zebra"
   * @param notify - whether to send notification or not.
   */
  setActiveTab(e, t = !0) {
    this.state.set("activeTab", e, t);
  }
  toggleTab(e) {
    const t = new Co("toggleTab", this.state.get("timeit"));
    switch (this.setActiveTab("tree", !1), t.split("collapse tree"), this.state.get("collapse")) {
      case Jt.COLLAPSED:
        this.rendered.treeview.collapseAll();
        break;
      case Jt.ROOT:
        this.rendered.treeview.openLevel(1);
        break;
      case Jt.EXPANDED:
        this.rendered.treeview.expandAll();
        break;
      case Jt.LEAVES:
        this.rendered.treeview.openLevel(-1);
        break;
    }
    this.checkChanges({ states: this.getStates() }, !0), t.split("notify state changes"), t.stop(), this.display.toggleClippingTab(!e);
  }
  /**
   * Render a CAD object and build the navigation tree.
   *
   * This is the main entry point for displaying CAD geometry. It:
   * - Creates the Three.js scene with lights, camera, and controls
   * - Tessellates and renders the shape geometry
   * - Builds the navigation tree UI
   * - Sets up clipping planes and helpers
   *
   * @param shapes - the Shapes object representing the tessellated CAD object
   * @param renderOptions - the render options (edge color, opacity, etc.)
   * @param viewerOptions - the viewer options (camera position, clipping, etc.)
   * @public
   */
  render(e, t, i) {
    this.shapes = e, this.renderOptions = t, this.setViewerDefaults(i), this.animation.cleanBackup();
    const n = new Co("viewer", this.state.get("timeit")), s = new Ma(), { nestedGroup: a, treeview: o } = this.buildInitialGroup(s, !1);
    n.split("scene and tree done"), this.bbox || (this.bbox = a.boundingBox());
    const l = new b();
    this.bbox.getCenter(l), this.bb_max = this.bbox.max_dist_from_center(), this.bb_radius = Math.max(this.bbox.boundingSphere().radius, l.length()), n.split("bounding box");
    const c = new va(this.state.get("cadWidth"), this.state.get("height"), this.bb_radius, i.target ?? this.bbox.center(), this.state.get("ortho"), i.up ?? this.state.get("up")), h = new aE(this.state.get("control"), c.getCamera(), new b(...i.target ?? this.bbox.center()), this.renderer.domElement, this.state.get("rotateSpeed"), this.state.get("zoomSpeed"), this.state.get("panSpeed"), this.state.get("holroyd"));
    h.controls.enableKeys = !1, "screenSpacePanning" in h.controls && (h.controls.screenSpacePanning = !0);
    const d = new Dd(16777215, Eo(this.state.get("ambientIntensity")));
    s.add(d);
    const u = new Id(16777215, Eo(this.state.get("directIntensity")));
    s.add(u);
    const p = new dw({
      bbox: this.bbox,
      ticks: this.state.get("ticks"),
      gridFontSize: this.state.get("gridFontSize"),
      centerGrid: this.state.get("centerGrid"),
      axes0: this.state.get("axes0"),
      grid: [...this.state.get("grid")],
      flipY: i.up === "Z",
      theme: this.state.get("theme"),
      cadWidth: this.state.get("cadWidth"),
      height: this.state.get("height"),
      maxAnisotropy: this.renderer.capabilities.getMaxAnisotropy(),
      tickValueElement: this.display.tickValueElement,
      tickInfoElement: this.display.tickInfoElement,
      getCamera: () => {
        var S;
        return ((S = this._rendered) == null ? void 0 : S.camera.getCamera()) ?? null;
      },
      getAxes0: () => {
        var S;
        return ((S = this.state) == null ? void 0 : S.get("axes0")) ?? !1;
      }
    });
    p.computeGrid(), s.add(p), this.gridSize = p.size;
    const m = new vg(this.bbox.center(), this.gridSize / 2, 2, this.state.get("cadWidth"), this.state.get("height"), this.state.get("axes0"), this.state.get("axes"), this.state.get("theme"));
    s.add(m);
    const _ = 1.1 * Math.max(Math.abs(this.bbox.min.length()), Math.abs(this.bbox.max.length()));
    this._stencilCSize = _;
    const g = new ww(this.bbox.center(), 2 * _, a, {
      onNormalChange: (S, C) => this.display.setNormalLabel(S, C)
    }, this.state.get("theme"));
    s.add(g);
    const f = this.state.get("theme"), v = new gw(80, 80, c.getCamera(), f);
    v.create(), this._rendered = {
      scene: s,
      camera: c,
      controls: h,
      nestedGroup: a,
      gridHelper: p,
      axesHelper: m,
      clipping: g,
      treeview: o,
      orientationMarker: v,
      ambientLight: d,
      directLight: u
    }, i.position == null && i.quaternion == null ? (this.presetCamera("iso", this.state.get("zoom")), this.state.set("highlightedButton", "iso")) : i.position != null ? (this.setCamera(!1, new b(...i.position), i.quaternion ? new ot(...i.quaternion) : null, this.state.get("zoom")), i.quaternion == null && c.lookAtTarget()) : (this.display.addInfoHtml("<b>quaternion needs position to be provided, falling back to ISO view</b>"), this.presetCamera("iso", this.state.get("zoom"))), h.update(), h.saveState(), this.setAmbientLight(this.state.get("ambientIntensity")), this.setDirectLight(this.state.get("directIntensity")), this.display.setSliderLimits(this.gridSize / 2), this.display.syncClipSlidersFromState();
    const x = i.clipSlider0 != null ? i.clipSlider0 : this.gridSize / 2, y = i.clipSlider1 != null ? i.clipSlider1 : this.gridSize / 2, A = i.clipSlider2 != null ? i.clipSlider2 : this.gridSize / 2;
    a.setClipPlanes(g.clipPlanes), this.setLocalClipping(!1), g.setVisible(!1), this.toggleTab(!1), this.display.updateUI(), n.split("ui updated"), this.display.autoCollapse(), n.split("stencil done"), this.toggleAnimationLoop(this.hasAnimationLoop), this.ready = !0, this.setClipNormal(0, i.clipNormal0 ?? null, x, !0), this.setClipNormal(1, i.clipNormal1 ?? null, y, !0), this.setClipNormal(2, i.clipNormal2 ?? null, A, !0), this.setClipSlider(0, x, !0), this.setClipSlider(1, y, !0), this.setClipSlider(2, A, !0), this.setClipIntersection(i.clipIntersection ?? !1, !0), this.setClipObjectColorCaps(i.clipObjectColors ?? !1, !0), this.setClipPlaneHelpers(i.clipPlaneHelpers ?? !1, !0), this.display.showReadyMessage(hf, this.state.get("control")), n.split("show done"), this.notifyCallback && this.notifyCallback({
      // Computed values from controls/camera
      target: { old: null, new: ji(h.target.toArray()) },
      target0: { old: null, new: ji(h.target0.toArray()) },
      position: { old: null, new: this.rendered.camera.getPosition().toArray() },
      quaternion: { old: null, new: this.rendered.camera.getQuaternion().toArray() },
      zoom: { old: null, new: this.rendered.camera.getZoom() },
      // All config values from state
      ...this.state.getAllNotifiable()
    }), n.split("notification done"), this.update(!0, !1), o.update(), this.display.setTheme(this.state.get("theme")), this.setZebraCount(this.state.get("zebraCount")), this.setZebraDirection(this.state.get("zebraDirection")), this.setZebraOpacity(this.state.get("zebraOpacity")), this.setZebraColorScheme(this.state.get("zebraColorScheme")), this.setZebraMappingMode(this.state.get("zebraMappingMode")), n.split("update done"), n.stop();
  }
  // ---------------------------------------------------------------------------
  // Camera Type & Projection
  // ---------------------------------------------------------------------------
  /**
   * Get camera type.
   * @returns "ortho" or "perspective".
   */
  getCameraType() {
    return this.rendered.camera.ortho ? "ortho" : "perspective";
  }
  /**
   * Set camera mode to OrthographicCamera or PerspectiveCamera.
   * @param flag - true for orthographic, false for perspective
   * @param notify - whether to send notification or not.
   * @public
   */
  switchCamera(e, t = !0) {
    this.state.set("ortho", e, t), this.rendered.camera.switchCamera(e), this.rendered.controls.setCamera(this.rendered.camera.getCamera()), this.rendered.gridHelper.scaleLabels(), this.rendered.gridHelper.update(this.rendered.camera.getZoom(), !0), this.update(!0);
  }
  /**
   * Recenter camera on the bounding box center of all objects.
   * @param notify - whether to send notification or not.
   */
  recenterCamera(e = !0) {
    const t = new b(...this.bbox.center());
    this.setCameraTarget(t), this.update(!0, e);
  }
  /**
   * Centers the camera view on all visible objects in the scene.
   * Calculates a bounding box that encompasses all visible ObjectGroup instances
   * and sets the camera target to the center of that bounding box.
   *
   * @param notify - Whether to notify listeners of the camera update
   */
  centerVisibleObjects(e = !0) {
    const t = this.rendered.nestedGroup.groups, i = new _s();
    for (const s in t) {
      const a = t[s];
      a instanceof Mi && a.getVisibility() && i.expandByObject(a);
    }
    const n = new b(...i.center());
    this.setCameraTarget(n), this.update(!0, e);
  }
  /**
   * Enable/disable local clipping
   * @param flag - whether to enable local clipping
   */
  setLocalClipping(e) {
    this.renderer.localClippingEnabled = e, this.update(this.updateMarker);
  }
  /**
   * Backup animation (for switch to explode animation)
   */
  backupAnimation() {
    this.animation.hasTracks() && this.animation.backup();
  }
  /**
   * Restore animation (for switch back from explode animation)
   */
  restoreAnimation() {
    if (this.animation.hasBackup()) {
      const e = this.animation.restore();
      this.initAnimation(e.duration, e.speed, "A", e.repeat);
    }
  }
  removeLastBbox() {
    this.lastBbox != null && (this.rendered.scene.remove(this.lastBbox.bbox), this.lastBbox.bbox.dispose(), this.lastBbox = null);
  }
  // ---------------------------------------------------------------------------
  // Object Picking & Selection
  // ---------------------------------------------------------------------------
  setPickHandler(e) {
    e ? this.renderer.domElement.addEventListener("dblclick", this.pick, !1) : this.renderer.domElement.removeEventListener("dblclick", this.pick, !1);
  }
  /**
   * Set raycast mode
   * @param flag - turn raycast mode on or off
   */
  setRaycastMode(e) {
    e ? (this.raycaster = new sf(this.rendered.camera, this.renderer.domElement, this.state.get("cadWidth"), this.state.get("height"), this.bb_max / 30, this.rendered.scene.children[0], this.handleRaycastEvent), this.raycaster.init()) : (this.raycaster && this.raycaster.dispose(), this.raycaster = null);
  }
  // ---------------------------------------------------------------------------
  // Appearance (Axes, Grid, Visual Settings)
  // ---------------------------------------------------------------------------
  /**
   * Get whether axes helpers are visible.
   * @returns true if axes are shown
   * @public
   */
  getAxes() {
    return this.state.get("axes");
  }
  /**
   * Get visibility of grids.
   * @returns grids value.
   */
  getGrids() {
    return this.state.get("grid");
  }
  /**
   * Get location of axes.
   * @returns axes0 value, true means at origin (0,0,0)
   */
  getAxes0() {
    return this.state.get("axes0");
  }
  /**
   * Get transparency state of CAD objects.
   * @returns transparent value.
   */
  getTransparent() {
    return this.state.get("transparent");
  }
  /**
   * Get blackEdges value.
   * @returns blackEdges value.
   */
  getBlackEdges() {
    return this.state.get("blackEdges");
  }
  /**
   * Get default color of the edges.
   * @returns edgeColor value.
   */
  getEdgeColor() {
    return this.state.get("edgeColor");
  }
  /**
   * Get default opacity.
   * @returns opacity value.
   */
  getOpacity() {
    return this.state.get("defaultOpacity");
  }
  /**
   * Get whether tools are shown/hidden.
   * @returns tools value.
   */
  getTools() {
    return this.state.get("tools");
  }
  // ---------------------------------------------------------------------------
  // Getters & Setters: Lighting & Materials
  // ---------------------------------------------------------------------------
  /**
   * Get intensity of ambient light.
   * @returns ambientLight value.
   */
  getAmbientLight() {
    return this.state.get("ambientIntensity");
  }
  /**
   * Get intensity of direct light.
   * @returns directLight value.
   */
  getDirectLight() {
    return this.state.get("directIntensity");
  }
  // ---------------------------------------------------------------------------
  // Camera State Getters & Setters
  // ---------------------------------------------------------------------------
  /**
   * Get ortho value as property (for ViewerLike interface compatibility).
   */
  get ortho() {
    var e;
    return ((e = this._rendered) == null ? void 0 : e.camera.ortho) ?? !0;
  }
  /**
   * Get camera property. Throws if not rendered.
   */
  get camera() {
    return this.rendered.camera;
  }
  /**
   * Get nestedGroup property. Throws if not rendered.
   */
  get nestedGroup() {
    return this.rendered.nestedGroup;
  }
  /**
   * Get clipping property. Throws if not rendered.
   */
  get clipping() {
    return this.rendered.clipping;
  }
  /**
   * Get treeview property. Returns null if not rendered.
   */
  get treeview() {
    var e;
    return ((e = this._rendered) == null ? void 0 : e.treeview) ?? null;
  }
  /**
   * Get orientationMarker property. Throws if not rendered.
   */
  get orientationMarker() {
    return this.rendered.orientationMarker;
  }
  /**
   * Get gridHelper property. Throws if not rendered.
   */
  get gridHelper() {
    return this.rendered.gridHelper;
  }
  /**
   * Get axesHelper property. Throws if not rendered.
   */
  get axesHelper() {
    return this.rendered.axesHelper;
  }
  /**
   * Get scene property. Throws if not rendered.
   */
  get scene() {
    return this.rendered.scene;
  }
  /**
   * Get controls property. Throws if not rendered.
   */
  get controls() {
    return this.rendered.controls;
  }
  /**
   * Get ambientLight property. Throws if not rendered.
   */
  get ambientLight() {
    return this.rendered.ambientLight;
  }
  /**
   * Get directLight property. Throws if not rendered.
   */
  get directLight() {
    return this.rendered.directLight;
  }
  /**
   * Get ortho value.
   * @returns ortho value.
   */
  getOrtho() {
    return this.rendered.camera.ortho;
  }
  /**
   * Set/unset camera's orthographic mode.
   * @param flag - whether to set orthographic mode or not.
   * @param notify - whether to send notification or not.
   */
  setOrtho(e, t = !0) {
    this.switchCamera(e, t);
  }
  /**
   * Set zscaling value.
   * @param value - scale factor.
   */
  setZscaleValue(e) {
    this.rendered.nestedGroup.setZScale(e), this.zScale = e, this.update(!0);
  }
  /**
   * Get zoom value.
   * @returns zoom value.
   * @public
   */
  getCameraZoom() {
    return this.rendered.camera.getZoom();
  }
  /**
   * Set zoom value.
   * @param val - float zoom value.
   * @param notify - whether to send notification or not.
   * @public
   */
  setCameraZoom(e, t = !0) {
    this.rendered.camera.setZoom(e), this.rendered.controls.update(), this.update(!0, t);
  }
  /**
   * Get the current camera position.
   * @returns camera position as 3 dim array [x,y,z].
   * @public
   */
  getCameraPosition() {
    return this.rendered.camera.getPosition().toArray();
  }
  /**
   * Set camera position.
   * @param position - camera position as 3 dim Array [x,y,z].
   * @param relative - flag whether the position is a relative (e.g. [1,1,1] for iso) or absolute point.
   * @param notify - whether to send notification or not.
   * @public
   */
  setCameraPosition(e, t = !1, i = !0) {
    this.rendered.camera.setPosition(e, t), this.rendered.controls.update(), this.update(!0, i);
  }
  /**
   * Get the current camera rotation as quaternion.
   * @returns camera rotation as 4 dim quaternion array [x,y,z,w].
   * @public
   */
  getCameraQuaternion() {
    return Fp(this.rendered.camera.getQuaternion().toArray());
  }
  /**
   * Set camera rotation via quaternion.
   * @param quaternion - camera rotation as 4 dim quaternion array [x,y,z,w].
   * @param notify - whether to send notification or not.
   * @public
   */
  setCameraQuaternion(e, t = !0) {
    this.rendered.camera.setQuaternion(e), this.rendered.controls.update(), this.update(!0, t);
  }
  /**
   * Get the current camera target.
   * @returns camera target as 3 dim array array [x,y,z].
   * @public
   */
  getCameraTarget() {
    return ji(this.rendered.controls.getTarget().toArray());
  }
  /**
   * Set camera target.
   * @param target - camera target as THREE.Vector3 or [x, y, z] tuple.
   * @param notify - whether to send notification or not.
   * @public
   */
  setCameraTarget(e, t = !0) {
    const i = Array.isArray(e) ? new b(...e) : e, n = this.rendered.camera.getCamera(), s = n.zoom, a = n.position.clone().sub(this.rendered.controls.getTarget());
    n.position.copy(i.clone().add(a)), n.updateWorldMatrix(!0, !1), this.rendered.controls.getTarget().copy(i), or(n) && (n.zoom = s, n.updateProjectionMatrix()), this.rendered.controls.update(), this.update(!0, t);
  }
  getCameraLocationSettings() {
    return {
      position: this.getCameraPosition(),
      quaternion: this.getCameraQuaternion(),
      target: this.getCameraTarget(),
      zoom: this.getCameraZoom()
    };
  }
  setCameraLocationSettings(e = null, t = null, i = null, n = null, s = !0) {
    e != null && this.rendered.camera.setPosition(e, !1), t != null && this.state.get("control") === "trackball" && this.rendered.camera.setQuaternion(t), i != null && this.rendered.controls.setTarget(new b(...i)), n != null && this.rendered.camera.setZoom(n), this.rendered.controls.update(), this.update(!0, s);
  }
  // ---------------------------------------------------------------------------
  // Tree State Management
  // ---------------------------------------------------------------------------
  /**
   * Get states of all treeview leaves.
   * @returns object mapping paths to visibility states.
   * @public
   */
  getStates() {
    return this._rendered ? this._rendered.treeview.getStates() : {};
  }
  /**
   * Get state of a treeview leaf for a path.
   * separator can be / or |
   * @param path - path of the object
   * @returns state value in the form of [mesh, edges] = [0/1, 0/1]
   * @public
   */
  getState(e) {
    if (!this._rendered)
      return null;
    const t = e.replaceAll("|", "/");
    return this._rendered.treeview.getState(t);
  }
  // ---------------------------------------------------------------------------
  // Dynamic Part Management
  // ---------------------------------------------------------------------------
  /**
   * Build tree data from a Shapes object.
   * Mirrors ShapeRenderer._getTree() logic.
   */
  _buildTreeData(e) {
    const t = (n) => {
      const s = {};
      for (const a of n)
        a.parts != null ? s[a.name] = t(a.parts) : s[a.name] = a.state;
      return s;
    }, i = {};
    return i[e.name] = t(e.parts ?? []), i;
  }
  /**
   * Find the parent Shapes node and the parent's parts array for a given path.
   * @param path - Absolute path like "/root/group/part"
   * @returns The parent Shapes node, or null if not found.
   */
  _findShapesParent(e) {
    if (!this.shapes)
      return null;
    const t = e.split("/").filter(Boolean);
    if (t.length < 2)
      return null;
    const i = t.slice(0, -1);
    let n = this.shapes;
    if (n.name !== i[0])
      return null;
    for (let s = 1; s < i.length; s++) {
      if (!n.parts)
        return null;
      const a = n.parts.find((o) => o.name === i[s]);
      if (!a)
        return null;
      n = a;
    }
    return n;
  }
  /**
   * Rebuild the treeview from the current shapes data.
   * Preserves visibility states across the rebuild.
   */
  _rebuildTreeView() {
    const e = this.rendered.treeview.getStates();
    this.compactTree = this._buildTreeData(this.shapes), this.tree = this.compactTree, ct(this.rendered.treeview);
    const t = new gh(this.tree, this.display.cadTreeScrollContainer, this.setObject, this.handlePick, this.update, this.notifyStates, this.getNodeColor, this.state.get("theme"), this.state.get("newTreeBehavior"), !1);
    this.rendered.treeview = t, this.display.clearCadTree();
    const i = t.create();
    this.display.addCadTree(i), t.render(), this.rendered.treeview.setStates(e);
    const n = this.state.get("collapse");
    n != null && this.collapseNodes(n, !1);
  }
  /**
   * Apply current material/rendering settings to new objects in the group.
   * @param paths - The paths of the newly added objects.
   */
  _applyCurrentSettings(e) {
    const t = this.rendered.nestedGroup;
    for (const i of e) {
      const n = t.groups[i];
      n instanceof Mi && (n.setTransparent(this.state.get("transparent")), n.setBlackEdges(this.state.get("blackEdges")), n.setMetalness(this.state.get("metalness")), n.setRoughness(this.state.get("roughness")), n.setPolygonOffset(2), t.clipPlanes && n.setClipPlanes(t.clipPlanes));
    }
  }
  /**
   * Add a part (leaf or subtree) to the scene under an existing parent.
   *
   * For a **leaf**, pass a Shapes object with `shape` set and `name`
   * as a plain name (no leading slash).  The absolute path is built as
   * `parentPath + "/" + partData.name`.
   *
   * For a **subtree**, pass a Shapes object with `parts` set and `id`
   * as a slash-prefixed relative tree (e.g. `"/shelf"`).  All `id`
   * fields in the tree are prefixed with `parentPath` before rendering.
   *
   * When adding many parts in a batch, pass `{ skipBounds: true }` to
   * defer the expensive bounds/clipping/treeview recomputation, then call
   * `updateBounds()` once after the loop.
   *
   * @param parentPath - Absolute path of the parent group
   *   (e.g. "/assembly").  Must already exist as a CompoundGroup.
   * @param partData - A Shapes object describing the part to add.
   * @param options - Optional settings.
   * @param options.skipBounds - When true, skip bounds/clipping/treeview
   *   update and re-render.  Caller must call `updateBounds()` afterwards.
   * @returns The absolute path of the added root element.
   * @throws If the viewer is not rendered, the parent doesn't exist,
   *   or the name/id already exists at that level.
   * @public
   */
  addPart(e, t, i = {}) {
    if (!this._rendered)
      throw new Error("Viewer.render() must be called before addPart()");
    const n = this.rendered.nestedGroup, s = n.groups[e];
    if (!s || !lw(s))
      throw new Error(`Parent group not found or not a CompoundGroup: ${e}`);
    const a = t.parts != null && Array.isArray(t.parts), o = a ? e + t.id : e + "/" + t.name;
    if (n.groups[o] != null)
      throw new Error(`Part already exists: ${o}`);
    a ? this._prefixIds(t, e) : t.id = o;
    const l = this._findShapesParent(o);
    if (!l)
      throw new Error(`Parent not found in shapes data: ${e}`);
    if (l.parts || (l.parts = []), l.parts.push(t), a) {
      const h = n.renderLoop(t);
      s.add(h);
    } else {
      const h = `${o}/__addPart_tmp__`, d = {
        version: t.version,
        id: h,
        name: "__addPart_tmp__",
        loc: [[0, 0, 0], [0, 0, 0, 1]],
        parts: [t]
      }, u = n.renderLoop(d), p = n.groups[o];
      u.remove(p), s.add(p), delete n.groups[h];
    }
    const c = Object.keys(n.groups).filter((h) => h === o || h.startsWith(o + "/"));
    return this._applyCurrentSettings(c), this.expandedNestedGroup != null && (ct(this.expandedNestedGroup), this.expandedNestedGroup = null, this.expandedTree = null), i.skipBounds ? (this._treeNeedsRebuild = !0, o) : (this._treeNeedsRebuild = !0, this.updateBounds(), o);
  }
  /**
   * Recursively prefix all `id` fields in a Shapes tree.
   */
  _prefixIds(e, t) {
    if (e.id = t + e.id, e.parts)
      for (const i of e.parts)
        this._prefixIds(i, t);
  }
  /**
   * Remove a part (leaf or subtree) from the scene by path.
   *
   * When removing many parts in a batch, pass `{ skipBounds: true }` to
   * defer the expensive bounds/clipping/treeview recomputation, then call
   * `updateBounds()` once after the loop.
   *
   * @param path - The absolute path of the part to remove
   *   (e.g., "/assembly/shelf_5").
   * @param options - Optional settings.
   * @param options.skipBounds - When true, skip bounds/clipping/treeview
   *   update and re-render.  Caller must call `updateBounds()` afterwards.
   * @throws If the viewer is not rendered or the path doesn't exist.
   * @public
   */
  removePart(e, t = {}) {
    if (!this._rendered)
      throw new Error("Viewer.render() must be called before removePart()");
    const i = this.rendered.nestedGroup, n = i.groups[e];
    if (!n)
      throw new Error(`Part not found: ${e}`);
    n.parent && n.parent.remove(n);
    const s = Object.keys(i.groups).filter((o) => o === e || o.startsWith(e + "/"));
    for (const o of s)
      delete i.groups[o];
    const a = this._findShapesParent(e);
    if (a && a.parts) {
      const o = e.substring(e.lastIndexOf("/") + 1);
      a.parts = a.parts.filter((l) => l.name !== o);
    }
    if (this.expandedNestedGroup != null && (ct(this.expandedNestedGroup), this.expandedNestedGroup = null, this.expandedTree = null), t.skipBounds) {
      this._pendingDisposal.push(n), this._treeNeedsRebuild = !0;
      return;
    }
    ct(n), this._treeNeedsRebuild = !0, this.updateBounds();
  }
  /**
   * Update an existing part's geometry.
   *
   * When the mesh topology is unchanged (same number of vertices, triangles,
   * and edge segments), buffers are updated in-place — no Three.js objects
   * are disposed or recreated.  When topology differs the method
   * automatically falls back to a batched `removePart` + `addPart`.
   *
   * Only leaf parts (ObjectGroups with `shapeGeometry`) are supported.
   * The part must already exist in the scene.
   *
   * When updating many parts in a batch, pass `{ skipBounds: true }` to
   * defer the expensive bounds/clipping recomputation, then call
   * `updateBounds()` once after the loop:
   *
   * ```ts
   * for (const p of parts) {
   *   viewer.updatePart(path, data, { skipBounds: true });
   * }
   * viewer.updateBounds();
   * ```
   *
   * @param path - The absolute path of the part to update
   *   (e.g., "/assembly/part").
   * @param partData - A Shapes object with the new `shape` data.
   *   The `shape.vertices`, `shape.normals`, `shape.triangles`, and
   *   `shape.edges` fields are used to update the geometry.
   *   Optionally `color`, `alpha`, and `loc` are synced into `this.shapes`.
   * @param options - Optional settings.
   * @param options.skipBounds - When true, skip bounds/clipping/explode-cache
   *   update and re-render.  Caller must call `updateBounds()` afterwards.
   * @throws If the viewer is not rendered, the path doesn't exist,
   *   or the target is not a leaf ObjectGroup with shape geometry.
   * @public
   */
  updatePart(e, t, i = {}) {
    var A;
    if (!this._rendered)
      throw new Error("Viewer.render() must be called before updatePart()");
    const s = this.rendered.nestedGroup.groups[e];
    if (!s)
      throw new Error(`Part not found: ${e}`);
    if (!fs(s))
      throw new Error(`Part is not a leaf ObjectGroup: ${e}`);
    if (!s.shapeGeometry)
      throw new Error(`Part has no shape geometry (may be edges/vertices only): ${e}`);
    if (!t.shape)
      throw new Error("partData.shape is required for updatePart");
    const a = t.shape, o = s.shapeGeometry, l = (S) => S ? S instanceof Float32Array || S instanceof Uint32Array ? S.length : Array.isArray(S) && S.length > 0 && Array.isArray(S[0]) ? S.reduce((C, P) => C + P.length, 0) : S.length : 0, c = o.getAttribute("position"), h = o.getIndex(), d = c.count === l(a.vertices) / 3, u = h != null && h.count === l(a.triangles);
    let p = !0;
    if (s.edges && a.edges)
      if (en(s.edges))
        p = (((A = s.edges.geometry.getAttribute("instanceStart")) == null ? void 0 : A.count) ?? 0) === l(a.edges) / 6;
      else {
        const S = s.edges.geometry.getAttribute("position");
        p = S != null && S.count === l(a.edges) / 3;
      }
    if (!d || !u || !p) {
      const S = e.substring(0, e.lastIndexOf("/"));
      this.removePart(e, { skipBounds: !0 }), this.addPart(S, t, { skipBounds: !0 }), i.skipBounds || this.updateBounds();
      return;
    }
    const m = (S) => S instanceof Float32Array ? S : Array.isArray(S) && S.length > 0 && Array.isArray(S[0]) ? new Float32Array(S.flat()) : new Float32Array(S), _ = (S) => S instanceof Uint32Array ? S : Array.isArray(S) && S.length > 0 && Array.isArray(S[0]) ? new Uint32Array(S.flat()) : new Uint32Array(S), g = m(a.vertices), f = m(a.normals), v = _(a.triangles);
    c.array.set(g), c.needsUpdate = !0;
    const x = o.getAttribute("normal");
    if (x.array.set(f), x.needsUpdate = !0, h.array.set(v), h.needsUpdate = !0, o.computeBoundingBox(), o.computeBoundingSphere(), s.edges && a.edges && a.edges.length > 0) {
      const S = m(a.edges);
      if (en(s.edges)) {
        const C = s.edges.geometry.getAttribute("instanceStart");
        if (C && "data" in C) {
          const P = C.data;
          P.array.set(S), P.needsUpdate = !0;
        } else
          s.edges.geometry.setPositions(S);
        s.edges.geometry.computeBoundingBox(), s.edges.geometry.computeBoundingSphere();
      } else {
        const C = s.edges.geometry, P = C.getAttribute("position");
        P.array.set(S), P.needsUpdate = !0, C.computeBoundingBox(), C.computeBoundingSphere();
      }
    }
    const y = this._findShapesParent(e);
    if (y && y.parts) {
      const S = e.substring(e.lastIndexOf("/") + 1), C = y.parts.find((P) => P.name === S);
      C && (C.shape = a, t.color !== void 0 && (C.color = t.color), t.alpha !== void 0 && (C.alpha = t.alpha), t.loc !== void 0 && (C.loc = t.loc));
    }
    i.skipBounds || this.updateBounds();
  }
  /**
   * Recompute scene bounds, camera far plane, clipping stencils, and
   * re-render.  Call this once after a batch of
   * `addPart`, `removePart`, or `updatePart` calls that used
   * `{ skipBounds: true }`.
   *
   * If parts were added or removed in the batch, the navigation treeview
   * is also rebuilt automatically.
   *
   * @public
   */
  updateBounds() {
    if (!this._rendered)
      throw new Error("Viewer.render() must be called before updateBounds()");
    const e = this.rendered.nestedGroup;
    e.bbox = null, this.bbox = e.boundingBox();
    const t = new b();
    this.bbox.getCenter(t), this.bb_max = this.bbox.max_dist_from_center(), this.bb_radius = Math.max(this.bbox.boundingSphere().radius, t.length()), this.rendered.camera.updateFarPlane(this.bb_radius), this.rendered.camera.updateCameraDistance(this.bb_radius);
    const i = this.rendered.controls.getResetLocation(), n = i.position0.clone().sub(i.target0);
    i.target0.set(...this.bbox.center()), i.position0.copy(i.target0).add(n), this.rendered.controls.setResetLocation(i.target0, i.position0, i.quaternion0, i.zoom0);
    const s = 1.1 * Math.max(Math.abs(this.bbox.min.length()), Math.abs(this.bbox.max.length()));
    if (s > this._stencilCSize + 1e-6) {
      this._stencilCSize = s;
      const a = this.rendered.clipping;
      a.rebuildStencils(this.bbox.center(), 2 * s), e.setClipPlanes(a.clipPlanes), this.display.setSliderLimits(s);
    }
    if (this.expandedNestedGroup != null && (ct(this.expandedNestedGroup), this.expandedNestedGroup = null, this.expandedTree = null), this._treeNeedsRebuild && (this._treeNeedsRebuild = !1, this._rebuildTreeView()), this.update(this.updateMarker), this._pendingDisposal.length > 0) {
      for (const a of this._pendingDisposal)
        ct(a);
      this._pendingDisposal = [];
    }
  }
  /**
   * Pre-size the clipping stencil region so that all future `updatePart` /
   * `updateBounds` calls whose geometry stays within `bb` will never trigger
   * an expensive `rebuildStencils`.
   *
   * Call this once before a series of updates when the maximum extent of the
   * geometry is known upfront (e.g. the parameter range of a slider).
   *
   * @param bb - The maximum bounding box that geometry will ever occupy.
   */
  ensureStencilSize(e) {
    if (!this._rendered)
      throw new Error("Viewer.render() must be called before ensureStencilSize()");
    const t = new b(e.xmin, e.ymin, e.zmin), i = new b(e.xmax, e.ymax, e.zmax), n = new b().addVectors(t, i).multiplyScalar(0.5), s = 1.1 * Math.max(Math.abs(t.length()), Math.abs(i.length()));
    if (s > this._stencilCSize + 1e-6) {
      this._stencilCSize = s;
      const a = this.rendered.clipping, o = this.rendered.nestedGroup;
      a.rebuildStencils([n.x, n.y, n.z], 2 * s), o.setClipPlanes(a.clipPlanes), this.display.setSliderLimits(s);
    }
  }
  // ---------------------------------------------------------------------------
  // UI sensitivity
  // ---------------------------------------------------------------------------
  /**
   * Get zoom speed.
   * @returns zoomSpeed value.
   */
  getZoomSpeed() {
    return this.state.get("zoomSpeed");
  }
  /**
   * Get panning speed.
   * @returns pan speed value.
   */
  getPanSpeed() {
    return this.state.get("panSpeed");
  }
  /**
   * Get rotation speed.
   * @returns rotation speed value.
   */
  getRotateSpeed() {
    return this.state.get("rotateSpeed");
  }
  /**
   * Get holroyd (non-tumbling) trackball mode.
   * @returns holroyd flag.
   */
  getHolroyd() {
    return this.state.get("holroyd");
  }
  // ---------------------------------------------------------------------------
  // Clipping Planes
  // ---------------------------------------------------------------------------
  /**
   * Get intersection mode.
   * @returns clip intersection value.
   */
  getClipIntersection() {
    return this.state.get("clipIntersection");
  }
  /**
   * Get clipping plane state.
   * @returns clip plane visibility value.
   */
  getClipPlaneHelpers() {
    return this.state.get("clipPlaneHelpers");
  }
  /**
   * Get clipping plane state.
   * @param index - index of the normal: 0, 1 ,2
   * @returns clip plane visibility value.
   */
  getClipNormal(e) {
    return ji(this.clipNormals[e].toArray());
  }
  /**
   * Set the normal at index to a given normal
   * @param index - index of the normal: 0, 1 ,2
   * @param normal - 3 dim array representing the normal
   * @param value - value of the slider, if given
   * @param notify - whether to send notification or not.
   */
  setClipNormal(e, t, i = null, n = !0) {
    if (t == null || !this.ready)
      return;
    const s = new b(...t).normalize();
    this.clipNormals[e] = s;
    const a = ["clipNormal0", "clipNormal1", "clipNormal2"];
    this.state.set(a[e], s, n), this.rendered.clipping.setNormal(e, s), this.rendered.clipping.setConstant(e, this.gridSize / 2), i == null && (i = this.gridSize / 2), this.setClipSlider(e, i, n), this.rendered.nestedGroup.setClipPlanes(this.rendered.clipping.clipPlanes), this.update(this.updateMarker);
  }
  // ---------------------------------------------------------------------------
  // Explode Animation
  // ---------------------------------------------------------------------------
  /**
   * Calculate explode trajectories and initiate the animation.
   *
   * @param duration - duration of animation.
   * @param speed - speed of animation.
   * @param multiplier - multiplier for length of trajectories.
   * @public
   */
  explode(e = 2, t = 1, i = 2.5) {
    this.clearAnimation();
    const n = this.getAxes0(), s = new b(), a = new b();
    let o = null, l = null, c = null;
    n || new Tt().setFromObject(this.rendered.nestedGroup.rootGroup).getCenter(s);
    for (const h in this.rendered.nestedGroup.groups) {
      const d = this.rendered.nestedGroup.groups[h], u = new Tt();
      d instanceof Mi && u.expandByObject(d), !u.isEmpty() && (u.getCenter(a), o = a.sub(s), l = d.parent.worldToLocal(o.clone()), c = d.parent.worldToLocal(o.clone().multiplyScalar(i)), c.sub(l), this.addPositionTrack(h, [0, e], [[0, 0, 0], c.toArray()]));
    }
    this.initAnimation(e, t, "E", !1);
  }
  /**
   * Toggle explode mode on/off.
   * @param flag - whether to enable or disable explode mode
   * @param notify - whether to send notification or not.
   * @public
   */
  setExplode(e, t = !0) {
    const i = this.state.get("animationMode") === "explode";
    e !== i && (e ? (this.hasAnimation() && this.backupAnimation(), this.explode()) : this.hasAnimation() ? (this.controlAnimation("stop"), this.clearAnimation(), this.restoreAnimation()) : this.state.set("animationMode", "none"), this.checkChanges({ explode: e }, t));
  }
  /**
   * Activate or deactivate a measurement/selection tool.
   * This is the single entry point for tool state changes - Display should call this
   * rather than mutating state directly.
   * @param name - Tool name ("distance", "properties", "select")
   * @param flag - Whether to activate (true) or deactivate (false) the tool
   */
  activateTool(e, t) {
    const i = this.state.get("activeTool");
    t ? (this.state.set("animationMode", "none"), this.hasAnimation() && this.backupAnimation(), this.state.set("activeTool", e)) : ((i === e || e === "explode") && this.state.set("activeTool", null), this.hasAnimation() && (this.controlAnimation("stop"), this.clearAnimation(), this.restoreAnimation()));
  }
  // ---------------------------------------------------------------------------
  // Keyboard Configuration
  // ---------------------------------------------------------------------------
  /**
   * Set modifiers and action shortcuts for keymap
   *
   * @param config - keymap e.g. {"shift": "shiftKey", "ctrl": "ctrlKey", "meta": "altKey", "axes": "a", ...}
   */
  setKeyMap(e) {
    const t = /* @__PURE__ */ new Set(["shift", "ctrl", "meta", "alt"]), i = {}, n = {};
    for (const [s, a] of Object.entries(e))
      a !== void 0 && (t.has(s) ? i[s] = a : n[s] = a);
    if (Object.keys(i).length > 0) {
      const s = _t.get_config();
      _t.set(i), this.display.updateHelp(s, i);
    }
    _t.setActionShortcuts(n), this.display.updateTooltips();
  }
  // ---------------------------------------------------------------------------
  // View Layout
  // ---------------------------------------------------------------------------
  /**
   * Get the current CAD view width.
   * @public
   */
  get cadWidth() {
    return this.state.get("cadWidth");
  }
  /**
   * Get the current tree width.
   * @public
   */
  get treeWidth() {
    return this.state.get("treeWidth");
  }
  /**
   * Get the current view height.
   * @public
   */
  get height() {
    return this.state.get("height");
  }
  /**
   * Get the current glass mode state.
   * @public
   */
  get glass() {
    return this.state.get("glass");
  }
  /**
   * Resize UI and renderer.
   *
   * @param cadWidth - new width of CAD View
   * @param treeWidth - new width of navigation tree
   * @param height - new height of CAD View
   * @param glass - Whether to use glass mode or not
   * @public
   */
  resizeCadView(e, t, i, n = !1) {
    this.state.set("cadWidth", e), this.state.set("height", i), this.renderer.setSize(e, i), this.display.setSizes({
      treeWidth: t,
      treeHeight: this.state.get("treeHeight"),
      cadWidth: e,
      height: i
    }), this.state.set("glass", n);
    const s = e + (n ? 0 : t);
    this.display.updateToolbarCollapse(s), this.rendered.camera.changeDimensions(this.bb_radius, e, i), this.controls.handleResize(), this.update(!0), this.raycaster && (this.raycaster.width = e, this.raycaster.height = i);
  }
  // ---------------------------------------------------------------------------
  // THREE.js Helper Factories
  // ---------------------------------------------------------------------------
  vector3(e = 0, t = 0, i = 0) {
    return new b(e, t, i);
  }
  quaternion(e = 0, t = 0, i = 0, n = 1) {
    return new ot(e, t, i, n);
  }
}
class Pn {
  /**
   * Create a Slider instance
   * @param index - Slider identifier (e.g., "plane1", "ambientlight")
   * @param min - Minimum value
   * @param max - Maximum value
   * @param container - DOM container to search for slider elements
   * @param options - Configuration options
   */
  constructor(e, t, i, n, s) {
    this._notify = (l, c = !0) => {
      if (this.type == "plane" && this.notifyCallback && this.index !== void 0) {
        const h = {};
        h[`clip_slider_${this.index - 1}`] = parseFloat(String(l)), this.notifyCallback(h, c);
      }
    }, this.sliderChange = (l) => {
      if (!(l.target instanceof HTMLInputElement))
        return;
      const c = l.target.value;
      this.input.value = String(Math.round(1e3 * parseFloat(c)) / 1e3), this._handle(this.type, this.index, this.input.value), this._notify(c);
    }, this.inputChange = (l) => {
      if (!(l.target instanceof HTMLInputElement))
        return;
      const c = Math.max(Math.min(parseFloat(l.target.value), parseFloat(this.slider.max)), parseFloat(this.slider.min));
      this.input.value = String(Math.round(1e3 * c) / 1e3), this.slider.value = String(c), this._handle(this.type, this.index, this.input.value), this._notify(c);
    }, e.startsWith("plane") ? (this.index = parseInt(e.substring(5)), this.type = "plane") : (this.index = void 0, this.type = e), this.handler = s.handler, this.percentage = s.percentage || !1, this.notifyCallback = s.notifyCallback || null, this.isReadyCheck = s.isReadyCheck || null, this.onSetSlider = s.onSetSlider || null;
    const a = n.getElementsByClassName(`tcv_sld_value_${e}`)[0], o = n.getElementsByClassName(`tcv_inp_value_${e}`)[0];
    if (!(a instanceof HTMLInputElement) || !(o instanceof HTMLInputElement))
      throw new Error(`Slider elements not found for index "${e}" in container`);
    this.slider = a, this.input = o, this.slider.min = String(t), this.slider.max = String(i), this.input.value = String(i), this.slider.oninput = this.sliderChange, this.input.addEventListener("change", this.inputChange);
  }
  /**
   * Invoke the value change handler with appropriate value transformation
   * @param type - Slider type ("plane" or other identifier)
   * @param index - Plane index (for plane-type sliders)
   * @param value - The input value as string
   */
  _handle(e, t, i) {
    if (e == "plane" && t !== void 0)
      this.handler(t, i);
    else if (this.isReadyCheck ? this.isReadyCheck() : !0) {
      const s = this.percentage ? parseFloat(i) / 100 : parseFloat(i);
      this.handler(s);
    }
  }
  /**
   * Configure slider range for symmetric limits around zero (used for clipping planes).
   * Only sets min/max/step - does NOT change the current value.
   * Values should be set via state subscriptions.
   * @param limit - The absolute limit value for both min (-limit) and max (+limit)
   */
  setLimits(e) {
    const t = Math.abs(Math.round(Math.log10(2 * e)));
    this.slider.min = String(-e), this.slider.max = String(e), this.slider.step = String(Math.pow(10, -(3 - t)));
  }
  /**
   * Get the current slider value
   * @returns The current value as a float
   */
  getValue() {
    return parseFloat(this.input.value);
  }
  /**
   * Set the slider value programmatically
   * @param value - The value to set (will be clamped to min/max range)
   * @param notify - Whether to trigger change notifications
   */
  setValue(e, t = !0) {
    const i = Math.max(Math.min(e, parseFloat(this.slider.max)), parseFloat(this.slider.min));
    this.input.value = String(Math.round(1e3 * i) / 1e3), this.slider.value = String(i), this._handle(this.type, this.index, this.input.value), this._notify(i, t);
  }
  /**
   * Update slider visual without triggering handler (for state subscription updates).
   * Use this when the state has already been updated and you just need to sync the UI.
   * @param value - The value to set (will be clamped to min/max range)
   */
  setValueFromState(e) {
    const t = Math.max(Math.min(e, parseFloat(this.slider.max)), parseFloat(this.slider.min));
    this.input.value = String(Math.round(1e3 * t) / 1e3), this.slider.value = String(t);
  }
  /**
   * Clean up event listeners.
   */
  dispose() {
    this.slider.oninput = null, this.input.removeEventListener("change", this.inputChange);
  }
}
class vE {
  /**
   * Create a Toolbar instance.
   * @param container - The container element for the toolbar.
   * @param id - Unique identifier for the toolbar.
   * @param options - Configuration options.
   */
  constructor(e, t, i) {
    this._onMouseLeave = () => {
      this.getVisibleWidth() < this.getWidthThreshold() && this.minimize();
    }, this.minimize = (n = null) => {
      this._toggle(!0, n);
    }, this.maximize = (n = null) => {
      this._toggle(!0), this._toggle(!1, n);
    }, this.id = t, this.container = e, this.getVisibleWidth = i.getVisibleWidth, this.getWidthThreshold = i.getWidthThreshold, this.features = i.features, this.container.addEventListener("mouseleave", this._onMouseLeave), this.buttons = {}, this.ellipses = [], this.toggles = { 0: [], 1: [], 2: [], 3: [] };
  }
  addButton(e, t) {
    e.setId(this.id), this.buttons[e.name] = e, t != -1 && this.toggles[t].push(e), this.container.appendChild(e.html);
  }
  addSeparator() {
    const e = document.createElement("span");
    e.className = "tcv_separator", this.container.appendChild(e);
  }
  addEllipsis(e) {
    this.container.appendChild(e.html), this.ellipses.push(e);
  }
  defineGroup(e) {
    for (const t of e)
      for (const i of e)
        i != t && t.addGroupMember(i);
  }
  _toggle(e, t = null) {
    let i, n;
    t == null ? (i = this.toggles, n = this.ellipses) : (i = {}, i[t] = this.toggles[t], n = [this.ellipses[t]]);
    for (const s of n)
      e ? s.html.classList.remove("tcv_unvisible") : s.html.classList.add("tcv_unvisible");
    for (const s in i)
      for (const a of i[s])
        !e && (a.name === "distance" && !this.features.measureTools || a.name === "properties" && !this.features.measureTools || a.name === "select" && !this.features.selectTool || a.name === "explode" && !this.features.explodeTool) || a.show(!e);
  }
  dispose() {
    this.container.removeEventListener("mouseleave", this._onMouseLeave);
    for (const e of Object.values(this.buttons))
      e.dispose();
    for (const e of this.ellipses)
      e.dispose();
  }
}
class ko {
  constructor(e, t) {
    this._onMouseEnter = () => {
      this.action(this.id);
    }, this.id = e, this.action = t;
    const i = document.createElement("span");
    i.innerHTML = "...", i.className = "tcv_ellipsis tcv_unvisible", this.html = i, this.html.addEventListener("mouseenter", this._onMouseEnter);
  }
  dispose() {
    this.html.removeEventListener("mouseenter", this._onMouseEnter);
  }
}
class Rg {
  constructor(e, t, i) {
    this._onClick = (o) => {
      this.handler(o);
    }, this.handler = (o) => {
    }, this.name = t, this.containerId = "";
    const n = document.createElement("span");
    n.className = "tcv_tooltip", n.setAttribute("data-tooltip", i), n.setAttribute("data-base-tooltip", i);
    const s = document.createElement("span");
    s.className = "tcv_button_frame", n.appendChild(s);
    const a = document.createElement("input");
    a.className = "tcv_reset tcv_btn", a.type = "button", a.classList.add(`tcv_button_${t}`), s.appendChild(a), this.html = n, this.frame = s, this.html.addEventListener("click", this._onClick);
  }
  dispose() {
    this.html.removeEventListener("click", this._onClick);
  }
  setId(e) {
    this.containerId = e;
  }
  alignRight() {
    this.html.classList.add("tcv_align_right");
  }
  show(e) {
    this.html.style.display = e ? "inline-block" : "none";
  }
}
class Bi extends Rg {
  constructor(e, t, i, n) {
    super(e, t, i), this.handler = (s) => {
      const a = s instanceof MouseEvent ? _t.get(s, "shift") : !1;
      this.action(this.name, a);
    }, this.highlight = (s) => {
      this.frame.classList.toggle("tcv_btn_highlight", s);
    }, this.action = n;
  }
}
class ki extends Rg {
  constructor(e, t, i, n, s = !1, a = null) {
    if (super(e, t, i), this.get = () => this.state, this.set = (o) => {
      this.state = o, this.frame.classList.toggle("tcv_btn_click2", this.state);
    }, this.clearGroup = () => {
      for (const o of this.sameGroup)
        o.state && (o.state = !1, o.frame.classList.remove("tcv_btn_click2"), o.action(this.name, !1));
    }, this.extractIdFromName = (o) => {
      const l = "grid-", c = o.indexOf(l) + l.length, h = o.indexOf("_", c);
      return o.slice(c, h);
    }, this.handler = (o) => {
      if (!(o.target instanceof HTMLInputElement))
        return;
      const l = o.target, c = this.extractIdFromName(l.id || "");
      if (this.dropdown != null && c && this.dropdown.includes(c)) {
        const h = l.checked;
        this.action(`grid-${c}`, h), this.checkElems[c].checked = h;
      } else l.type === "button" && (this.state || this.clearGroup(), this.set(!this.state), this.action(this.name, this.state));
    }, this.action = n, this.state = s, this.dropdown = a, this.sameGroup = [], this.checkElems = {}, a != null) {
      const o = document.createElement("span");
      o.classList.add("tcv_grid-content"), o.classList.add("tcv_dropdown-content"), o.classList.add("tcv_round");
      for (const l of a) {
        const c = document.createElement("div");
        c.className = "tcv_tooltip", c.setAttribute("data-tooltip", `${i} ${l}`);
        const h = document.createElement("input");
        h.className = `tcv_grid-${l} tcv_check tcv_dropdown-entry`, h.id = `tcv_grid-${l}_${this.containerId}`, h.type = "checkbox", c.appendChild(h);
        const d = document.createElement("label");
        d.htmlFor = h.id, d.className = "tcv_label tcv_dropdown-entry", d.textContent = l, c.appendChild(d), o.appendChild(c), this.checkElems[l] = h;
      }
      this.frame.appendChild(o), this.frame.classList.add("tcv_grid-dropdown");
    }
  }
  addGroupMember(e) {
    this.sameGroup.push(e);
  }
}
class xE {
  /**
   * Create an Info panel instance.
   * @param html - The HTML container element for info display.
   */
  constructor(e) {
    this.html = e, this.number = 0, this.chunks = [], this.clear();
  }
  /**
   * Clear all displayed information.
   */
  clear() {
    this.html.innerHTML = "", this.number = 0, this.chunks = [];
  }
  /**
   * Dispose of resources and clear the container.
   */
  dispose() {
    this.clear(), this.html.innerHTML = "";
  }
  /**
   * Add plain text as a preformatted block.
   * @param msg - The text message to display.
   */
  addText(e) {
    this.addHtml(`<pre style="white-space: nowrap;">${e}</pre>`);
  }
  /**
   * Add HTML content to the info panel.
   * New content appears at the top of the list.
   * @param html - The HTML string to add.
   */
  addHtml(e) {
    this.chunks.unshift([this.number, e]), this.number += 1, this.render();
  }
  /**
   * Render all chunks to the container as a table.
   */
  render() {
    let e = "<table class='tcv_info_table'>";
    for (const t of this.chunks)
      e += "<tr class='tcv_info_row'>", e += `<td><pre class="tcv_info_num">[${t[0]}]</pre></td>`, e += `<td>${t[1]}</td>`, e += "</tr>";
    e += "</table>", this.html.innerHTML = e;
  }
  /**
   * Display version information for CadQuery and Jupyter CadQuery.
   * @param cqVersion - CadQuery version string.
   * @param jcqVersion - Jupyter CadQuery version string.
   */
  versionMsg(e, t) {
    this.addHtml(`<b>Versions</b>
          <table>
            <tr class="tcv_small_table"><td>CadQuery:</td>        <td>${e}</td> </tr>
            <tr class="tcv_small_table"><td>Jupyter CadQuery:</td><td>${t}</td> </tr>
          </table>`);
  }
  /**
   * Display the ready message with viewer version and control mode.
   * @param version - Viewer version string.
   * @param control - Control mode name (e.g., "orbit", "trackball").
   */
  readyMsg(e, t) {
    this.clear();
    const i = `<div class="tcv_info_header">Ready</div>
            <table class="small_table">
              <tr class="tcv_small_table_row" ><td>Version</td><td>${e}</td> </tr>
              <tr class="tcv_small_table_row" ><td>Control</td><td>${t}</td></tr>
              <tr class="tcv_small_table_row" ><td>Axes</td>
                <td>
                  <span class="tcv_info_red"><b>X</b></span>,
                  <span class="tcv_info_green"><b>Y</b></span>,
                  <span class="tcv_info_blue"><b>Z</b></span>
                </td>
              </tr>
            </table>`;
    this.addHtml(i);
  }
  /**
   * Display bounding box information for a selected object.
   * @param path - The object's path in the tree.
   * @param name - The object's name.
   * @param bb - The bounding box to display.
   */
  bbInfo(e, t, i) {
    let n = `
            <table class="tcv_small_table">
                <tr class="tcv_small_table_row">
                    <td><b>Path:</b></td>
                    <td>${e}</td>
                </tr>
                <tr class="tcv_small_table_row">
                    <td><b>Name:</b></td>
                    <td>${t}</td>
                </tr>
            </table>
            `;
    n += `
            <div class="tcv_info_header">Bounding box:</div>
            <table class="tcv_small_table">
                <tr class="tcv_small_table_row">
                    <th></th>
                    <th>min</th>
                    <th>max</th>
                    <th>center</th>
                </tr>
            `;
    const s = new b();
    i.getCenter(s), ["x", "y", "z"].forEach((a) => {
      n += `
                <tr class="tcv_small_table_row">
                    <th>${a}</th>
                    <td align='right'>${i.min[a].toFixed(3)}</td>
                    <td align='right'>${i.max[a].toFixed(3)}</td>
                    <td align='right'>${s[a].toFixed(3)}</td>
                </tr>
            `;
    }), n += "</table>", this.addHtml(n);
  }
  /**
   * Display camera target center information.
   * @param center - The center coordinates [x, y, z].
   */
  centerInfo(e) {
    const t = `<div>Camera target set to AABB center:</div><div class='tcv_info_line'>{ x: ${e[0].toFixed(2)}, y: ${e[1].toFixed(2)}, z: ${e[2].toFixed(2)} }</div>`;
    this.addHtml(t);
  }
}
var bE = `<div class="tcv_cad_viewer">
    <div class="tcv_cad_toolbar tcv_round"></div>

    <div class="tcv_cad_body">
        <div class="tcv_cad_navigation">
            <div class="tcv_cad_tree tcv_round">
                <div class="tcv_tabnav">
                    <span class="tcv_tooltip" style="flex: 1"><input class='tcv_tab_tree tcv_tab tcv_tab-left tcv_tab-selected' value="Tree" type="button" style="width: 100%" /></span>
                    <span class="tcv_tooltip" style="flex: 1"><input class='tcv_tab_clip tcv_tab tcv_tab-right tcv_tab-unselected' value="Clip" type="button" style="width: 100%" /></span>
                    <span class="tcv_tooltip" style="flex: 1"><input class='tcv_tab_material tcv_tab tcv_tab-right tcv_tab-unselected' value="Material" type="button" style="width: 100%" /></span>
                    <span class="tcv_tooltip" style="flex: 1"><input class='tcv_tab_zebra tcv_tab tcv_tab-right tcv_tab-unselected' value="Zebra" type="button" style="width: 100%" /></span>
                </div>
                <div class="tcv_cad_tree_toggles">
                    <span class="tcv_tooltip" data-tooltip="Collpase nodes with a single leaf">
                        <input class='tcv_collapse_singles tcv_btn tcv_small_btn' value="1" type="button" />
                    </span>
                    <span class="tcv_tooltip" data-tooltip="Expand root node only">
                        <input class='tcv_expand_root tcv_btn tcv_small_btn' value="R" type="button" />
                    </span>
                    <span class="tcv_tooltip" data-tooltip="Collpase tree">
                        <input class='tcv_collapse_all tcv_btn tcv_small_btn' value="C" type="button" />
                    </span>
                    <span class="tcv_tooltip" data-tooltip="Expand tree">
                        <input class='tcv_expand tcv_btn tcv_small_btn' value="E" type="button" />
                    </span>
                </div>
                <div class="tcv_box_content tcv_mac-scrollbar tcv_scroller">
                    <div class="tcv_cad_tree_container"></div>
                    <div class="tcv_cad_clip_container">
                        <div class="tcv_slider_group">
                            <div>
                                <span class="tcv_tooltip" data-tooltip="Set red clipping plane to view direction">
                                    <input class='tcv_btn_norm_plane1 tcv_btn tcv_plane' type="button" />
                                </span>
                                <span class="tcv_lbl_norm_plane1 tcv_label">N1 = (n/a, n/a, n/a)</span>
                            </div>
                            <div>
                                <input type="range" min="1" max="100" value="50"
                                    class="tcv_sld_value_plane1 tcv_clip_slider">
                                <input value=50 class="tcv_inp_value_plane1 tcv_clip_input"></input>
                            </div>
                        </div>
                        <div class="tcv_slider_group">
                            <div>
                                <span class="tooltip" data-tooltip="Set green clipping plane to view direction">
                                    <input class='tcv_btn_norm_plane2 tcv_btn tcv_plane' type="button" />
                                </span>
                                <span class="tcv_lbl_norm_plane2 tcv_label">N2 = (n/a, n/a, n/a)</span>
                            </div>
                            <div>
                                <input type="range" min="1" max="100" value="50"
                                    class="tcv_sld_value_plane2 tcv_clip_slider">
                                <input value=50 class="tcv_inp_value_plane2 tcv_clip_input"></input>
                            </div>
                        </div>
                        <div class="tcv_slider_group">
                            <div>
                                <span class="tooltip" data-tooltip="Set blue clipping plane to view direction">
                                    <input class='tcv_btn_norm_plane3 tcv_btn tcv_plane' type="button" />
                                </span>
                                <span class="tcv_lbl_norm_plane3 tcv_label">N3 = (n/a, n/a, n/a)</span>
                            </div>
                            <div>
                                <input type="range" min="1" max="100" value="50"
                                    class="tcv_sld_value_plane3 tcv_clip_slider">
                                <input value=50 class="tcv_inp_value_plane3 tcv_clip_input"></input>
                            </div>
                        </div>
                        <div class="tcv_clip_checks">
                            <div>
                                <span class="tcv_tooltip" data-tooltip="Use intersection clipping">
                                    <input class='tcv_clip_intersection tcv_check' type="checkbox" />
                                    <span class="tcv_label">Intersection</span>
                                </span>
                                <span class="tcv_tooltip" data-tooltip="Show clipping planes">
                                    <input class='tcv_clip_plane_helpers tcv_axes0 tcv_check' type="checkbox" />
                                    <span class="tcv_label">Planes</span>
                                </span>
                            </div>
                            <span class="tcv_tooltip" data-tooltip="Use object color caps instead of RGB">
                                <input class='tcv_clip_caps tcv_axes0 tcv_check' type="checkbox" />
                                <span class="tcv_label">Use object color caps</span>
                            </span>
                        </div>
                    </div>
                    <div class="tcv_cad_material_container">
                        <div class="tcv_cad_tree_toggles">
                            <span class="tcv_tooltip" data-tooltip="Reset to original values">
                                <input class='tcv_material_reset tcv_btn tcv_small_btn' value="R" type="button" />
                            </span>
                        </div>
                        <div class="tcv_material_ambientlight tcv_label">
                            Ambient light intensity (%)
                        </div>
                        <div class="tcv_slider_group">
                            <div>
                                <input type="range" min="0" max="20" value="1"
                                    class="tcv_sld_value_ambientlight tcv_clip_slider">
                                <input value=1 class="tcv_inp_value_ambientlight tcv_clip_input"></input>
                            </div>
                        </div>
                        <div class="tcv_material_pointlight tcv_label">
                            Directional light intensity (%)
                        </div>
                        <div class="tcv_slider_group">
                            <div>
                                <input type="range" min="0" max="40" value="1"
                                    class="tcv_sld_value_pointlight tcv_clip_slider">
                                <input value=1 class="tcv_inp_value_pointlight tcv_clip_input"></input>
                            </div>
                        </div>
                        <div class="tcv_material_metalness tcv_label">
                            Metalness (%)
                        </div>
                        <div class="tcv_slider_group">
                            <div>
                                <input type="range" min="0" max="100" value="40"
                                    class="tcv_sld_value_metalness tcv_clip_slider">
                                <input value=40 class="tcv_inp_value_metalness tcv_clip_input"></input>
                            </div>
                        </div>
                        <div class="tcv_material_roughness tcv_label">
                            Roughness (%)
                        </div>
                        <div class="tcv_slider_group">
                            <div>
                                <input type="range" min="0" max="100" value="40"
                                    class="tcv_sld_value_roughness tcv_clip_slider">
                                <input value=40 class="tcv_inp_value_roughness tcv_clip_input"></input>
                            </div>
                        </div>
                        <div class="tcv_material_info">
                            Note: This is not a full material renderer.
                        </div>
                    </div>
                    <div class="tcv_cad_zebra_container">
                        <div class="tcv_zebra_stripe_count tcv_label">
                            Stripe Count
                        </div>
                        <div class="tcv_slider_group">
                            <div>
                                <input type="range" min="2" max="50" value="10"
                                    class="tcv_sld_value_zebra_count tcv_clip_slider">
                                <input value=10 class="tcv_inp_value_zebra_count tcv_clip_input"></input>
                            </div>
                        </div>                        
                        <div class="tcv_zebra_stripe_opacity tcv_label">
                            Stripe Opacity
                        </div>
                        <div class="tcv_slider_group">
                            <div>
                                <input type="range" min="0.0" max="1.0" step="0.01" value="1.0"
                                    class="tcv_sld_value_zebra_opacity tcv_clip_slider">
                                <input value=1.0 class="tcv_inp_value_zebra_opacity tcv_clip_input"></input>
                            </div>
                        </div>                        
                        <div class="tcv_zebra_stripe_direction tcv_label">
                            Stripe Direction
                        </div>
                        <div class="tcv_slider_group">
                            <div>
                                <input type="range" min="0" max="90" step="0.5" value="0"
                                    class="tcv_sld_value_zebra_direction tcv_clip_slider">
                                <input value=0 class="tcv_inp_value_zebra_direction tcv_clip_input"></input>
                            </div>
                        </div>   
                        <div class="tcv_zebra_radio">
                            <div>
                                <span class="tcv_tooltip" data-tooltip="Select stripe color scheme">
                                    <input class='tcv_zebra_colorscheme tcv_radio tcv_zebra_color1' type="radio" id="zebra_blackwhite" name="zebra_color_group" value="blackwhite" checked>
                                    <label for="zebra_blackwhite" class="tcv_radio_label">B/W</label>
                                    <input class='tcv_zebra_colorscheme tcv_radio tcv_zebra_color2' type="radio" id="zebra_grayscale" name="zebra_color_group" value="grayscale">
                                    <label for="zebra_grayscale" class="tcv_radio_label">Gray</label>
                                    <input class='tcv_zebra_colorscheme tcv_radio tcv_zebra_color3' type="radio" id="zebra_colorful" name="zebra_color_group" value="colorful">
                                    <label for="zebra_colorful" class="tcv_radio_label">Colors</label>
                                </span>

                            </div>
                        </div>                                             
                        <div class="tcv_zebra_radio">
                            <div>
                               <span class="tcv_tooltip" data-tooltip="Select stripe mapping">
                                    <input class='tcv_zebra_mapping tcv_radio tcv_zebra_mapping1' type="radio" id="zebra_reflection" name="zebra_mapping_group" value="reflection" checked>
                                    <label for="zebra_reflection" class="tcv_radio_label">Reflection</label>
                                    <input class='tcv_zebra_mapping tcv_radio tcv_zebra_mapping2' type="radio" id="zebra_normal" name="zebra_mapping_group" value="normal">
                                    <label for="zebra_normal" class="tcv_radio_label">Normal</label>
                                </span>
                            </div>
                        </div>                                             
                    </div>
                </div>
            </div>
            <div class="tcv_cad_info_wrapper">
                <div class="tcv_toggle_info_wrapper">
                    <!-- <span class="tooltip" data-tooltip="Open/close info box"> -->
                        <!-- <input class='tcv_toggle_info tcv_btn tcv_small_info_btn' value="<" type="button" /> -->
                        <span class='tcv_toggle_info'></span><span class="tcv_info_label">Info</span>
                    <!-- </span> -->
                </div>
                <div class="tcv_cad_info tcv_round">
                    <div class="tcv_box_content tcv_mac-scrollbar tcv_scroller">
                        <div class="tcv_cad_info_container"></div>
                    </div>
                </div>
            </div>
        </div>

        <div class="tcv_cad_view">
            <div class="tcv_distance_measurement_panel tcv_panel tcv_round">
                <div class="tcv_measure_header">Distance</div>
            </div>

            <div class="tcv_properties_measurement_panel tcv_panel tcv_round">
                <div class="tcv_measure_header">Properties</div>
                <div class="tcv_measure_subheader">Shape</div>
            </div>

            <div class="tcv_cad_animation tcv_round">
                <span class="tcv_animation_label">E</span>
                <span><input type="range" min="0" max="1000" value="0"
                        class="tcv_animation_slider tcv_clip_slider"></span>
                <span class="tcv_tooltip" data-tooltip="Play animation"><input class='tcv_play tcv_btn'
                        type="button" /></span>
                <span class="tcv_tooltip" data-tooltip="Pause animation"><input class='tcv_pause tcv_btn'
                        type="button" /></span>
                <span class="tcv_tooltip" data-tooltip="Stop and reset animation"><input class='tcv_stop tcv_btn'
                        type="button" /></span>
            </div>
            
            <div class="tcv_cad_zscale tcv_round">
                <span class="tcv_animation_label">Z</span>
                <span><input type="range" min="1" max="32" value="0"
                        class="tcv_zscale_slider tcv_clip_slider"></span>
            </div>

            <div class="tcv_cad_help tcv_round">
                <table class="tcv_cad_help_layout">
                    <tr>
                        <td></td>
                        <td><b>Mouse Navigation</b></td>
                    </tr>
                    <tr>
                        <td>Rotate</td>
                        <td>&lt;left mouse button&gt;</td>
                    </tr>
                    <tr>
                        <td>Rotate up / down</td>
                        <td>&lt;{{ctrl}}&gt; + &lt;left mouse button&gt;</td>
                    </tr>
                    <tr>
                        <td>Rotate left / right</td>
                        <td>&lt;{{meta}}&gt; + &lt;left mouse button&gt;</td>
                    </tr>
                    <tr>
                        <td>Pan</td>
                        <td>&lt;{{shift}}&gt; + &lt;left mouse button&gt; or &lt;right mouse button&gt;</td>
                    </tr>
                    <tr>
                        <td>Zoom</td>
                        <td>&lt;mouse wheel&gt; or &lt;middle mouse button&gt;</td>
                    </tr>

                    <tr>
                        <td></td>
                        <td><b>Mouse Selection</b></td>
                    </tr>
                    <tr>
                        <td>Pick element</td>
                        <td>&lt;left mouse button&gt; double click</td>
                    </tr>
                    <tr>
                        <td></td>
                        <td>Click on navigation tree label</td>
                    </tr>
                    <tr>
                        <td></td>
                        <td>(Shows axis-aligned bounding box, AABB)</td>
                    </tr>
                    <tr>
                        <td>Isolate element</td>
                        <td>&lt;{{shift}}&gt; + &lt;left mouse button&gt; double click</td>
                    </tr>
                    <tr>
                        <td></td>
                        <td>&lt;{{shift}}&gt; + click on navigation tree label (nested)</td>
                    </tr>
                    <tr>
                        <td>Hide element</td>
                        <td>&lt;{{meta}}&gt; + &lt;left mouse button&gt; double click object</td>
                    </tr>
                    <tr>    
                        <td></td>                
                        <td>&lt;{{meta}}&gt; + &lt;left mouse button&gt; click tree label (nested)</td>
                    </tr>
                    <tr>
                        <td>Hide other elements</td>
                        <td>&lt;{{shift}}&gt; + &lt;{{meta}}&gt; + &lt;left mouse button&gt; click tree label (nested)</td>
                    </tr>
                    <tr>
                        <td>Set camera target</td>
                        <td>&lt;{{shift}}&gt + &lt;{{meta}}&gt; + &lt;left mouse button&gt; double click</td>
                    </tr>                    
                    <tr>
                        <td></td>
                        <td><b>CAD Object Tree</b></td>
                    </tr>
                    <tr>
                        <td>Collapse single leafs</td>
                        <td>Button '1' (all nodes with one leaf only)</td>
                    </tr>
                    <tr>
                        <td>Expand root only</td>
                        <td>Button 'R'</td>
                    </tr>
                    <tr>
                        <td>Collapse all nodes</td>
                        <td>Button 'C'</td>
                    </tr>
                    <tr>
                        <td>Expand all nodes</td>
                        <td>Button 'E'</td>
                    </tr>
                    <tr>
                        <td></td>
                        <td><b>Measure Mode</b></td>
                    </tr>
                    <tr>
                        <td>Select 1. (and 2.) object</td>
                        <td>&lt;left mouse button&gt;</td>
                    </tr>
                    <tr>
                        <td>Use center instead of min distance</td>
                        <td>&lt;{{shift}}&gt; + &lt;left mouse button&gt; for the second selection</td>
                    </tr>
                    <tr>
                        <td>Filter object types</td>
                        <td>Type menu or &lt;n&gt;one, &lt;s&gt;olid, &lt;f&gt;ace, &lt;e&gt;dge , &lt;v&gt;ertices</td>
                    </tr>
                    <tr>
                        <td>Unselect last object</td>
                        <td>&lt;right mouse button&gt;</td>
                    </tr>
                    <tr>
                        <td>Unselect all objects</td>
                        <td>&lt;ESC&gt;</td>
                    </tr>
                </table>
            </div>
            <div class="tcv_filter_menu">
                <div class="tcv_drop_down tcv_shape_filter">
                    <span class="tcv_round tcv_filter_content"><span class="tcv_filter_value">None</span>
                        <span class="tcv_filter_icon">⏶
                        </span></span>
                    <div class="tcv_filter_dropdown tcv_round">
                        <div class="tcv_filter_dropdown_value tvc_filter_none">None</div>
                        <div class="tcv_filter_dropdown_value tvc_filter_vertex">Vertex</div>
                        <div class="tcv_filter_dropdown_value tvc_filter_edge">Edge</div>
                        <div class="tcv_filter_dropdown_value tvc_filter_face">Face</div>
                        <div class="tcv_filter_dropdown_value tvc_filter_solid">Solid</div>
                    </div>
                </div>
            </div>
        </div>
    </div>
    <div class="tcv_tick_size">
        ⊢⊣<span class="tcv_tick_size_value">0</span>
    </div>
</div>`;
function SE(r) {
  const e = _t.getshortcuts("shift"), t = _t.getshortcuts("ctrl"), i = _t.getshortcuts("meta"), n = _t.getshortcuts("alt");
  return bE.replaceAll("{{id}}", r).replaceAll("{{shift}}", e).replaceAll("{{ctrl}}", t).replaceAll("{{meta}}", i).replaceAll("{{alt}}", n);
}
function Si(r) {
  return `${r}px`;
}
const ME = ["plane", "play", "pause", "stop"], Ii = new JM();
class wE {
  // ---------------------------------------------------------------------------
  // Constructor & Toolbar Setup
  // ---------------------------------------------------------------------------
  /**
   * Create Display.
   * @param container - the DOM element that should contain the Display
   * @param options - display options
   * @public
   */
  constructor(e, t) {
    this.setAxes = (s, a) => {
      this.viewer.setAxes(a);
    }, this.setGrid = (s, a) => {
      this.viewer.setGrid(s, a);
    }, this.setAxes0 = (s, a) => {
      this.viewer.setAxes0(a);
    }, this.setOrtho = (s, a) => {
      this.viewer.switchCamera(!a);
    }, this.setTransparent = (s, a) => {
      this.viewer.setTransparent(a);
    }, this.setBlackEdges = (s, a) => {
      this.viewer.setBlackEdges(a);
    }, this.setExplode = (s, a) => {
      this.viewer.setExplode(a);
    }, this.showExplode = (s) => {
      const a = this.getElement("tcv_explode_widget");
      a.style.display = s ? "inline-block" : "none";
    }, this.setZScale = (s, a) => {
      this.showZScale(a), this.viewer.nestedGroup.setZScale(1), this.viewer.update(!0), this.getInputElement("tcv_zscale_slider").value = "1";
    }, this.showZScale = (s) => {
      const a = this.getElement("tcv_cad_zscale");
      a.style.display = s ? "inline-block" : "none";
    }, this.setTool = (s, a) => {
      this.viewer.toggleAnimationLoop(a);
      const o = this.state.get("activeTool"), l = typeof o == "string" ? o : "";
      a ? (this.viewer.activateTool(s, !0), ["distance", "properties", "angle", "select"].includes(s) && !["distance", "properties", "angle", "select"].includes(l) && (this.viewer.toggleGroup(!0), this.viewer.toggleTab(!0)), this.viewer.setRaycastMode(a), this.shapeFilterDropDownMenu.setRaycaster(this.viewer.raycaster), s === "distance" ? (this.viewer.cadTools.enable(Kt.DISTANCE), this.viewer.checkChanges({ activeTool: Kt.DISTANCE })) : s === "properties" ? (this.viewer.cadTools.enable(Kt.PROPERTIES), this.viewer.checkChanges({ activeTool: Kt.PROPERTIES })) : s === "select" && (this.viewer.cadTools.enable(Kt.SELECT), this.viewer.checkChanges({ activeTool: Kt.SELECT }))) : ((l === s || s === "explode") && (this.viewer.toggleGroup(!1), this.viewer.toggleTab(!1)), s === "distance" ? this.viewer.cadTools.disable() : s === "properties" ? this.viewer.cadTools.disable() : s === "select" && this.viewer.cadTools.disable(), this.viewer.checkChanges({ activeTool: Kt.NONE }), this.viewer.clearSelection(), this.viewer.activateTool(s, !1), this.viewer.setRaycastMode(a)), this.viewer.setPickHandler(!a), this.shapeFilterDropDownMenu.show(a);
    }, this.showTools = (s) => {
      this.tools = s;
      const a = this.getElement("tcv_cad_toolbar"), o = this.getElement("tcv_cad_navigation");
      s ? (a.style.height = "38px", a.style.display = "flex", o.style.height = "38px", o.style.display = "block") : (a.style.height = "0px", a.style.display = "none", o.style.height = "0px", o.style.display = "none");
    }, this.showMeasureTools = (s) => {
      this.clickButtons.distance.show(s), this.clickButtons.properties.show(s);
    }, this.showSelectTool = (s) => {
      this.clickButtons.select.show(s);
    }, this.showExplodeTool = (s) => {
      this.clickButtons.explode.show(s);
    }, this.showZScaleTool = (s) => {
      this.clickButtons.zscale.show(s), s || this.showZScale(!1);
    }, this.setClipPlaneHelpers = (s) => {
      if (!(s.target instanceof HTMLInputElement))
        return;
      const a = s.target.checked;
      this.lastPlaneState = a, this.viewer.setClipPlaneHelpers(a);
    }, this.setClipIntersection = (s) => {
      s.target instanceof HTMLInputElement && this.viewer.setClipIntersection(s.target.checked);
    }, this.setObjectColorCaps = (s) => {
      s.target instanceof HTMLInputElement && this.viewer.setClipObjectColorCaps(s.target.checked);
    }, this.setClipNormalFromPosition = (s) => {
      if (!(s.target instanceof HTMLElement))
        return;
      const o = parseInt(s.target.classList[0].slice(-1)) - 1;
      Xp(o) && this.viewer.setClipNormalFromPosition(o);
    }, this.setNormalLabel = (s, a) => {
      this.planeLabels[s].innerHTML = `N=(${a[0].toFixed(2)}, ${a[1].toFixed(2)}, ${a[2].toFixed(2)})`;
    }, this.reset = () => {
      this.viewer.reset(), this.viewer.state.set("highlightedButton", null);
    }, this.resize = () => {
      this.viewer.resize();
    }, this.setView = (s, a = !1) => {
      this.viewer.presetCamera(s), a && this.viewer.centerVisibleObjects(), this.viewer.state.set("highlightedButton", s), this.viewer.keepHighlight = !0, this.viewer.update(!0, !1);
    }, this.pinAsPng = (s, a) => {
      this.viewer.pinAsPng();
    }, this.selectTab = (s) => {
      if (!(s.target instanceof HTMLElement))
        return;
      const o = s.target.className.split(" ")[0].slice(8);
      (o === "clip" || o === "tree" || o === "material" || o === "zebra") && this.viewer.setActiveTab(o);
    }, this.toggleClippingTab = (s) => {
      s ? this.tabClip.removeAttribute("disabled") : this.tabClip.setAttribute("disabled", "true"), this.tabClip.classList.toggle("tcv_tab-disabled", !s);
    }, this.handleCollapseNodes = (s) => {
      if (!(s.target instanceof HTMLInputElement))
        return;
      const a = s.target.value, l = {
        1: Jt.LEAVES,
        R: Jt.ROOT,
        C: Jt.COLLAPSED,
        E: Jt.EXPANDED
      }[a];
      l !== void 0 && this.viewer.collapseNodes(l);
    }, this.handleMaterialReset = (s) => {
      this.viewer.resetMaterial();
    }, this.setZebraCount = (s) => {
      this.zebraCountSlider.setValue(s);
    }, this.setZebraOpacity = (s) => {
      this.zebraOpacitySlider.setValue(s);
    }, this.setZebraDirection = (s) => {
      this.zebraDirectionSlider.setValue(s);
    }, this.setZebraColorScheme = (s) => {
      if (!(s.target instanceof HTMLInputElement))
        return;
      const a = s.target.value;
      (a === "blackwhite" || a === "colorful" || a === "grayscale") && (this.viewer.setZebraColorScheme(a), this.setZebraColorSchemeSelect(a));
    }, this.setZebraColorSchemeSelect = (s) => {
      const a = this.container.querySelector(`input[name="zebra_color_group"][value="${s}"]`);
      a instanceof HTMLInputElement && (a.checked = !0);
    }, this.setZebraMappingMode = (s) => {
      if (!(s.target instanceof HTMLInputElement))
        return;
      const a = s.target.value;
      (a === "reflection" || a === "normal") && (this.viewer.setZebraMappingMode(a), this.setZebraMappingModeSelect(a));
    }, this.setZebraMappingModeSelect = (s) => {
      const a = this.container.querySelector(`input[name="zebra_mapping_group"][value="${s}"]`);
      a instanceof HTMLInputElement && (a.checked = !0);
    }, this.refreshPlane = (s, a) => {
      const o = s - 1;
      Xp(o) && this.viewer.refreshPlane(o, parseFloat(a));
    }, this.controlAnimation = (s) => {
      if (!(s.target instanceof HTMLElement))
        return;
      const a = s.target.className.split(" ")[0].slice(4);
      this.controlAnimationByName(a);
    }, this.animationChange = (s) => {
      s.target instanceof HTMLInputElement && (this.viewer.setRelativeTime(s.target.valueAsNumber / 1e3), this.viewer.lastBbox != null && (this.viewer.lastBbox.needsUpdate = !0));
    }, this._handleKeyboardShortcut = (s) => {
      if (!(s instanceof KeyboardEvent) || s.ctrlKey || s.altKey || s.metaKey)
        return;
      const a = s.target;
      if (a instanceof HTMLInputElement && a.type !== "button" && a.type !== "checkbox" || a instanceof HTMLTextAreaElement || a instanceof HTMLSelectElement)
        return;
      const o = _t.getActionForKey(s.key);
      o && this._dispatchAction(o) !== "propagate" && (s.preventDefault(), s.stopPropagation());
    }, this.showHelp = (s) => {
      this.cadHelp.style.display = s ? "block" : "none", this.help_shown = s;
    }, this.toggleHelp = () => {
      this.showHelp(!this.help_shown);
    }, this.showDistancePanel = (s) => {
      this.distanceMeasurementPanel.style.display = s ? "block" : "none";
    }, this.showPropertiesPanel = (s) => {
      this.propertiesMeasurementPanel.style.display = s ? "block" : "none";
    }, this.showInfo = (s) => {
      var o;
      const a = (o = this.cadInfo.parentNode) == null ? void 0 : o.parentNode;
      a instanceof HTMLElement && (a.style.display = s ? "block" : "none"), this.getElement("tcv_toggle_info").innerHTML = s ? "▾" : "▸", this.info_shown = s;
    }, this.toggleInfo = () => {
      this.showInfo(!this.info_shown);
    }, this.container = e, this.container.setAttribute("tabindex", "0"), this.container.style.outline = "none", this.container.innerHTML = SE(this.container.id), this.cadBody = this.getElement("tcv_cad_body"), this.measureTools = t.measureTools, this.measurementDebug = t.measurementDebug, this.selectTool = t.selectTool, this.explodeTool = t.explodeTool, this.zscaleTool = t.zscaleTool, this.zScale = 1, this.cadTool = new vE(this.getElement("tcv_cad_toolbar"), e.id, {
      getVisibleWidth: () => this.glass ? this.cadWidth : this.cadWidth + this.treeWidth,
      getWidthThreshold: () => this._widthThreshold(),
      features: {
        measureTools: this.measureTools,
        selectTool: this.selectTool,
        explodeTool: this.explodeTool
      }
    }), this.cadView = this.getElement("tcv_cad_view"), this.distanceMeasurementPanel = this.getElement("tcv_distance_measurement_panel"), this.propertiesMeasurementPanel = this.getElement("tcv_properties_measurement_panel"), this.measurementPanels = {
      distancePanel: this.distanceMeasurementPanel,
      propertiesPanel: this.propertiesMeasurementPanel
    }, this.filterDropdown = {
      container: this.getElement("tcv_shape_filter"),
      dropdown: this.getElement("tcv_filter_dropdown"),
      icon: this.getElement("tcv_filter_icon"),
      value: this.getElement("tcv_filter_value"),
      content: this.getElement("tcv_filter_content"),
      options: {
        none: this.getElement("tvc_filter_none"),
        vertex: this.getElement("tvc_filter_vertex"),
        edge: this.getElement("tvc_filter_edge"),
        face: this.getElement("tvc_filter_face"),
        solid: this.getElement("tvc_filter_solid")
      }
    }, this.cadTree = this.getElement("tcv_cad_tree_container"), this.cadTreeScrollContainer = this.getElement("tcv_box_content"), this.cadTreeToggles = this.getElement("tcv_cad_tree_toggles"), this.cadClip = this.getElement("tcv_cad_clip_container"), this.cadMaterial = this.getElement("tcv_cad_material_container"), this.cadZebra = this.getElement("tcv_cad_zebra_container"), this.tabTree = this.getElement("tcv_tab_tree"), this.tabClip = this.getElement("tcv_tab_clip"), this.tabMaterial = this.getElement("tcv_tab_material"), this.tabZebra = this.getElement("tcv_tab_zebra"), this.cadInfo = this.getElement("tcv_cad_info_container"), this._info = new xE(this.cadInfo), this.tickValueElement = this.getElement("tcv_tick_size_value"), this.tickInfoElement = this.getElement("tcv_tick_size"), this.cadAnim = this.getElement("tcv_cad_animation"), this.cadTools = this.getElement("tcv_cad_tools"), t.zebraTool || (this.tabZebra.style.display = "none"), this.cadHelp = this.getElement("tcv_cad_help"), Ii.add(this.cadHelp, "contextmenu", (s) => (s.preventDefault(), s.stopPropagation(), !1)), this.planeLabels = [];
    for (let s = 1; s < 4; s++)
      this.planeLabels.push(this.getElement(`tcv_lbl_norm_plane${s}`));
    this.glass = t.glass, this.tools = t.tools, this.cadWidth = t.cadWidth, this.height = t.height, this.treeWidth = t.treeWidth, this._events = [], this._unsubscribers = [], this.setSizes(t), this.cadTree.style.display = "block", this.cadClip.style.display = "none", this.cadMaterial.style.display = "none", this.cadZebra.style.display = "none", this.clipSliders = null, this.lastPlaneState = !1, this.help_shown = !0, this.info_shown = !this.glass;
    const i = t.theme;
    if (this.theme = i, this.setButtonBackground(), this.clickButtons = {}, this.buttons = {}, this.clickButtons.axes = new ki(i, "axes", "Show axes", this.setAxes), this.cadTool.addButton(this.clickButtons.axes, -1), this.cadTool.addEllipsis(new ko(0, this.cadTool.maximize)), this.clickButtons.axes0 = new ki(i, "axes0", "Show axes at origin (0,0,0)", this.setAxes0), this.cadTool.addButton(this.clickButtons.axes0, 0), this.clickButtons.grid = new ki(i, "grid", "Show grid", this.setGrid, !1, ["xy", "xz", "yz"]), this.cadTool.addButton(this.clickButtons.grid, 0), this.cadTool.addSeparator(), this.clickButtons.perspective = new ki(i, "perspective", "Use perspective camera", this.setOrtho), this.cadTool.addButton(this.clickButtons.perspective, -1), this.cadTool.addEllipsis(new ko(1, this.cadTool.maximize)), this.clickButtons.transparent = new ki(i, "transparent", "Show transparent faces", this.setTransparent), this.cadTool.addButton(this.clickButtons.transparent, 1), this.clickButtons.blackedges = new ki(i, "blackedges", "Show black edges", this.setBlackEdges), this.cadTool.addButton(this.clickButtons.blackedges, 1), this.cadTool.addSeparator(), this.buttons.reset = new Bi(i, "reset", "Reset view", this.reset), this.cadTool.addButton(this.buttons.reset, -1), this.cadTool.addEllipsis(new ko(2, this.cadTool.maximize)), this.buttons.resize = new Bi(i, "resize", "Resize object", this.resize), this.cadTool.addButton(this.buttons.resize, 2), this.buttons.iso = new Bi(i, "iso", "Switch to iso view", this.setView), this.cadTool.addButton(this.buttons.iso, 2), this.buttons.front = new Bi(i, "front", "Switch to front view", this.setView), this.cadTool.addButton(this.buttons.front, 2), this.buttons.rear = new Bi(i, "rear", "Switch to back view", this.setView), this.cadTool.addButton(this.buttons.rear, 2), this.buttons.top = new Bi(i, "top", "Switch to top view", this.setView), this.cadTool.addButton(this.buttons.top, 2), this.buttons.bottom = new Bi(i, "bottom", "Switch to bottom view", this.setView), this.cadTool.addButton(this.buttons.bottom, 2), this.buttons.left = new Bi(i, "left", "Switch to left view", this.setView), this.cadTool.addButton(this.buttons.left, 2), this.buttons.right = new Bi(i, "right", "Switch to right view", this.setView), this.cadTool.addButton(this.buttons.right, 2), this.cadTool.addSeparator(), this.clickButtons.explode = new ki(i, "explode", "Explode tool", this.setExplode), this.explodeTool && !this.zscaleTool && this.cadTool.addButton(this.clickButtons.explode, -1), this.clickButtons.zscale = new ki(i, "zscale", "Scale along the Z-axis", this.setZScale), this.zscaleTool && !this.explodeTool) {
      this.cadTool.addButton(this.clickButtons.zscale, -1), this.showZScale(!1);
      const s = this.getInputElement("tcv_zscale_slider");
      Ii.add(s, "change", (a) => {
        a.target instanceof HTMLInputElement && (this.zScale = parseInt(a.target.value), this.viewer.setZscaleValue(parseInt(a.target.value)));
      });
    }
    this.clickButtons.distance = new ki(i, "distance", "Measure distance between shapes", this.setTool), this.cadTool.addButton(this.clickButtons.distance, 3), (this.measureTools ? 2 : 0) + (this.explodeTool ? 1 : 0) + (this.selectTool ? 1 : 0) + (this.zscaleTool ? 1 : 0) > 1 && this.cadTool.addEllipsis(new ko(3, this.cadTool.maximize)), this.clickButtons.properties = new ki(i, "properties", "Show shape properties", this.setTool), this.cadTool.addButton(this.clickButtons.properties, 3), this.clickButtons.select = new ki(i, "select", "Copy shape IDs to clipboard", this.setTool), this.cadTool.addButton(this.clickButtons.select, 3), this.cadTool.defineGroup([
      this.clickButtons.explode,
      this.clickButtons.distance,
      this.clickButtons.properties,
      this.clickButtons.select
    ]), Ii.add(document, "keydown", (s) => {
      s instanceof KeyboardEvent && s.key === "Escape" && this.help_shown && (s.preventDefault(), this.showHelp(!1));
    }), this.cadTool.addSeparator(), this.buttons.pin = new Bi(i, "pin", "Pin viewer as png", this.pinAsPng), this.buttons.pin.alignRight(), this.cadTool.addButton(this.buttons.pin, -1), this.shapeFilterDropDownMenu = new dE(this), this.showPinning(t.pinning), this.buttons.help = new Bi(i, "help", "Help", this.toggleHelp), this.cadTool.addButton(this.buttons.help, -1), this.animationSlider = null;
  }
  // ---------------------------------------------------------------------------
  // Private Helpers
  // ---------------------------------------------------------------------------
  setButtonBackground() {
    for (const e of ME) {
      const t = this.container.getElementsByClassName(`tcv_${e}`);
      for (let i = 0; i < t.length; i++)
        t[i].classList.add(`tcv_button_${e}`);
    }
  }
  /**
   * Calculate the width threshold for toolbar collapse.
   * @returns The threshold width in pixels.
   */
  _widthThreshold() {
    let e = 770;
    return this.state.get("pinning") || (e -= 30), this.state.get("selectTool") || (e -= 30), !this.state.get("explodeTool") && !this.state.get("zscaleTool") && (e -= 30), e;
  }
  /**
   * Update toolbar collapse state based on available width.
   * Maximizes toolbar if width is sufficient, minimizes otherwise.
   * @param availableWidth - The available width in pixels.
   */
  updateToolbarCollapse(e) {
    e >= this._widthThreshold() ? this.cadTool.maximize() : this.cadTool.minimize();
  }
  setupCheckEvent(e, t, i) {
    const n = this.getInputElement(e);
    Ii.add(n, "change", t), i !== void 0 && (n.checked = i), this._events.push(["change", e, t]);
  }
  setupClickEvent(e, t) {
    const i = this.getElement(e);
    Ii.add(i, "click", t), this._events.push(["click", e, t]);
  }
  setupRadioEvent(e, t) {
    const i = this.getElement(e);
    Ii.add(i, "change", t), this._events.push(["change", e, t]);
  }
  /**
   * Get a DOM element by class name (internal use only).
   * @param name - Name of the DOM element class
   * @returns The DOM element
   */
  getElement(e) {
    var i;
    const t = (i = this.container) == null ? void 0 : i.getElementsByClassName(e)[0];
    return t instanceof HTMLElement ? t : document.createElement("div");
  }
  /**
   * Get an input element by class name (internal use only).
   * @param name - Name of the DOM element class
   * @returns The input element
   */
  getInputElement(e) {
    var i;
    const t = (i = this.container) == null ? void 0 : i.getElementsByClassName(e)[0];
    return t instanceof HTMLInputElement ? t : document.createElement("input");
  }
  // ---------------------------------------------------------------------------
  // Disposal & UI Layout
  // ---------------------------------------------------------------------------
  /**
   * Dispose of all resources. Call when done with the viewer.
   *
   * Disposes:
   * - All state subscriptions
   * - Event listeners
   * - Toolbar and buttons
   * - Sliders
   * - DOM content
   *
   * After dispose(), the Display instance should not be used.
   *
   * @public
   */
  dispose() {
    var e, t, i, n, s, a, o;
    if (this._unsubscribers) {
      for (const l of this._unsubscribers)
        l();
      this._unsubscribers = [];
    }
    if (Ii.dispose(), this.cadTool.dispose(), this.clipSliders)
      for (const l of this.clipSliders)
        l.dispose();
    (e = this.ambientlightSlider) == null || e.dispose(), (t = this.directionallightSlider) == null || t.dispose(), (i = this.metalnessSlider) == null || i.dispose(), (n = this.roughnessSlider) == null || n.dispose(), (s = this.zebraCountSlider) == null || s.dispose(), (a = this.zebraOpacitySlider) == null || a.dispose(), (o = this.zebraDirectionSlider) == null || o.dispose(), this.cadTree.innerHTML = "", this.cadView.removeChild(this.cadView.children[2]), this.container.innerHTML = "";
  }
  // ---------------------------------------------------------------------------
  // Info Panel Methods
  // ---------------------------------------------------------------------------
  /**
   * Add HTML content to the info panel.
   * @param html - The HTML string to add.
   */
  addInfoHtml(e) {
    this._info.addHtml(e);
  }
  /**
   * Display the ready message with viewer version and control mode.
   * @param version - Viewer version string.
   * @param control - Control mode name (e.g., "orbit", "trackball").
   */
  showReadyMessage(e, t) {
    this._info.readyMsg(e, t);
  }
  /**
   * Display camera target center information.
   * @param center - The center coordinates [x, y, z].
   */
  showCenterInfo(e) {
    this._info.centerInfo(e);
  }
  /**
   * Display bounding box information for a selected object.
   * @param path - The object's path in the tree.
   * @param name - The object's name.
   * @param bb - The bounding box to display.
   */
  showBoundingBoxInfo(e, t, i) {
    this._info.bbInfo(e, t, i);
  }
  // ---------------------------------------------------------------------------
  // Canvas Capture
  // ---------------------------------------------------------------------------
  /**
   * Capture the canvas as a data URL.
   * @param options - Capture options.
   * @returns Promise resolving to task ID and data URL.
   */
  captureCanvas(e) {
    const { taskId: t, render: i, onComplete: n } = e, s = this.getCanvas();
    return s instanceof HTMLCanvasElement ? (i(), new Promise((a) => {
      s.toBlob((o) => {
        const l = new FileReader();
        l.addEventListener("load", () => {
          a({ task: t, dataUrl: l.result }), n && n();
        }, { once: !0 }), l.readAsDataURL(o);
      });
    })) : Promise.reject(new Error("Canvas element not found"));
  }
  /**
   * Set the width and height of the different UI elements (tree, canvas and info box).
   * @param options - Size options
   * @public
   */
  setSizes(e) {
    e.cadWidth && (this.cadWidth = e.cadWidth, this.cadView.style.width = Si(e.cadWidth)), e.height && (this.height = e.height, this.cadView.style.height = Si(e.height)), e.treeWidth && (this.treeWidth = e.treeWidth, this.cadTree.parentElement.parentElement.style.width = Si(e.treeWidth), this.cadInfo.parentElement.parentElement.style.width = Si(e.treeWidth)), !e.glass && e.treeHeight && (this.cadTree.parentElement.parentElement.style.height = Si(e.treeHeight), this.cadInfo.parentElement.parentElement.style.height = Si(this.height - e.treeHeight - 4)), e.tools && !e.glass ? (this.cadTool.container.style.width = Si(this.treeWidth + this.cadWidth + 4), this.cadBody.style.width = Si(this.treeWidth + this.cadWidth + 4)) : (this.cadTool.container.style.width = Si(this.cadWidth + 2), this.cadBody.style.width = Si(this.cadWidth + 2)), this.cadBody.style.height = Si(this.height + 4);
  }
  // ---------------------------------------------------------------------------
  // UI Setup & State Subscriptions
  // ---------------------------------------------------------------------------
  /**
   * Set up the UI and attach the canvas element.
   * Called by Viewer constructor, not intended for direct use.
   * @param viewer - The viewer instance for this UI.
   * @param canvasElement - The Three.js renderer canvas to attach.
   * @internal
   */
  setupUI(e, t) {
    this.viewer = e, this.state = e.state, this.attachCanvas(t), this.theme === "browser" && (this.mediaQuery = window.matchMedia("(prefers-color-scheme: dark)"), Ii.add(this.mediaQuery, "change", (a) => {
      a instanceof MediaQueryListEvent && a.matches ? this.setTheme("dark") : this.setTheme("light");
    })), this.setupClickEvent("tcv_expand_root", this.handleCollapseNodes), this.setupClickEvent("tcv_collapse_singles", this.handleCollapseNodes), this.setupClickEvent("tcv_collapse_all", this.handleCollapseNodes), this.setupClickEvent("tcv_expand", this.handleCollapseNodes), this.setupClickEvent("tcv_material_reset", this.handleMaterialReset), this.setupClickEvent("tcv_toggle_info", this.toggleInfo), this.help_shown = !0, this.info_shown = !this.glass, [
      "tcv_tab_tree",
      "tcv_tab_clip",
      "tcv_tab_material",
      "tcv_tab_zebra"
    ].forEach((a) => {
      this.setupClickEvent(a, this.selectTab);
    }), this.clipSliders = [];
    for (let a = 1; a < 4; a++)
      this.clipSliders.push(new Pn(`plane${a}`, 0, 100, this.container, {
        handler: this.refreshPlane,
        notifyCallback: (o, l) => this.viewer.checkChanges(o, l),
        onSetSlider: this.refreshPlane
      }));
    const n = () => this.viewer.ready;
    this.ambientlightSlider = new Pn("ambientlight", 0, 400, this.container, {
      handler: this.viewer.setAmbientLight,
      percentage: !0,
      isReadyCheck: n
    }), this.directionallightSlider = new Pn("pointlight", 0, 400, this.container, {
      handler: this.viewer.setDirectLight,
      percentage: !0,
      isReadyCheck: n
    }), this.metalnessSlider = new Pn("metalness", 0, 100, this.container, {
      handler: this.viewer.setMetalness,
      percentage: !0,
      isReadyCheck: n
    }), this.roughnessSlider = new Pn("roughness", 0, 100, this.container, {
      handler: this.viewer.setRoughness,
      percentage: !0,
      isReadyCheck: n
    }), this.zebraCountSlider = new Pn("zebra_count", 2, 50, this.container, {
      handler: this.viewer.setZebraCount,
      isReadyCheck: n
    }), this.zebraOpacitySlider = new Pn("zebra_opacity", 0, 1, this.container, {
      handler: this.viewer.setZebraOpacity,
      isReadyCheck: n
    }), this.zebraDirectionSlider = new Pn("zebra_direction", 0, 90, this.container, {
      handler: this.viewer.setZebraDirection,
      isReadyCheck: n
    }), this.getInputElement("tcv_zebra_color1").checked = !0, this.getInputElement("tcv_zebra_mapping1").checked = !0, this.setupCheckEvent("tcv_clip_plane_helpers", this.setClipPlaneHelpers, !1), this.setupCheckEvent("tcv_clip_intersection", this.setClipIntersection, !1), this.setupCheckEvent("tcv_clip_caps", this.setObjectColorCaps, !1);
    for (let a = 1; a < 4; a++)
      this.setupClickEvent(`tcv_btn_norm_plane${a}`, this.setClipNormalFromPosition);
    [1, 2, 3].forEach((a) => {
      this.setupRadioEvent(`tcv_zebra_color${a}`, this.setZebraColorScheme);
    }), [1, 2].forEach((a) => {
      this.setupRadioEvent(`tcv_zebra_mapping${a}`, this.setZebraMappingMode);
    }), this.setupClickEvent("tcv_play", this.controlAnimation), this.setupClickEvent("tcv_pause", this.controlAnimation), this.setupClickEvent("tcv_stop", this.controlAnimation);
    const s = this.container.getElementsByClassName("tcv_animation_slider")[0];
    this.animationSlider = s instanceof HTMLInputElement ? s : null, this.animationSlider && Ii.add(this.animationSlider, "input", this.animationChange), this.showHelp(!1), this.showDistancePanel(!1), this.showPropertiesPanel(!1), this.showMeasureTools(this.measureTools), this.showSelectTool(this.selectTool), this.showExplodeTool(this.explodeTool), this.showZScaleTool(this.zscaleTool), this.subscribeToStateChanges(), Ii.add(this.container, "mousedown", () => this.container.focus()), Ii.add(this.container, "keydown", this._handleKeyboardShortcut);
  }
  /**
   * Subscribe to ViewerState changes to keep UI in sync.
   * Stores unsubscribe functions for cleanup in dispose().
   * @internal
   */
  subscribeToStateChanges() {
    const e = this.viewer.state;
    this._unsubscribers = [];
    const t = (i, n, s) => {
      this._unsubscribers.push(e.subscribe(i, n, s));
    };
    t("axes", (i) => {
      var n;
      (n = this.clickButtons.axes) == null || n.set(i.new);
    }), t("axes0", (i) => {
      var n;
      (n = this.clickButtons.axes0) == null || n.set(i.new);
    }), t("ortho", (i) => {
      var n;
      (n = this.clickButtons.perspective) == null || n.set(!i.new);
    }), t("transparent", (i) => {
      var n;
      (n = this.clickButtons.transparent) == null || n.set(i.new);
    }), t("blackEdges", (i) => {
      var n;
      (n = this.clickButtons.blackedges) == null || n.set(i.new);
    }), t("grid", (i) => {
      const n = this.clickButtons.grid;
      if (n) {
        const s = i.new;
        n.set(s.some((a) => a)), n.checkElems && (n.checkElems.xy.checked = s[0], n.checkElems.xz.checked = s[1], n.checkElems.yz.checked = s[2]);
      }
    }, { immediate: !0 }), t("tools", (i) => {
      this.showTools(i.new);
    }), t("glass", (i) => {
      this.glassMode(i.new);
    }), t("theme", (i) => {
      this.setTheme(i.new);
    }), t("clipIntersection", (i) => {
      this.getInputElement("tcv_clip_intersection").checked = i.new;
    }), t("clipPlaneHelpers", (i) => {
      this.checkElement("tcv_clip_plane_helpers", i.new);
    }, { immediate: !0 }), t("clipObjectColors", (i) => {
      this.getInputElement("tcv_clip_caps").checked = i.new;
    }), t("clipSlider0", (i) => {
      var n, s;
      i.new !== -1 && ((s = (n = this.clipSliders) == null ? void 0 : n[0]) == null || s.setValueFromState(i.new));
    }), t("clipSlider1", (i) => {
      var n, s;
      i.new !== -1 && ((s = (n = this.clipSliders) == null ? void 0 : n[1]) == null || s.setValueFromState(i.new));
    }), t("clipSlider2", (i) => {
      var n, s;
      i.new !== -1 && ((s = (n = this.clipSliders) == null ? void 0 : n[2]) == null || s.setValueFromState(i.new));
    }), t("ambientIntensity", (i) => {
      var n;
      (n = this.ambientlightSlider) == null || n.setValueFromState(i.new * 100);
    }, { immediate: !0 }), t("directIntensity", (i) => {
      var n;
      (n = this.directionallightSlider) == null || n.setValueFromState(i.new * 100);
    }, { immediate: !0 }), t("metalness", (i) => {
      var n;
      (n = this.metalnessSlider) == null || n.setValueFromState(i.new * 100);
    }, { immediate: !0 }), t("roughness", (i) => {
      var n;
      (n = this.roughnessSlider) == null || n.setValueFromState(i.new * 100);
    }, { immediate: !0 }), t("zebraCount", (i) => {
      var n;
      (n = this.zebraCountSlider) == null || n.setValueFromState(i.new);
    }), t("zebraOpacity", (i) => {
      var n;
      (n = this.zebraOpacitySlider) == null || n.setValueFromState(i.new);
    }), t("zebraDirection", (i) => {
      var n;
      (n = this.zebraDirectionSlider) == null || n.setValueFromState(i.new);
    }), t("zebraColorScheme", (i) => {
      this.setZebraColorSchemeSelect(i.new);
    }), t("zebraMappingMode", (i) => {
      this.setZebraMappingModeSelect(i.new);
    }), t("animationMode", (i) => {
      var s;
      const n = i.new;
      this.cadAnim.style.display = n !== "none" ? "block" : "none", this.getElement("tcv_animation_label").innerHTML = n === "explode" ? "E" : "A", (s = this.clickButtons.explode) == null || s.set(n === "explode");
    }, { immediate: !0 }), t("animationSliderValue", (i) => {
      this.animationSlider && (this.animationSlider.value = String(i.new));
    }, { immediate: !0 }), t("zscaleActive", (i) => {
      var n;
      (n = this.clickButtons.zscale) == null || n.set(i.new);
    }), t("highlightedButton", (i) => {
      var s;
      [
        "front",
        "rear",
        "top",
        "bottom",
        "left",
        "right",
        "iso"
      ].forEach((a) => {
        var o;
        (o = this.buttons[a]) == null || o.highlight(!1);
      }), i.new && i.new in this.buttons && ((s = this.buttons[i.new]) == null || s.highlight(!0));
    }), t("activeTool", (i) => {
      var n, s;
      i.old && i.old in this.clickButtons && ((n = this.clickButtons[i.old]) == null || n.set(!1)), i.new && i.new in this.clickButtons && ((s = this.clickButtons[i.new]) == null || s.set(!0));
    }), t("activeTab", (i) => {
      this.switchToTab(i.new, i.old ?? void 0);
    });
  }
  /**
   * Initialize UI elements from current state.
   * Called once during initialization. Subsequent updates happen via state subscriptions.
   * @internal
   */
  updateUI() {
    const e = this.viewer.state, t = e.get("axes"), i = e.get("axes0"), n = e.get("ortho"), s = e.get("transparent"), a = e.get("blackEdges"), o = e.get("tools"), l = e.get("glass"), c = e.get("clipPlaneHelpers");
    typeof t == "boolean" && this.clickButtons.axes.set(t), typeof i == "boolean" && this.clickButtons.axes0.set(i), typeof n == "boolean" && this.clickButtons.perspective.set(!n), typeof s == "boolean" && this.clickButtons.transparent.set(s), typeof a == "boolean" && this.clickButtons.blackedges.set(a), typeof o == "boolean" && this.showTools(o), typeof l == "boolean" && this.glassMode(l);
    const h = this.glass ? this.cadWidth : this.cadWidth + this.treeWidth;
    this.updateToolbarCollapse(h), this.lastPlaneState = typeof c == "boolean" ? c : !1, this.syncMaterialSlidersFromState(), this.syncZebraSlidersFromState();
  }
  // ---------------------------------------------------------------------------
  // DOM Management
  // ---------------------------------------------------------------------------
  /**
   * Check or uncheck a checkbox
   * @param name - name of the check box, see getElement
   * @param flag - whether to check or uncheck
   */
  checkElement(e, t) {
    this.getInputElement(e).checked = t;
  }
  /**
   * Attach the canvas element to the CAD view container.
   * @param canvasElement - The canvas to attach.
   */
  attachCanvas(e) {
    const t = this.cadView.querySelector("canvas");
    t ? this.cadView.replaceChild(e, t) : this.cadView.appendChild(e), Ii.add(e, "click", () => {
      this.help_shown && this.showHelp(!1);
    });
  }
  /**
   * Get the DOM canvas element
   */
  getCanvas() {
    return this.cadView.children[this.cadView.children.length - 1];
  }
  /**
   * Clear the Cad tree
   */
  clearCadTree() {
    this.cadTree.innerHTML = "";
  }
  /**
   * Add the Cad tree and other UI elements like Clipping
   * @param cadTree - the DOM element that contains the cadTree
   */
  addCadTree(e) {
    this.cadTree.appendChild(e);
  }
  /**
   * Show/hide pinning button
   */
  showPinning(e) {
    this.buttons.pin.show(e);
  }
  /**
   * Switch to a tab (internal, called by activeTab subscription).
   */
  switchToTab(e, t) {
    var n;
    if (!["clip", "tree", "material", "zebra"].includes(e))
      return;
    const i = (s, a, o, l) => {
      this.cadTree.style.display = s ? "block" : "none", this.cadTreeToggles.style.display = s ? "block" : "none", this.cadClip.style.display = a ? "block" : "none", this.cadMaterial.style.display = o ? "block" : "none", this.cadZebra.style.display = l ? "block" : "none", this.viewer.clipping.setVisible(a), this.viewer.setLocalClipping(a), a || this.viewer.setClipPlaneHelpers(!1), e !== "zebra" && t === "zebra" && this.viewer.enableZebraTool(!1);
    };
    if (e === "tree")
      i(!0, !1, !1, !1), this.viewer.nestedGroup.setBackVisible(!1), (n = this.viewer.treeview) == null || n.update();
    else if (e === "clip") {
      i(!1, !0, !1, !1), this.viewer.nestedGroup.setBackVisible(!0);
      const s = this.viewer.state.get("clipIntersection");
      typeof s == "boolean" && this.viewer.setClipIntersection(s), this.viewer.setClipPlaneHelpers(this.lastPlaneState), this.viewer.update(!0, !1);
    } else e === "material" ? (i(!1, !1, !0, !1), this.viewer.nestedGroup.setBackVisible(!1)) : e === "zebra" && (i(!1, !1, !1, !0), this.viewer.enableZebraTool(!0));
    [this.tabTree, this.tabClip, this.tabMaterial, this.tabZebra].forEach((s) => {
      s.classList.add("tcv_tab-unselected"), s.classList.remove("tcv_tab-selected");
    }), this.viewer.checkChanges({ tab: e }), e === "tree" ? (this.tabTree.classList.add("tcv_tab-selected"), this.tabTree.classList.remove("tcv_tab-unselected")) : e === "clip" ? (this.tabClip.classList.add("tcv_tab-selected"), this.tabClip.classList.remove("tcv_tab-unselected")) : e === "material" ? (this.tabMaterial.classList.add("tcv_tab-selected"), this.tabMaterial.classList.remove("tcv_tab-unselected")) : e === "zebra" && (this.tabZebra.classList.remove("tcv_tab-unselected"), this.tabZebra.classList.add("tcv_tab-selected"));
  }
  // ---------------------------------------------------------------------------
  // Slider & Animation Control
  // ---------------------------------------------------------------------------
  /**
   * Set minimum and maximum of the clipping sliders
   */
  setSliderLimits(e) {
    for (let t = 0; t < 3; t++)
      this.clipSliders[t].setLimits(e);
  }
  /**
   * Sync clip slider UI from current state values.
   * Called after setSliderLimits to apply initial values with correct limits.
   */
  syncClipSlidersFromState() {
    const e = this.viewer.state, t = [
      e.get("clipSlider0"),
      e.get("clipSlider1"),
      e.get("clipSlider2")
    ];
    for (let i = 0; i < 3; i++)
      t[i] !== -1 && this.clipSliders[i].setValueFromState(t[i]);
  }
  /**
   * Sync material slider UI from current state values.
   * Called from updateUI after render options are applied to state.
   * State stores values in 0-1 range, sliders display 0-100 (or 0-400 for lights).
   */
  syncMaterialSlidersFromState() {
    var t, i, n, s;
    const e = this.viewer.state;
    (t = this.ambientlightSlider) == null || t.setValueFromState(e.get("ambientIntensity") * 100), (i = this.directionallightSlider) == null || i.setValueFromState(e.get("directIntensity") * 100), (n = this.metalnessSlider) == null || n.setValueFromState(e.get("metalness") * 100), (s = this.roughnessSlider) == null || s.setValueFromState(e.get("roughness") * 100);
  }
  /**
   * Sync zebra slider UI from current state values.
   * Called from updateUI after viewer options are applied to state.
   */
  syncZebraSlidersFromState() {
    var t, i, n;
    const e = this.viewer.state;
    (t = this.zebraCountSlider) == null || t.setValueFromState(e.get("zebraCount")), (i = this.zebraOpacitySlider) == null || i.setValueFromState(e.get("zebraOpacity")), (n = this.zebraDirectionSlider) == null || n.setValueFromState(e.get("zebraDirection")), this.setZebraColorSchemeSelect(e.get("zebraColorScheme")), this.setZebraMappingModeSelect(e.get("zebraMappingMode"));
  }
  /**
   * Handle animation control by button name
   */
  controlAnimationByName(e) {
    this.viewer.controlAnimation(e);
    const t = this.viewer.animation.getRelativeTime();
    this.viewer.state.set("animationSliderValue", 1e3 * t), e == "play" ? this.viewer.bboxNeedsUpdate = !0 : e == "stop" ? (this.viewer.bboxNeedsUpdate = !1, this.viewer.lastBbox != null && (this.viewer.lastBbox.needsUpdate = !0)) : this.viewer.bboxNeedsUpdate = !this.viewer.bboxNeedsUpdate;
  }
  /**
   * Dispatch a keyboard shortcut action.
   * Returns "propagate" if the event should not be suppressed.
   */
  _dispatchAction(e) {
    if ([
      "axes",
      "axes0",
      "grid",
      "perspective",
      "transparent",
      "blackedges",
      "explode",
      "zscale",
      "distance",
      "properties",
      "select"
    ].includes(e)) {
      this._toggleClickButton(e);
      return;
    }
    if (e === "gridxy") {
      const i = this.state.get("grid"), n = i[0] && !i[1] && !i[2];
      this.viewer.setGrid("grid", !1), n || this.viewer.setGrid("grid-xy", !0);
      return;
    }
    switch (e) {
      case "reset":
        this.reset();
        return;
      case "resize":
        this.resize();
        return;
      case "iso":
      case "front":
      case "rear":
      case "top":
      case "bottom":
      case "left":
      case "right":
        this.setView(e);
        return;
      case "help":
        this.toggleHelp();
        return;
      case "play": {
        const i = this.state.get("animationMode");
        if (i === "animation" || i === "explode") {
          const n = this.viewer.clipAction;
          n && n.isRunning() ? this.controlAnimationByName("pause") : this.controlAnimationByName("play");
        }
        return;
      }
      case "stop": {
        if (this.help_shown) {
          this.showHelp(!1), this.container.focus();
          return;
        }
        if (this.state.get("activeTool"))
          return "propagate";
        const i = this.state.get("animationMode");
        (i === "explode" || i === "animation") && this.controlAnimationByName("stop");
        return;
      }
      case "tree":
      case "clip":
      case "material":
      case "zebra":
        this.viewer.setActiveTab(e);
        return;
    }
  }
  /**
   * Programmatically toggle a ClickButton by name.
   */
  _toggleClickButton(e) {
    const t = this.clickButtons[e];
    t && t.html.style.display !== "none" && (t.state || t.clearGroup(), t.set(!t.state), t.action(t.name, t.state));
  }
  /**
   * Update tooltips with keyboard shortcut suffixes.
   */
  updateTooltips() {
    var i;
    const e = _t.getActionShortcuts();
    for (const [n, s] of Object.entries(e)) {
      const a = this.clickButtons[n] || this.buttons[n];
      if (a) {
        const o = a.html.getAttribute("data-base-tooltip");
        o && a.html.setAttribute("data-tooltip", `${o} › ${s}`);
      }
    }
    const t = {
      tree: { el: this.tabTree, label: "Navigation Tree" },
      clip: { el: this.tabClip, label: "Clipping Tool" },
      material: { el: this.tabMaterial, label: "Material Selection" },
      zebra: { el: this.tabZebra, label: "Zebra Tool" }
    };
    for (const [n, s] of Object.entries(e)) {
      const a = t[n];
      (i = a == null ? void 0 : a.el) != null && i.parentElement && a.el.parentElement.setAttribute("data-tooltip", `${a.label} › ${s}`);
    }
  }
  /**
   * Replace container content with a static image
   */
  replaceWithImage(e) {
    for (; this.container.firstChild; )
      this.container.removeChild(this.container.firstChild);
    this.container.appendChild(e);
  }
  // ---------------------------------------------------------------------------
  // Theme & Glass Mode
  // ---------------------------------------------------------------------------
  /**
   * Auto collapse tree nodes when cad width < 600
   */
  autoCollapse() {
    this.cadWidth < 600 && this.glass && (console.info("Small view, collapsing tree"), this.viewer.collapseNodes(Jt.COLLAPSED));
  }
  /**
   * Enable/disable glass mode (UI update only).
   */
  glassMode(e) {
    var a;
    const t = (a = this.state) == null ? void 0 : a.get("treeHeight"), i = typeof t == "number" ? t : Math.round(this.height * 2 / 3), n = this.getElement("tcv_cad_tree");
    e ? (n.classList.add("tcv_cad_tree_glass"), n.style.height = "", n.style.maxHeight = Si(i - 18), this.getElement("tcv_cad_info").classList.add("tcv_cad_info_glass"), this.getElement("tcv_cad_view").classList.add("tcv_cad_view_glass"), this.getElement("tcv_toggle_info_wrapper").style.display = "block", this.showInfo(!1), this.glass = !0, this.autoCollapse()) : (n.classList.remove("tcv_cad_tree_glass"), n.style.maxHeight = "", n.style.height = Si(i), this.getElement("tcv_cad_info").classList.remove("tcv_cad_info_glass"), this.getElement("tcv_cad_view").classList.remove("tcv_cad_view_glass"), this.getElement("tcv_toggle_info_wrapper").style.display = "none", this.showInfo(!0), this.glass = !1);
    const s = {
      cadWidth: this.cadWidth,
      glass: this.glass,
      height: this.height,
      treeHeight: i,
      tools: this.tools,
      treeWidth: e ? 0 : this.treeWidth
    };
    this.setSizes(s);
  }
  /**
   * Update help dialog with new key mappings
   */
  updateHelp(e, t) {
    const i = this.getElement("tcv_cad_help_layout"), n = Object.keys(e);
    for (const s of n)
      e[s] && t[s] && (i.innerHTML = i.innerHTML.replaceAll("&lt;" + e[s].slice(0, -3) + "&gt;", "&lt;_" + t[s].slice(0, -3) + "&gt;"));
    i.innerHTML = i.innerHTML.replaceAll("_shift", "shift"), i.innerHTML = i.innerHTML.replaceAll("_ctrl", "ctrl"), i.innerHTML = i.innerHTML.replaceAll("_alt", "alt"), i.innerHTML = i.innerHTML.replaceAll("_meta", "meta");
  }
  /**
   * Set the UI theme.
   * @param theme - "light", "dark", or "browser" for auto-detection
   * @returns The resolved theme ("light" or "dark")
   * @public
   */
  setTheme(e) {
    return e === "dark" || e === "browser" && window.matchMedia("(prefers-color-scheme: dark)").matches ? (this.container.setAttribute("data-theme", "dark"), document.body.setAttribute("data-theme", "dark"), this.viewer.ready && (this.viewer.orientationMarker.changeTheme("dark"), this.viewer.gridHelper.clearCache(), this.viewer.gridHelper.update(this.viewer.getCameraZoom(), !0, "dark")), this.viewer.update(!0), "dark") : (this.container.setAttribute("data-theme", "light"), document.body.setAttribute("data-theme", "light"), this.viewer.ready && (this.viewer.orientationMarker.changeTheme("light"), this.viewer.gridHelper.clearCache(), this.viewer.gridHelper.update(this.viewer.getCameraZoom(), !0, "light")), this.viewer.update(!0), "light");
  }
}
const ir = 200, gf = 12, _f = 400, EE = 800, TE = 100, AE = 3355443, CE = {
  ambientIntensity: 1,
  directIntensity: 1.1,
  metalness: 0.3,
  roughness: 0.65,
  edgeColor: AE,
  defaultOpacity: 0.5,
  normalLen: 0
}, Yh = {
  EXPAND_ALL: 2
  // Show all nodes expanded
}, yf = {
  up: "Z",
  axes: !0,
  axes0: !0,
  grid: [!0, !1, !1],
  ortho: !0,
  transparent: !1,
  blackEdges: !0,
  collapse: Yh.EXPAND_ALL
}, RE = {
  theme: "browser",
  pinning: !1
};
function PE({ model: r, el: e }) {
  const t = r.get("width") || "100%", i = r.get("height") || 600, n = typeof t == "number" ? `${t}px` : t, s = document.createElement("div");
  s.className = "marimo-cad-container", s.style.width = n, s.style.height = i + "px", e.appendChild(s);
  let a = null, o = null, l = null, c = !1, h = /* @__PURE__ */ new Set(), d = "/Group";
  function u() {
    if (c) return;
    const f = s.getBoundingClientRect().width, v = f > 0 ? Math.floor(f) : EE, x = Math.max(v - ir - gf, _f);
    a = new wE(s, {
      ...RE,
      cadWidth: x,
      height: i,
      treeWidth: ir
    }), o = new yE(a, yf, (y) => {
      y.type === "select" && (r.set("selected", y.data), r.save_changes());
    }), c = !0, r.send({ type: "ready" }), m(), requestAnimationFrame(() => {
      if (o.ready)
        try {
          o.resizeCadView(x, ir, i, !1);
        } catch (y) {
          console.warn("[marimo-cad] Initial resize failed:", y.message);
        }
    });
  }
  function p(f) {
    if (!o.ready || !(f != null && f.parts)) return !1;
    const v = f.id || d, x = new Set(f.parts.map((y) => y.name));
    for (const y of h)
      if (!x.has(y))
        try {
          o.removePart(`${v}/${y}`, { skipBounds: !0 });
        } catch {
        }
    for (const y of f.parts) {
      const A = `${v}/${y.name}`;
      try {
        h.has(y.name) && o.removePart(A, { skipBounds: !0 }), o.addPart(v, y, { skipBounds: !0 });
      } catch (S) {
        console.warn(`[marimo-cad] Failed to sync part ${y.name}:`, S.message);
      }
    }
    return o.updateBounds(), h = x, d = v, o.collapseNodes(Yh.EXPAND_ALL), !0;
  }
  function m() {
    var v;
    if (!o) return;
    const f = r.get("shapes_data");
    if ((v = f == null ? void 0 : f.parts) != null && v.length && !(o.ready && p(f))) {
      o.render(f, CE, yf), h.clear(), d = f.id || "/Group";
      for (const x of f.parts)
        h.add(x.name);
      o.collapseNodes(Yh.EXPAND_ALL);
    }
  }
  r.on("change:shapes_data", m);
  function _(f) {
    if (!a || !(o != null && o.ready)) return;
    const v = Math.max(Math.floor(f) - ir - gf, _f);
    try {
      a.setSizes({ cadWidth: v, height: i, treeWidth: ir }), o.resizeCadView(v, ir, i, !1);
    } catch (x) {
      console.warn("[marimo-cad] Resize failed:", x.message);
    }
  }
  const g = new ResizeObserver((f) => {
    const v = f[0].contentRect.width;
    v > 0 && (c ? (l && clearTimeout(l), l = setTimeout(() => _(v), TE)) : u());
  });
  return g.observe(s), requestAnimationFrame(() => {
    c || u();
  }), () => {
    if (g.disconnect(), l && clearTimeout(l), o)
      try {
        o.dispose();
      } catch {
      }
    s.innerHTML = "";
  };
}
const kE = { render: PE };
export {
  kE as default,
  PE as render
};
