import { BufferGeometry as J, Mesh as q, Box3 as ge, Vector3 as A, Sphere as Oe, CompressedTexture as Ge, Texture as E, Matrix3 as Fe, InterleavedBuffer as We, InterleavedBufferAttribute as Ue, BufferAttribute as ze, TextureLoader as Ee, Matrix4 as _e, Clock as Ne, MeshStandardMaterial as qe } from "./three-MHVqtJYj.js";
import { DRACOLoader as Ve, KTX2Loader as Xe, MeshoptDecoder as je, GLTFLoader as xe } from "./three-examples-C5Ht-QFN.js";
const Ke = "";
globalThis.GLTF_PROGRESSIVE_VERSION = Ke;
console.debug("[gltf-progressive] version -");
let C = "https://www.gstatic.com/draco/versioned/decoders/1.5.7/", V = "https://cdn.needle.tools/static/three/0.179.1/basis2/";
const Ye = C, He = V, Se = new URL(C + "draco_decoder.js");
Se.searchParams.append("range", "true");
fetch(Se, {
  method: "GET",
  headers: {
    Range: "bytes=0-1"
  }
}).catch((i) => {
  console.debug(`Failed to fetch remote Draco decoder from ${C} (offline: ${typeof navigator < "u" ? navigator.onLine : "unknown"})`), C === Ye && Je("./include/draco/"), V === He && Ze("./include/ktx2/");
}).finally(() => {
  Pe();
});
const Qe = () => ({
  dracoDecoderPath: C,
  ktx2TranscoderPath: V
});
function Je(i) {
  C = i, P && P[pe] != C ? (console.debug("Updating Draco decoder path to " + i), P[pe] = C, P.setDecoderPath(C), P.preload()) : console.debug("Setting Draco decoder path to " + i);
}
function Ze(i) {
  V = i, R && R.transcoderPath != V ? (console.debug("Updating KTX2 transcoder path to " + i), R.setTranscoderPath(V), R.init()) : console.debug("Setting KTX2 transcoder path to " + i);
}
function we(i) {
  return Pe(), i ? R.detectSupport(i) : i !== null && console.warn("No renderer provided to detect ktx2 support - loading KTX2 textures might fail"), { dracoLoader: P, ktx2Loader: R, meshoptDecoder: ne };
}
function Te(i) {
  i.dracoLoader || i.setDRACOLoader(P), i.ktx2Loader || i.setKTX2Loader(R), i.meshoptDecoder || i.setMeshoptDecoder(ne);
}
const pe = Symbol("dracoDecoderPath");
let P, ne, R;
function Pe() {
  P || (P = new Ve(), P[pe] = C, P.setDecoderPath(C), P.setDecoderConfig({ type: "js" }), P.preload()), R || (R = new Xe(), R.setTranscoderPath(V), R.init()), ne || (ne = je);
}
const me = /* @__PURE__ */ new WeakMap();
function Ae(i, t) {
  let e = me.get(i);
  e ? e = Object.assign(e, t) : e = t, me.set(i, e);
}
const et = xe.prototype.load;
function tt(...i) {
  const t = me.get(this);
  let e = i[0];
  const s = new URL(e, window.location.href);
  if (s.hostname.endsWith("needle.tools")) {
    const r = t?.progressive !== void 0 ? t.progressive : !0, o = t?.usecase ? t.usecase : "default";
    r ? this.requestHeader.Accept = `*/*;progressive=allowed;usecase=${o}` : this.requestHeader.Accept = `*/*;usecase=${o}`, e = s.toString();
  }
  return i[0] = e, et?.call(this, ...i);
}
xe.prototype.load = tt;
X("debugprogressive");
function X(i) {
  if (typeof window > "u") return !1;
  const e = new URL(window.location.href).searchParams.get(i);
  return e == null || e === "0" || e === "false" ? !1 : e === "" ? !0 : e;
}
function st(i, t) {
  if (t === void 0 || i === void 0 || t.startsWith("./") || t.startsWith("http") || t.startsWith("data:") || t.startsWith("blob:"))
    return t;
  const e = i.lastIndexOf("/");
  if (e >= 0) {
    const s = i.substring(0, e + 1);
    for (; s.endsWith("/") && t.startsWith("/"); ) t = t.substring(1);
    return s + t;
  }
  return t;
}
function Ie() {
  return K !== void 0 || (K = /iPhone|iPad|iPod|Android|IEMobile/i.test(navigator.userAgent), X("debugprogressive") && console.log("[glTF Progressive]: isMobileDevice", K)), K;
}
let K;
function Me() {
  if (typeof window > "u") return !1;
  const i = new URL(window.location.href), t = i.hostname === "localhost" || /^\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}$/.test(i.hostname);
  return i.hostname === "127.0.0.1" || t;
}
class rt {
  constructor(t = 100, e = {}) {
    this.maxConcurrent = t, this.debug = e.debug ?? !1, window.requestAnimationFrame(this.tick);
  }
  _running = /* @__PURE__ */ new Map();
  _queue = [];
  debug = !1;
  tick = () => {
    this.internalUpdate(), setTimeout(this.tick, 10);
  };
  /**
   * Request a slot for a promise with a specific key. This function returns a promise with a `use` method that can be called to add the promise to the queue.
   */
  slot(t) {
    return this.debug && console.debug(`[PromiseQueue]: Requesting slot for key ${t}, running: ${this._running.size}, waiting: ${this._queue.length}`), new Promise((e) => {
      this._queue.push({ key: t, resolve: e });
    });
  }
  add(t, e) {
    this._running.has(t) || (this._running.set(t, e), e.finally(() => {
      this._running.delete(t), this.debug && console.debug(`[PromiseQueue]: Promise finished now running: ${this._running.size}, waiting: ${this._queue.length}. (finished ${t})`);
    }), this.debug && console.debug(`[PromiseQueue]: Added new promise, now running: ${this._running.size}, waiting: ${this._queue.length}. (added ${t})`));
  }
  internalUpdate() {
    const t = this.maxConcurrent - this._running.size;
    for (let e = 0; e < t && this._queue.length > 0; e++) {
      this.debug && console.debug(`[PromiseQueue]: Running ${this._running.size} promises, waiting for ${this._queue.length} more.`);
      const { key: s, resolve: n } = this._queue.shift();
      n({
        use: (r) => this.add(s, r)
      });
    }
  }
}
const nt = typeof window > "u" && typeof document > "u", ye = Symbol("needle:raycast-mesh");
function Z(i) {
  return i?.[ye] instanceof J ? i[ye] : null;
}
function ot(i, t) {
  if ((i.type === "Mesh" || i.type === "SkinnedMesh") && !Z(i)) {
    const s = at(t);
    s.userData = { isRaycastMesh: !0 }, i[ye] = s;
  }
}
function it(i = !0) {
  if (i) {
    if (Y) return;
    const t = Y = q.prototype.raycast;
    q.prototype.raycast = function(e, s) {
      const n = this, r = Z(n);
      let o;
      r && n.isMesh && (o = n.geometry, n.geometry = r), t.call(this, e, s), o && (n.geometry = o);
    };
  } else {
    if (!Y) return;
    q.prototype.raycast = Y, Y = null;
  }
}
let Y = null;
function at(i) {
  const t = new J();
  for (const e in i.attributes)
    t.setAttribute(e, i.getAttribute(e));
  return t.setIndex(i.getIndex()), t;
}
const U = new Array(), g = X("debugprogressive");
let Q, N = -1;
if (g) {
  let i = function() {
    N += 1, N >= t && (N = -1), console.log(`Toggle LOD level [${N}]`);
  }, t = 6;
  window.addEventListener("keyup", (e) => {
    e.key === "p" && i(), e.key === "w" && (Q = !Q, console.log(`Toggle wireframe [${Q}]`));
    const s = parseInt(e.key);
    !isNaN(s) && s >= 0 && (N = s, console.log(`Set LOD level to [${N}]`));
  });
}
function ke(i) {
  if (g && Q !== void 0)
    if (Array.isArray(i))
      for (const t of i)
        ke(t);
    else i && "wireframe" in i && (i.wireframe = Q === !0);
}
const H = new Array();
let lt = 0;
const ut = Ie() ? 2 : 10;
function dt(i) {
  if (H.length < ut) {
    const s = H.length;
    g && console.warn(`[Worker] Creating new worker #${s}`);
    const n = Le.createWorker(i || {});
    return H.push(n), n;
  }
  const t = lt++ % H.length;
  return H[t];
}
class Le {
  constructor(t, e) {
    this.worker = t, this._debug = e.debug ?? !1, t.onmessage = (s) => {
      const n = s.data;
      switch (this._debug && console.log("[Worker] EVENT", n), n.type) {
        case "loaded-gltf":
          for (const r of this._running)
            if (r.url === n.result.url) {
              ct(n.result), r.resolve(n.result);
              const o = r.url;
              o.startsWith("blob:") && URL.revokeObjectURL(o);
            }
      }
    }, t.onerror = (s) => {
      console.error("[Worker] Error in gltf-progressive worker:", s);
    }, t.postMessage({
      type: "init"
    });
  }
  static async createWorker(t) {
    const e = /* new-worker */ new Worker(URL.createObjectURL(new Blob(["import '" + `${new URL('./loader.worker-CiTwpNPW.js', import.meta.url).toString()}` + "';"], { type: 'text/javascript' })), {
      type: "module"
    });
    return new Le(e, t);
  }
  _running = [];
  _webglRenderer = null;
  async load(t, e) {
    const s = Qe();
    let n = e?.renderer;
    n || (this._webglRenderer ??= (async () => {
      const { WebGLRenderer: u } = await import("./three-MHVqtJYj.js").then((d) => d.THREE);
      return new u();
    })(), n = await this._webglRenderer);
    const l = we(n).ktx2Loader.workerConfig;
    t instanceof URL ? t = t.toString() : t.startsWith("file:") ? t = URL.createObjectURL(new Blob([t])) : !t.startsWith("blob:") && !t.startsWith("http:") && !t.startsWith("https:") && (t = new URL(t, window.location.href).toString());
    const a = {
      type: "load",
      url: t,
      dracoDecoderPath: s.dracoDecoderPath,
      ktx2TranscoderPath: s.ktx2TranscoderPath,
      ktx2LoaderConfig: l
    };
    return this._debug && console.debug("[Worker] Sending load request", a), this.worker.postMessage(a), new Promise((u) => {
      this._running.push({
        url: t.toString(),
        resolve: u
      });
    });
  }
  _debug = !1;
}
function ct(i) {
  for (const t of i.geometries) {
    const e = t.geometry, s = new J();
    if (s.name = e.name || "", e.index) {
      const n = e.index;
      s.setIndex(le(n));
    }
    for (const n in e.attributes) {
      const r = e.attributes[n], o = le(r);
      s.setAttribute(n, o);
    }
    if (e.morphAttributes)
      for (const n in e.morphAttributes) {
        const o = e.morphAttributes[n].map((l) => le(l));
        s.morphAttributes[n] = o;
      }
    if (s.morphTargetsRelative = e.morphTargetsRelative ?? !1, s.boundingBox = new ge(), s.boundingBox.min = new A(
      e.boundingBox?.min.x,
      e.boundingBox?.min.y,
      e.boundingBox?.min.z
    ), s.boundingBox.max = new A(
      e.boundingBox?.max.x,
      e.boundingBox?.max.y,
      e.boundingBox?.max.z
    ), s.boundingSphere = new Oe(
      new A(
        e.boundingSphere?.center.x,
        e.boundingSphere?.center.y,
        e.boundingSphere?.center.z
      ),
      e.boundingSphere?.radius
    ), e.groups)
      for (const n of e.groups)
        s.addGroup(n.start, n.count, n.materialIndex);
    e.userData && (s.userData = e.userData), t.geometry = s;
  }
  for (const t of i.textures) {
    const e = t.texture;
    let s = null;
    if (e.isCompressedTexture) {
      const n = e.mipmaps, r = e.image?.width || e.source?.data?.width || -1, o = e.image?.height || e.source?.data?.height || -1;
      s = new Ge(
        n,
        r,
        o,
        e.format,
        e.type,
        e.mapping,
        e.wrapS,
        e.wrapT,
        e.magFilter,
        e.minFilter,
        e.anisotropy,
        e.colorSpace
      );
    } else
      s = new E(
        e.image,
        e.mapping,
        e.wrapS,
        e.wrapT,
        e.magFilter,
        e.minFilter,
        e.format,
        e.type,
        e.anisotropy,
        e.colorSpace
      ), s.mipmaps = e.mipmaps, s.channel = e.channel, s.source.data = e.source.data, s.flipY = e.flipY, s.premultiplyAlpha = e.premultiplyAlpha, s.unpackAlignment = e.unpackAlignment, s.matrix = new Fe(...e.matrix.elements);
    if (!s) {
      console.error("[Worker] Failed to create new texture from received data. Texture is not a CompressedTexture or Texture.");
      continue;
    }
    t.texture = s;
  }
  return i;
}
function le(i) {
  let t = i;
  if ("isInterleavedBufferAttribute" in i && i.isInterleavedBufferAttribute) {
    const e = i.data, s = e.array, n = new We(s, e.stride);
    t = new Ue(n, i.itemSize, s.byteOffset, i.normalized), t.offset = i.offset;
  } else "isBufferAttribute" in i && i.isBufferAttribute && (t = new ze(i.array, i.itemSize, i.normalized), t.usage = i.usage, t.gpuType = i.gpuType, t.updateRanges = i.updateRanges);
  return t;
}
const ft = X("gltf-progressive-worker"), ht = X("gltf-progressive-reduce-mipmaps"), ue = Symbol("needle-progressive-texture"), F = "NEEDLE_progressive";
class y {
  /** The name of the extension */
  get name() {
    return F;
  }
  // #region PUBLIC API
  static getMeshLODExtension(t) {
    const e = this.getAssignedLODInformation(t);
    return e?.key ? this.lodInfos.get(e.key) : null;
  }
  static getPrimitiveIndex(t) {
    const e = this.getAssignedLODInformation(t)?.index;
    return e ?? -1;
  }
  static getMaterialMinMaxLODsCount(t, e) {
    const s = this, n = "LODS:minmax", r = t[n];
    if (r != null) return r;
    if (e || (e = {
      min_count: 1 / 0,
      max_count: 0,
      lods: []
    }), Array.isArray(t)) {
      for (const l of t)
        this.getMaterialMinMaxLODsCount(l, e);
      return t[n] = e, e;
    }
    if (g === "verbose" && console.log("getMaterialMinMaxLODsCount", t), t.type === "ShaderMaterial" || t.type === "RawShaderMaterial") {
      const l = t;
      for (const a of Object.keys(l.uniforms)) {
        const u = l.uniforms[a].value;
        u?.isTexture === !0 && o(u, e);
      }
    } else if (t.isMaterial)
      for (const l of Object.keys(t)) {
        const a = t[l];
        a?.isTexture === !0 && o(a, e);
      }
    else
      g && console.warn(`[getMaterialMinMaxLODsCount] Unsupported material type: ${t.type}`);
    return t[n] = e, e;
    function o(l, a) {
      const u = s.getAssignedLODInformation(l);
      if (u) {
        const d = s.lodInfos.get(u.key);
        if (d && d.lods) {
          a.min_count = Math.min(a.min_count, d.lods.length), a.max_count = Math.max(a.max_count, d.lods.length);
          for (let p = 0; p < d.lods.length; p++) {
            const L = d.lods[p];
            L.width && (a.lods[p] = a.lods[p] || { min_height: 1 / 0, max_height: 0 }, a.lods[p].min_height = Math.min(a.lods[p].min_height, L.height), a.lods[p].max_height = Math.max(a.lods[p].max_height, L.height));
          }
        }
      }
    }
  }
  /** Check if a LOD level is available for a mesh or a texture
   * @param obj the mesh or texture to check
   * @param level the level of detail to check for (0 is the highest resolution). If undefined, the function checks if any LOD level is available
   * @returns true if the LOD level is available (or if any LOD level is available if level is undefined)
   */
  static hasLODLevelAvailable(t, e) {
    if (Array.isArray(t)) {
      for (const r of t)
        if (this.hasLODLevelAvailable(r, e)) return !0;
      return !1;
    }
    if (t.isMaterial === !0) {
      for (const r of Object.keys(t)) {
        const o = t[r];
        if (o && o.isTexture && this.hasLODLevelAvailable(o, e))
          return !0;
      }
      return !1;
    } else if (t.isGroup === !0) {
      for (const r of t.children)
        if (r.isMesh === !0 && this.hasLODLevelAvailable(r, e))
          return !0;
    }
    let s, n;
    if (t.isMesh ? s = t.geometry : (t.isBufferGeometry || t.isTexture) && (s = t), s && s?.userData?.LODS) {
      const r = s.userData.LODS;
      if (n = this.lodInfos.get(r.key), e === void 0) return n != null;
      if (n)
        return Array.isArray(n.lods) ? e < n.lods.length : e === 0;
    }
    return !1;
  }
  /** Load a different resolution of a mesh (if available)
   * @param context the context
   * @param source the sourceid of the file from which the mesh is loaded (this is usually the component's sourceId)
   * @param mesh the mesh to load the LOD for
   * @param level the level of detail to load (0 is the highest resolution)
   * @returns a promise that resolves to the mesh with the requested LOD level
   * @example
   * ```javascript
   * const mesh = this.gameObject as Mesh;
   * NEEDLE_progressive.assignMeshLOD(context, sourceId, mesh, 1).then(mesh => {
   *    console.log("Mesh with LOD level 1 loaded", mesh);
   * });
   * ```
   */
  static assignMeshLOD(t, e) {
    if (!t) return Promise.resolve(null);
    if (t instanceof q || t.isMesh === !0) {
      const s = t.geometry, n = this.getAssignedLODInformation(s);
      if (!n)
        return Promise.resolve(null);
      for (const r of U)
        r.onBeforeGetLODMesh?.(t, e);
      return t["LOD:requested level"] = e, y.getOrLoadLOD(s, e).then((r) => {
        if (Array.isArray(r)) {
          const o = n.index || 0;
          r = r[o];
        }
        return t["LOD:requested level"] === e && (delete t["LOD:requested level"], r && s != r && (r?.isBufferGeometry ? t.geometry = r : g && console.error("Invalid LOD geometry", r))), r;
      }).catch((r) => (console.error("Error loading mesh LOD", t, r), null));
    } else g && console.error("Invalid call to assignMeshLOD: Request mesh LOD but the object is not a mesh", t);
    return Promise.resolve(null);
  }
  static assignTextureLOD(t, e = 0) {
    if (!t) return Promise.resolve(null);
    if (t.isMesh === !0) {
      const s = t;
      if (Array.isArray(s.material)) {
        const n = new Array();
        for (const r of s.material) {
          const o = this.assignTextureLOD(r, e);
          n.push(o);
        }
        return Promise.all(n).then((r) => {
          const o = new Array();
          for (const l of r)
            Array.isArray(l) && o.push(...l);
          return o;
        });
      } else
        return this.assignTextureLOD(s.material, e);
    }
    if (t.isMaterial === !0) {
      const s = t, n = [], r = new Array();
      if (s.uniforms && (s.isRawShaderMaterial || s.isShaderMaterial === !0)) {
        const o = s;
        for (const l of Object.keys(o.uniforms)) {
          const a = o.uniforms[l].value;
          if (a?.isTexture === !0) {
            const u = this.assignTextureLODForSlot(a, e, s, l).then((d) => (d && o.uniforms[l].value != d && (o.uniforms[l].value = d, o.uniformsNeedUpdate = !0), d));
            n.push(u), r.push(l);
          }
        }
      } else
        for (const o of Object.keys(s)) {
          const l = s[o];
          if (l?.isTexture === !0) {
            const a = this.assignTextureLODForSlot(l, e, s, o);
            n.push(a), r.push(o);
          }
        }
      return Promise.all(n).then((o) => {
        const l = new Array();
        for (let a = 0; a < o.length; a++) {
          const u = o[a], d = r[a];
          u && u.isTexture === !0 ? l.push({ material: s, slot: d, texture: u, level: e }) : l.push({ material: s, slot: d, texture: null, level: e });
        }
        return l;
      });
    }
    if (t instanceof E || t.isTexture === !0) {
      const s = t;
      return this.assignTextureLODForSlot(s, e, null, null);
    }
    return Promise.resolve(null);
  }
  // #region INTERNAL
  static assignTextureLODForSlot(t, e, s, n) {
    return t?.isTexture !== !0 ? Promise.resolve(null) : n === "glyphMap" ? Promise.resolve(t) : y.getOrLoadLOD(t, e).then((r) => {
      if (Array.isArray(r))
        return console.warn("Progressive: Got an array of textures for a texture slot, this should not happen..."), null;
      if (r?.isTexture === !0) {
        if (r != t && s && n) {
          const o = s[n];
          if (o && !g) {
            const l = this.getAssignedLODInformation(o);
            if (l && l?.level < e)
              return g === "verbose" && console.warn("Assigned texture level is already higher: ", l.level, e, s, o, r), null;
          }
          if (ht && r.mipmaps) {
            const l = r.mipmaps.length;
            r.mipmaps.length = Math.min(r.mipmaps.length, 3), l !== r.mipmaps.length && g && console.debug(`Reduced mipmap count from ${l} to ${r.mipmaps.length} for ${r.uuid}: ${r.image?.width}x${r.image?.height}.`);
          }
          s[n] = r;
        }
        return r;
      } else g == "verbose" && console.warn("No LOD found for", t, e);
      return null;
    }).catch((r) => (console.error("Error loading LOD", t, r), null));
  }
  parser;
  url;
  constructor(t) {
    const e = t.options.path;
    g && console.log("Progressive extension registered for", e), this.parser = t, this.url = e;
  }
  _isLoadingMesh;
  loadMesh = (t) => {
    if (this._isLoadingMesh) return null;
    const e = this.parser.json.meshes[t]?.extensions?.[F];
    return e ? (this._isLoadingMesh = !0, this.parser.getDependency("mesh", t).then((s) => (this._isLoadingMesh = !1, s && y.registerMesh(this.url, e.guid, s, e.lods?.length, 0, e), s))) : null;
  };
  // private _isLoadingTexture;
  // loadTexture = (textureIndex: number) => {
  //     if (this._isLoadingTexture) return null;
  //     const ext = this.parser.json.textures[textureIndex]?.extensions?.[EXTENSION_NAME] as NEEDLE_ext_progressive_texture;
  //     if (!ext) return null;
  //     this._isLoadingTexture = true;
  //     return this.parser.getDependency("texture", textureIndex).then(tex => {
  //         this._isLoadingTexture = false;
  //         if (tex) {
  //             NEEDLE_progressive.registerTexture(this.url, tex as Texture, ext.lods?.length, textureIndex, ext);
  //         }
  //         return tex;
  //     });
  // }
  afterRoot(t) {
    return g && console.log("AFTER", this.url, t), this.parser.json.textures?.forEach((e, s) => {
      if (e?.extensions) {
        const n = e?.extensions[F];
        if (n) {
          if (!n.lods) {
            g && console.warn("Texture has no LODs", n);
            return;
          }
          let r = !1;
          for (const o of this.parser.associations.keys())
            o.isTexture === !0 && this.parser.associations.get(o)?.textures === s && (r = !0, y.registerTexture(this.url, o, n.lods?.length, s, n));
          r || this.parser.getDependency("texture", s).then((o) => {
            o && y.registerTexture(this.url, o, n.lods?.length, s, n);
          });
        }
      }
    }), this.parser.json.meshes?.forEach((e, s) => {
      if (e?.extensions) {
        const n = e?.extensions[F];
        if (n && n.lods) {
          for (const r of this.parser.associations.keys())
            if (r.isMesh) {
              const o = this.parser.associations.get(r);
              o?.meshes === s && y.registerMesh(this.url, n.guid, r, n.lods.length, o.primitives, n);
            }
        }
      }
    }), null;
  }
  /**
   * Register a texture with LOD information
   */
  static registerTexture = (t, e, s, n, r) => {
    if (!e) {
      g && console.error("!! gltf-progressive: Called register texture without texture");
      return;
    }
    if (g) {
      const l = e.image?.width || e.source?.data?.width || 0, a = e.image?.height || e.source?.data?.height || 0;
      console.log(`> gltf-progressive: register texture[${n}] "${e.name || e.uuid}", Current: ${l}x${a}, Max: ${r.lods[0]?.width}x${r.lods[0]?.height}, uuid: ${e.uuid}`, r, e);
    }
    e.source && (e.source[ue] = r);
    const o = r.guid;
    y.assignLODInformation(t, e, o, s, n), y.lodInfos.set(o, r), y.lowresCache.set(o, e);
  };
  /**
   * Register a mesh with LOD information
   */
  static registerMesh = (t, e, s, n, r, o) => {
    const l = s.geometry;
    if (!l) {
      g && console.warn("gltf-progressive: Register mesh without geometry");
      return;
    }
    l.userData || (l.userData = {}), g && console.log("> Progressive: register mesh " + s.name, { index: r, uuid: s.uuid }, o, s), y.assignLODInformation(t, l, e, n, r), y.lodInfos.set(e, o);
    let a = y.lowresCache.get(e);
    a ? a.push(s.geometry) : a = [s.geometry], y.lowresCache.set(e, a), n > 0 && !Z(s) && ot(s, l);
    for (const u of U)
      u.onRegisteredNewMesh?.(s, o);
  };
  /** A map of key = asset uuid and value = LOD information */
  static lodInfos = /* @__PURE__ */ new Map();
  /** cache of already loaded mesh lods */
  static previouslyLoaded = /* @__PURE__ */ new Map();
  /** this contains the geometry/textures that were originally loaded */
  static lowresCache = /* @__PURE__ */ new Map();
  static workers = [];
  static _workersIndex = 0;
  static async getOrLoadLOD(t, e) {
    const s = g == "verbose", n = this.getAssignedLODInformation(t);
    if (!n)
      return g && console.warn(`[gltf-progressive] No LOD information found: ${t.name}, uuid: ${t.uuid}, type: ${t.type}`, t), null;
    const r = n?.key;
    let o;
    if (t.isTexture === !0) {
      const a = t;
      a.source && a.source[ue] && (o = a.source[ue]);
    }
    if (o || (o = y.lodInfos.get(r)), !o)
      g && console.warn(`Can not load LOD ${e}: no LOD info found for "${r}" ${t.name}`, t.type, y.lodInfos);
    else {
      if (e > 0) {
        let d = !1;
        const p = Array.isArray(o.lods);
        if (p && e >= o.lods.length ? d = !0 : p || (d = !0), d)
          return this.lowresCache.get(r);
      }
      const a = Array.isArray(o.lods) ? o.lods[e]?.path : o.lods;
      if (!a)
        return g && !o["missing:uri"] && (o["missing:uri"] = !0, console.warn("Missing uri for progressive asset for LOD " + e, o)), null;
      const u = st(n.url, a);
      if (u.endsWith(".glb") || u.endsWith(".gltf")) {
        if (!o.guid)
          return console.warn("missing pointer for glb/gltf texture", o), null;
        const d = u + "_" + o.guid, p = await this.queue.slot(u), L = this.previouslyLoaded.get(d);
        if (L !== void 0) {
          s && console.log(`LOD ${e} was already loading/loaded: ${d}`);
          let c = await L.catch((O) => (console.error(`Error loading LOD ${e} from ${u}
`, O), null)), x = !1;
          if (c == null || (c instanceof E && t instanceof E ? c.image?.data || c.source?.data ? c = this.copySettings(t, c) : (x = !0, this.previouslyLoaded.delete(d)) : c instanceof J && t instanceof J && (c.attributes.position?.array || (x = !0, this.previouslyLoaded.delete(d)))), !x)
            return c;
        }
        if (!p.use)
          return g && console.log(`LOD ${e} was aborted: ${u}`), null;
        const _ = o, I = new Promise(async (c, x) => {
          if (ft) {
            const m = await (await dt({})).load(u);
            if (m.textures.length > 0)
              for (const f of m.textures) {
                let h = f.texture;
                return y.assignLODInformation(n.url, h, r, e, void 0), t instanceof E && (h = this.copySettings(t, h)), h && (h.guid = _.guid), c(h);
              }
            if (m.geometries.length > 0) {
              const f = new Array();
              for (const h of m.geometries) {
                const v = h.geometry;
                y.assignLODInformation(n.url, v, r, e, h.primitiveIndex), f.push(v);
              }
              return c(f);
            }
            return c(null);
          }
          const O = new xe();
          Te(O), g && (await new Promise((w) => setTimeout(w, 1e3)), s && console.warn("Start loading (delayed) " + u, _.guid));
          let B = u;
          if (_ && Array.isArray(_.lods)) {
            const w = _.lods[e];
            w.hash && (B += "?v=" + w.hash);
          }
          const M = await O.loadAsync(B).catch((w) => (console.error(`Error loading LOD ${e} from ${u}
`, w), c(null)));
          if (!M)
            return c(null);
          const z = M.parser;
          s && console.log("Loading finished " + u, _.guid);
          let S = 0;
          if (M.parser.json.textures) {
            let w = !1;
            for (const m of M.parser.json.textures) {
              if (m?.extensions) {
                const f = m?.extensions[F];
                if (f?.guid && f.guid === _.guid) {
                  w = !0;
                  break;
                }
              }
              S++;
            }
            if (w) {
              let m = await z.getDependency("texture", S);
              return m && y.assignLODInformation(n.url, m, r, e, void 0), s && console.log('change "' + t.name + '" → "' + m.name + '"', u, S, m, d), t instanceof E && (m = this.copySettings(t, m)), m && (m.guid = _.guid), c(m);
            } else g && console.warn("Could not find texture with guid", _.guid, M.parser.json);
          }
          if (S = 0, M.parser.json.meshes) {
            let w = !1;
            for (const m of M.parser.json.meshes) {
              if (m?.extensions) {
                const f = m?.extensions[F];
                if (f?.guid && f.guid === _.guid) {
                  w = !0;
                  break;
                }
              }
              S++;
            }
            if (w) {
              const m = await z.getDependency("mesh", S);
              if (s && console.log(`Loaded Mesh "${m.name}"`, u, S, m, d), m.isMesh === !0) {
                const f = m.geometry;
                return y.assignLODInformation(n.url, f, r, e, 0), c(f);
              } else {
                const f = new Array();
                for (let h = 0; h < m.children.length; h++) {
                  const v = m.children[h];
                  if (v.isMesh === !0) {
                    const b = v.geometry;
                    y.assignLODInformation(n.url, b, r, e, h), f.push(b);
                  }
                }
                return c(f);
              }
            } else g && console.warn("Could not find mesh with guid", _.guid, M.parser.json);
          }
          return c(null);
        });
        return this.previouslyLoaded.set(d, I), p.use(I), await I;
      } else if (t instanceof E) {
        s && console.log("Load texture from uri: " + u);
        const p = await new Ee().loadAsync(u);
        return p ? (p.guid = o.guid, p.flipY = !1, p.needsUpdate = !0, p.colorSpace = t.colorSpace, s && console.log(o, p)) : g && console.warn("failed loading", u), p;
      }
    }
    return null;
  }
  static maxConcurrent = 50;
  static queue = new rt(y.maxConcurrent, { debug: g != !1 });
  static assignLODInformation(t, e, s, n, r) {
    if (!e) return;
    e.userData || (e.userData = {});
    const o = new gt(t, s, n, r);
    e.userData.LODS = o, "source" in e && typeof e.source == "object" && (e.source.LODS = o);
  }
  static getAssignedLODInformation(t) {
    return t ? t.userData?.LODS ? t.userData.LODS : "source" in t && t.source?.LODS ? t.source.LODS : null : null;
  }
  // private static readonly _copiedTextures: WeakMap<Texture, Texture> = new Map();
  static copySettings(t, e) {
    return e ? (g === "verbose" && console.debug(`Copy texture settings
`, t.uuid, `
`, e.uuid), e = e.clone(), e.offset = t.offset, e.repeat = t.repeat, e.colorSpace = t.colorSpace, e.magFilter = t.magFilter, e.minFilter = t.minFilter, e.wrapS = t.wrapS, e.wrapT = t.wrapT, e.flipY = t.flipY, e.anisotropy = t.anisotropy, e.mipmaps || (e.generateMipmaps = t.generateMipmaps), e) : t;
  }
}
class gt {
  url;
  /** the key to lookup the LOD information */
  key;
  level;
  /** For multi objects (e.g. a group of meshes) this is the index of the object */
  index;
  constructor(t, e, s, n) {
    this.url = t, this.key = e, this.level = s, n != null && (this.index = n);
  }
}
class de {
  static addPromise = (t, e, s, n) => {
    n.forEach((r) => {
      r.add(t, e, s);
    });
  };
  ready;
  /** The number of promises that have been added to this group so far */
  get awaitedCount() {
    return this._addedCount;
  }
  /** The number of promises that have been resolved */
  get resolvedCount() {
    return this._resolvedCount;
  }
  /** The number of promises that are in-flight */
  get currentlyAwaiting() {
    return this._awaiting.length;
  }
  _resolve;
  _signal;
  /** start frame can be undefined if the user configured this group to wait for the first promise.
   * Then the start frame will be set when the first promise has been added to the group */
  _frame_start;
  /** How many frames to capture since the start frame */
  _frames_to_capture;
  _resolved = !1;
  _addedCount = 0;
  _resolvedCount = 0;
  /** These promises are currently being awaited */
  _awaiting = [];
  _maxPromisesPerObject = 1;
  constructor(t, e) {
    const n = Math.max(e.frames ?? 2, 2);
    this._frame_start = e.waitForFirstCapture ? void 0 : t, this._frames_to_capture = n, this.ready = new Promise((r) => {
      this._resolve = r;
    }), this.ready.finally(() => {
      this._resolved = !0, this._awaiting.length = 0;
    }), this._signal = e.signal, this._signal?.addEventListener("abort", () => {
      this.resolveNow();
    }), this._maxPromisesPerObject = Math.max(1, e.maxPromisesPerObject ?? 1);
  }
  _currentFrame = 0;
  update(t) {
    this._currentFrame = t, this._frame_start === void 0 && this._addedCount > 0 && (this._frame_start = t), (this._signal?.aborted || this._awaiting.length === 0 && this._frame_start !== void 0 && t > this._frame_start + this._frames_to_capture) && this.resolveNow();
  }
  _seen = /* @__PURE__ */ new WeakMap();
  add(t, e, s) {
    if (this._resolved) {
      g && console.warn("PromiseGroup: Trying to add a promise to a resolved group, ignoring.");
      return;
    }
    if (!(this._frame_start !== void 0 && this._currentFrame > this._frame_start + this._frames_to_capture)) {
      if (this._maxPromisesPerObject >= 1)
        if (this._seen.has(e)) {
          let n = this._seen.get(e);
          if (n >= this._maxPromisesPerObject) {
            g && console.warn("PromiseGroup: Already awaiting object ignoring new promise for it.");
            return;
          }
          this._seen.set(e, n + 1);
        } else
          this._seen.set(e, 1);
      this._awaiting.push(s), this._addedCount++, s.finally(() => {
        this._resolvedCount++, this._awaiting.splice(this._awaiting.indexOf(s), 1);
      });
    }
  }
  resolveNow() {
    this._resolved || this._resolve?.({
      awaited_count: this._addedCount,
      resolved_count: this._resolvedCount,
      cancelled: this._signal?.aborted ?? !1
    });
  }
}
const k = X("debugprogressive"), pt = X("noprogressive"), ce = Symbol("Needle:LODSManager"), fe = Symbol("Needle:LODState"), W = Symbol("Needle:CurrentLOD"), T = { mesh_lod: -1, texture_lod: -1 };
let oe = class D {
  /** 
   * Assign a function to draw debug lines for the LODs. This function will be called with the start and end position of the line and the color of the line when the `debugprogressive` query parameter is set.
   */
  static debugDrawLine;
  /** @internal */
  static getObjectLODState(t) {
    return t[fe];
  }
  static addPlugin(t) {
    U.push(t);
  }
  static removePlugin(t) {
    const e = U.indexOf(t);
    e >= 0 && U.splice(e, 1);
  }
  /**
   * Gets the LODsManager for the given renderer. If the LODsManager does not exist yet, it will be created.  
   * @param renderer The renderer to get the LODsManager for.
   * @returns The LODsManager instance.
   */
  static get(t, e) {
    if (t[ce])
      return console.debug("[gltf-progressive] LODsManager already exists for this renderer"), t[ce];
    const s = new D(t, {
      engine: "unknown",
      ...e
    });
    return t[ce] = s, s;
  }
  renderer;
  context;
  projectionScreenMatrix = new _e();
  /** @deprecated use static `LODsManager.addPlugin()` method. This getter will be removed in later versions */
  get plugins() {
    return U;
  }
  /**
   * Force override the LOD level for all objects (meshes + textures) rendered in the scene
   * @default undefined automatically calculate LOD level
   */
  overrideLodLevel = void 0;
  /**
   * The target triangle density is the desired max amount of triangles on screen when the mesh is filling the screen.  
   * @default 200_000
   */
  targetTriangleDensity = 2e5;
  /**
   * The interval in frames to automatically update the bounds of skinned meshes.   
   * Set to 0 or a negative value to disable automatic bounds updates. 
   * @default 30
   */
  skinnedMeshAutoUpdateBoundsInterval = 30;
  /**
   * The update interval in frames. If set to 0, the LODs will be updated every frame. If set to 2, the LODs will be updated every second frame, etc.
   * @default "auto"
   */
  updateInterval = "auto";
  #e = 1;
  /**
   * If set to true, the LODsManager will not update the LODs.
   * @default false
   */
  pause = !1;
  /**
   * When set to true the LODsManager will not update the LODs. This can be used to manually update the LODs using the `update` method.  
   * Otherwise the LODs will be updated automatically when the renderer renders the scene.
   * @default false
   */
  manual = !1;
  _newPromiseGroups = [];
  _promiseGroupIds = 0;
  /**
   * Call to await LODs loading during the next render cycle.
   */
  awaitLoading(t) {
    const e = this._promiseGroupIds++, s = new de(this.#r, { ...t });
    this._newPromiseGroups.push(s);
    const n = performance.now();
    return s.ready.finally(() => {
      const r = this._newPromiseGroups.indexOf(s);
      r >= 0 && (this._newPromiseGroups.splice(r, 1), Me() && performance.measure("LODsManager:awaitLoading", {
        start: n,
        detail: { id: e, name: t?.name, awaited: s.awaitedCount, resolved: s.resolvedCount }
      }));
    }), s.ready;
  }
  _postprocessPromiseGroups() {
    if (this._newPromiseGroups.length !== 0)
      for (let t = this._newPromiseGroups.length - 1; t >= 0; t--)
        this._newPromiseGroups[t].update(this.#r);
  }
  _lodchangedlisteners = [];
  addEventListener(t, e) {
    t === "changed" && this._lodchangedlisteners.push(e);
  }
  removeEventListener(t, e) {
    if (t === "changed") {
      const s = this._lodchangedlisteners.indexOf(e);
      s >= 0 && this._lodchangedlisteners.splice(s, 1);
    }
  }
  // readonly plugins: NEEDLE_progressive_plugin[] = [];
  constructor(t, e) {
    this.renderer = t, this.context = { ...e };
  }
  #t;
  #o = new Ne();
  #r = 0;
  #n = 0;
  #i = 0;
  #s = 0;
  _fpsBuffer = [60, 60, 60, 60, 60];
  /**
   * Enable the LODsManager. This will replace the render method of the renderer with a method that updates the LODs.
   */
  enable() {
    if (this.#t) return;
    console.debug("[gltf-progressive] Enabling LODsManager for renderer");
    let t = 0;
    this.#t = this.renderer.render;
    const e = this;
    we(this.renderer), this.renderer.render = function(s, n) {
      const r = e.renderer.getRenderTarget();
      (r == null || "isXRRenderTarget" in r && r.isXRRenderTarget) && (t = 0, e.#r += 1, e.#n = e.#o.getDelta(), e.#i += e.#n, e._fpsBuffer.shift(), e._fpsBuffer.push(1 / e.#n), e.#s = e._fpsBuffer.reduce((l, a) => l + a) / e._fpsBuffer.length, k && e.#r % 200 === 0 && console.log("FPS", Math.round(e.#s), "Interval:", e.#e));
      const o = t++;
      e.#t.call(this, s, n), e.onAfterRender(s, n, o);
    };
  }
  disable() {
    this.#t && (console.debug("[gltf-progressive] Disabling LODsManager for renderer"), this.renderer.render = this.#t, this.#t = void 0);
  }
  update(t, e) {
    this.internalUpdate(t, e);
  }
  onAfterRender(t, e, s) {
    if (this.pause) return;
    const r = this.renderer.renderLists.get(t, 0).opaque;
    let o = !0;
    if (r.length === 1) {
      const l = r[0].material;
      (l.name === "EffectMaterial" || l.name === "CopyShader") && (o = !1);
    }
    if ((e.parent && e.parent.type === "CubeCamera" || s >= 1 && e.type === "OrthographicCamera") && (o = !1), o) {
      if (pt || (this.updateInterval === "auto" ? this.#s < 40 && this.#e < 10 ? (this.#e += 1, k && console.warn("↓ Reducing LOD updates", this.#e, this.#s.toFixed(0))) : this.#s >= 60 && this.#e > 1 && (this.#e -= 1, k && console.warn("↑ Increasing LOD updates", this.#e, this.#s.toFixed(0))) : this.#e = this.updateInterval, this.#e > 0 && this.#r % this.#e != 0))
        return;
      this.internalUpdate(t, e), this._postprocessPromiseGroups();
    }
  }
  /**
   * Update LODs in a scene
   */
  internalUpdate(t, e) {
    const s = this.renderer.renderLists.get(t, 0), n = s.opaque;
    this.projectionScreenMatrix.multiplyMatrices(e.projectionMatrix, e.matrixWorldInverse);
    const r = this.targetTriangleDensity;
    for (const a of n) {
      if (a.material && (a.geometry?.type === "BoxGeometry" || a.geometry?.type === "BufferGeometry") && (a.material.name === "SphericalGaussianBlur" || a.material.name == "BackgroundCubeMaterial" || a.material.name === "CubemapFromEquirect" || a.material.name === "EquirectangularToCubeUV")) {
        k && (a.material["NEEDLE_PROGRESSIVE:IGNORE-WARNING"] || (a.material["NEEDLE_PROGRESSIVE:IGNORE-WARNING"] = !0, console.warn("Ignoring skybox or BLIT object", a, a.material.name, a.material.type)));
        continue;
      }
      switch (a.material.type) {
        case "LineBasicMaterial":
        case "LineDashedMaterial":
        case "PointsMaterial":
        case "ShadowMaterial":
        case "MeshDistanceMaterial":
        case "MeshDepthMaterial":
          continue;
      }
      if (k === "color" && a.material && !a.object.progressive_debug_color) {
        a.object.progressive_debug_color = !0;
        const d = Math.random() * 16777215, p = new qe({ color: d });
        a.object.material = p;
      }
      const u = a.object;
      (u instanceof q || u.isMesh) && this.updateLODs(t, e, u, r);
    }
    const o = s.transparent;
    for (const a of o) {
      const u = a.object;
      (u instanceof q || u.isMesh) && this.updateLODs(t, e, u, r);
    }
    const l = s.transmissive;
    for (const a of l) {
      const u = a.object;
      (u instanceof q || u.isMesh) && this.updateLODs(t, e, u, r);
    }
  }
  /** Update the LOD levels for the renderer. */
  updateLODs(t, e, s, n) {
    s.userData || (s.userData = {});
    let r = s[fe];
    if (r || (r = new mt(), s[fe] = r), r.frames++ < 2)
      return;
    for (const l of U)
      l.onBeforeUpdateLOD?.(this.renderer, t, e, s);
    const o = this.overrideLodLevel !== void 0 ? this.overrideLodLevel : N;
    o >= 0 ? (T.mesh_lod = o, T.texture_lod = o) : (this.calculateLodLevel(e, s, r, n, T), T.mesh_lod = Math.round(T.mesh_lod), T.texture_lod = Math.round(T.texture_lod)), T.mesh_lod >= 0 && this.loadProgressiveMeshes(s, T.mesh_lod), s.material && T.texture_lod >= 0 && this.loadProgressiveTextures(s.material, T.texture_lod, o), g && s.material && !s.isGizmo && ke(s.material);
    for (const l of U)
      l.onAfterUpdatedLOD?.(this.renderer, t, e, s, T);
    r.lastLodLevel_Mesh = T.mesh_lod, r.lastLodLevel_Texture = T.texture_lod;
  }
  /** Load progressive textures for the given material
   * @param material the material to load the textures for
   * @param level the LOD level to load. Level 0 is the best quality, higher levels are lower quality
   * @returns Promise with true if the LOD was loaded, false if not
   */
  loadProgressiveTextures(t, e, s) {
    if (!t) return;
    if (Array.isArray(t)) {
      for (const r of t)
        this.loadProgressiveTextures(r, e);
      return;
    }
    let n = !1;
    if ((t[W] === void 0 || e < t[W]) && (n = !0), s !== void 0 && s >= 0 && (n = t[W] != s, e = s), n) {
      t[W] = e;
      const r = y.assignTextureLOD(t, e).then((o) => {
        this._lodchangedlisteners.forEach((l) => l({ type: "texture", level: e, object: t }));
      });
      de.addPromise("texture", t, r, this._newPromiseGroups);
    }
  }
  /** Load progressive meshes for the given mesh
   * @param mesh the mesh to load the LOD for
   * @param index the index of the mesh if it's part of a group
   * @param level the LOD level to load. Level 0 is the best quality, higher levels are lower quality
   * @returns Promise with true if the LOD was loaded, false if not
   */
  loadProgressiveMeshes(t, e) {
    if (!t) return Promise.resolve(null);
    let s = t[W] !== e;
    const n = t["DEBUG:LOD"];
    if (n != null && (s = t[W] != n, e = n), s) {
      t[W] = e;
      const r = t.geometry, o = y.assignMeshLOD(t, e).then((l) => (l && t[W] == e && r != t.geometry && this._lodchangedlisteners.forEach((a) => a({ type: "mesh", level: e, object: t })), l));
      return de.addPromise("mesh", t, o, this._newPromiseGroups), o;
    }
    return Promise.resolve(null);
  }
  // private testIfLODLevelsAreAvailable() {
  _sphere = new Oe();
  _tempBox = new ge();
  _tempBox2 = new ge();
  tempMatrix = new _e();
  _tempWorldPosition = new A();
  _tempBoxSize = new A();
  _tempBox2Size = new A();
  static corner0 = new A();
  static corner1 = new A();
  static corner2 = new A();
  static corner3 = new A();
  static _tempPtInside = new A();
  static isInside(t, e) {
    const s = t.min, n = t.max, r = (s.x + n.x) * 0.5, o = (s.y + n.y) * 0.5;
    return this._tempPtInside.set(r, o, s.z).applyMatrix4(e).z < 0;
  }
  static skinnedMeshBoundsFrameOffsetCounter = 0;
  static $skinnedMeshBoundsOffset = Symbol("gltf-progressive-skinnedMeshBoundsOffset");
  // #region calculateLodLevel
  calculateLodLevel(t, e, s, n, r) {
    if (!e) {
      r.mesh_lod = -1, r.texture_lod = -1;
      return;
    }
    if (!t) {
      r.mesh_lod = -1, r.texture_lod = -1;
      return;
    }
    let l = 10 + 1, a = !1;
    if (k && e["DEBUG:LOD"] != null)
      return e["DEBUG:LOD"];
    const u = y.getMeshLODExtension(e.geometry)?.lods, d = y.getPrimitiveIndex(e.geometry), p = u && u.length > 0, L = y.getMaterialMinMaxLODsCount(e.material), _ = L.min_count !== 1 / 0 && L.min_count >= 0 && L.max_count >= 0;
    if (!p && !_) {
      r.mesh_lod = 0, r.texture_lod = 0;
      return;
    }
    p || (a = !0, l = 0);
    const I = this.renderer.domElement.clientHeight || this.renderer.domElement.height;
    let G = e.geometry.boundingBox;
    if (e.type === "SkinnedMesh") {
      const c = e;
      if (!c.boundingBox)
        c.computeBoundingBox();
      else if (this.skinnedMeshAutoUpdateBoundsInterval > 0) {
        if (!c[D.$skinnedMeshBoundsOffset]) {
          const O = D.skinnedMeshBoundsFrameOffsetCounter++;
          c[D.$skinnedMeshBoundsOffset] = O;
        }
        const x = c[D.$skinnedMeshBoundsOffset];
        if ((s.frames + x) % this.skinnedMeshAutoUpdateBoundsInterval === 0) {
          const O = Z(c), B = c.geometry;
          O && (c.geometry = O), c.computeBoundingBox(), c.geometry = B;
        }
      }
      G = c.boundingBox;
    }
    if (G) {
      const c = t;
      if (e.geometry.attributes.color && e.geometry.attributes.color.count < 100 && e.geometry.boundingSphere) {
        this._sphere.copy(e.geometry.boundingSphere), this._sphere.applyMatrix4(e.matrixWorld);
        const f = t.getWorldPosition(this._tempWorldPosition);
        if (this._sphere.containsPoint(f)) {
          r.mesh_lod = 0, r.texture_lod = 0;
          return;
        }
      }
      if (this._tempBox.copy(G), this._tempBox.applyMatrix4(e.matrixWorld), c.isPerspectiveCamera && D.isInside(this._tempBox, this.projectionScreenMatrix)) {
        r.mesh_lod = 0, r.texture_lod = 0;
        return;
      }
      if (this._tempBox.applyMatrix4(this.projectionScreenMatrix), this.renderer.xr.enabled && c.isPerspectiveCamera && c.fov > 70) {
        const f = this._tempBox.min, h = this._tempBox.max;
        let v = f.x, b = f.y, $ = h.x, j = h.y;
        const ee = 2, ie = 1.5, te = (f.x + h.x) * 0.5, se = (f.y + h.y) * 0.5;
        v = (v - te) * ee + te, b = (b - se) * ee + se, $ = ($ - te) * ee + te, j = (j - se) * ee + se;
        const Be = v < 0 && $ > 0 ? 0 : Math.min(Math.abs(f.x), Math.abs(h.x)), $e = b < 0 && j > 0 ? 0 : Math.min(Math.abs(f.y), Math.abs(h.y)), ae = Math.max(Be, $e);
        s.lastCentrality = (ie - ae) * (ie - ae) * (ie - ae);
      } else
        s.lastCentrality = 1;
      const x = this._tempBox.getSize(this._tempBoxSize);
      x.multiplyScalar(0.5), screen.availHeight > 0 && I > 0 && x.multiplyScalar(I / screen.availHeight), t.isPerspectiveCamera ? x.x *= t.aspect : t.isOrthographicCamera;
      const O = t.matrixWorldInverse, B = this._tempBox2;
      B.copy(G), B.applyMatrix4(e.matrixWorld), B.applyMatrix4(O);
      const M = B.getSize(this._tempBox2Size), z = Math.max(M.x, M.y);
      if (Math.max(x.x, x.y) != 0 && z != 0 && (x.z = M.z / Math.max(M.x, M.y) * Math.max(x.x, x.y)), s.lastScreenCoverage = Math.max(x.x, x.y, x.z), s.lastScreenspaceVolume.copy(x), s.lastScreenCoverage *= s.lastCentrality, k && D.debugDrawLine) {
        const f = this.tempMatrix.copy(this.projectionScreenMatrix);
        f.invert();
        const h = D.corner0, v = D.corner1, b = D.corner2, $ = D.corner3;
        h.copy(this._tempBox.min), v.copy(this._tempBox.max), v.x = h.x, b.copy(this._tempBox.max), b.y = h.y, $.copy(this._tempBox.max);
        const j = (h.z + $.z) * 0.5;
        h.z = v.z = b.z = $.z = j, h.applyMatrix4(f), v.applyMatrix4(f), b.applyMatrix4(f), $.applyMatrix4(f), D.debugDrawLine(h, v, 255), D.debugDrawLine(h, b, 255), D.debugDrawLine(v, $, 255), D.debugDrawLine(b, $, 255);
      }
      let w = 999;
      if (u && s.lastScreenCoverage > 0)
        for (let f = 0; f < u.length; f++) {
          const h = u[f], b = (h.densities?.[d] || h.density || 1e-5) / s.lastScreenCoverage;
          if (d > 0 && Me() && !h.densities && !globalThis["NEEDLE:MISSING_LOD_PRIMITIVE_DENSITIES"] && (window["NEEDLE:MISSING_LOD_PRIMITIVE_DENSITIES"] = !0, console.warn("[Needle Progressive] Detected usage of mesh without primitive densities. This might cause incorrect LOD level selection: Consider re-optimizing your model by updating your Needle Integration, Needle glTF Pipeline or running optimization again on Needle Cloud.")), b < n) {
            w = f;
            break;
          }
        }
      w < l && (l = w, a = !0);
    }
    if (a ? r.mesh_lod = l : r.mesh_lod = s.lastLodLevel_Mesh, k && r.mesh_lod != s.lastLodLevel_Mesh) {
      const x = u?.[r.mesh_lod];
      x && console.log(`Mesh LOD changed: ${s.lastLodLevel_Mesh} → ${r.mesh_lod} (density: ${x.densities?.[d].toFixed(0)}) | ${e.name}`);
    }
    if (_) {
      const c = "saveData" in globalThis.navigator && globalThis.navigator.saveData === !0;
      if (s.lastLodLevel_Texture < 0) {
        if (r.texture_lod = L.max_count - 1, k) {
          const x = L.lods[L.max_count - 1];
          k && console.log(`First Texture LOD ${r.texture_lod} (${x.max_height}px) - ${e.name}`);
        }
      } else {
        const x = s.lastScreenspaceVolume.x + s.lastScreenspaceVolume.y + s.lastScreenspaceVolume.z;
        let O = s.lastScreenCoverage * 4;
        this.context?.engine === "model-viewer" && (O *= 1.5);
        const M = I / window.devicePixelRatio * O;
        let z = !1;
        for (let S = L.lods.length - 1; S >= 0; S--) {
          const w = L.lods[S];
          if (!(c && w.max_height >= 2048) && !(Ie() && w.max_height > 4096) && (w.max_height > M || !z && S === 0)) {
            if (z = !0, r.texture_lod = S, k && r.texture_lod < s.lastLodLevel_Texture) {
              const m = w.max_height;
              console.log(`Texture LOD changed: ${s.lastLodLevel_Texture} → ${r.texture_lod} = ${m}px 
Screensize: ${M.toFixed(0)}px, Coverage: ${(100 * s.lastScreenCoverage).toFixed(2)}%, Volume ${x.toFixed(1)} 
${e.name}`);
            }
            break;
          }
        }
      }
    } else
      r.texture_lod = 0;
  }
};
class mt {
  frames = 0;
  lastLodLevel_Mesh = -1;
  lastLodLevel_Texture = -1;
  lastScreenCoverage = 0;
  lastScreenspaceVolume = new A();
  lastCentrality = 0;
}
const ve = Symbol("NEEDLE_mesh_lod"), re = Symbol("NEEDLE_texture_lod");
let he = null;
function Ce() {
  const i = yt();
  i && (i.mapURLs(function(t) {
    return De(), t;
  }), De(), he?.disconnect(), he = new MutationObserver((t) => {
    t.forEach((e) => {
      e.addedNodes.forEach((s) => {
        s instanceof HTMLElement && s.tagName.toLowerCase() === "model-viewer" && Re(s);
      });
    });
  }), he.observe(document, { childList: !0, subtree: !0 }));
}
function yt() {
  if (typeof customElements > "u") return null;
  const i = customElements.get("model-viewer");
  return i || (customElements.whenDefined("model-viewer").then(() => {
    console.debug("[gltf-progressive] model-viewer defined"), Ce();
  }), null);
}
function De() {
  if (typeof document > "u") return;
  document.querySelectorAll("model-viewer").forEach((t) => {
    Re(t);
  });
}
const be = /* @__PURE__ */ new WeakSet();
let xt = 0;
function Re(i) {
  if (!i || be.has(i))
    return null;
  be.add(i), console.debug("[gltf-progressive] found new model-viewer..." + ++xt + `
`, i.getAttribute("src"));
  let t = null, e = null, s = null;
  for (let n = i; n != null; n = Object.getPrototypeOf(n)) {
    const r = Object.getOwnPropertySymbols(n), o = r.find((u) => u.toString() == "Symbol(renderer)"), l = r.find((u) => u.toString() == "Symbol(scene)"), a = r.find((u) => u.toString() == "Symbol(needsRender)");
    !t && o != null && (t = i[o].threeRenderer), !e && l != null && (e = i[l]), !s && a != null && (s = i[a]);
  }
  if (t && e) {
    let n = function() {
      if (s) {
        let o = 0, l = setInterval(() => {
          if (o++ > 5) {
            clearInterval(l);
            return;
          }
          s?.call(i);
        }, 300);
      }
    };
    console.debug("[gltf-progressive] setup model-viewer");
    const r = oe.get(t, { engine: "model-viewer" });
    return oe.addPlugin(new wt()), r.enable(), r.addEventListener("changed", () => {
      s?.call(i);
    }), i.addEventListener("model-visibility", (o) => {
      o.detail.visible && s?.call(i);
    }), i.addEventListener("load", () => {
      n();
    }), () => {
      r.disable();
    };
  }
  return null;
}
class wt {
  _didWarnAboutMissingUrl = !1;
  onBeforeUpdateLOD(t, e, s, n) {
    this.tryParseMeshLOD(e, n), this.tryParseTextureLOD(e, n);
  }
  getUrl(t) {
    if (!t)
      return null;
    let e = t.getAttribute("src");
    return e || (e = t.src), e || (this._didWarnAboutMissingUrl || console.warn("No url found in modelviewer", t), this._didWarnAboutMissingUrl = !0), e;
  }
  tryGetCurrentGLTF(t) {
    return t._currentGLTF;
  }
  tryGetCurrentModelViewer(t) {
    return t.element;
  }
  tryParseTextureLOD(t, e) {
    if (e[re] == !0) return;
    e[re] = !0;
    const s = this.tryGetCurrentGLTF(t), n = this.tryGetCurrentModelViewer(t), r = this.getUrl(n);
    if (r && s && e.material) {
      let o = function(a) {
        if (a[re] == !0) return;
        a[re] = !0, a.userData && (a.userData.LOD = -1);
        const u = Object.keys(a);
        for (let d = 0; d < u.length; d++) {
          const p = u[d], L = a[p];
          if (L?.isTexture === !0) {
            const _ = L.userData?.associations?.textures;
            if (_ == null) continue;
            const I = s.parser.json.textures[_];
            if (!I) {
              console.warn("Texture data not found for texture index " + _);
              continue;
            }
            if (I?.extensions?.[F]) {
              const G = I.extensions[F];
              G && r && y.registerTexture(r, L, G.lods.length, _, G);
            }
          }
        }
      };
      const l = e.material;
      if (Array.isArray(l)) for (const a of l) o(a);
      else o(l);
    }
  }
  tryParseMeshLOD(t, e) {
    if (e[ve] == !0) return;
    e[ve] = !0;
    const s = this.tryGetCurrentModelViewer(t), n = this.getUrl(s);
    if (!n)
      return;
    const r = e.userData?.gltfExtensions?.[F];
    if (r && n) {
      const o = e.uuid;
      y.registerMesh(n, o, e, 0, r.lods.length, r);
    }
  }
}
function Lt(...i) {
  let t, e, s, n;
  switch (i.length) {
    case 2:
      [s, e] = i, n = {};
      break;
    case 3:
      [s, e, n] = i;
      break;
    case 4:
      [t, e, s, n] = i;
      break;
    default:
      throw new Error("Invalid arguments");
  }
  we(e), Te(s), Ae(s, {
    progressive: !0,
    ...n?.hints
  }), s.register((o) => new y(o));
  const r = oe.get(e);
  return n?.enableLODsManager !== !1 && r.enable(), r;
}
Ce();
if (!nt) {
  const i = {
    gltfProgressive: {
      useNeedleProgressive: Lt,
      LODsManager: oe,
      configureLoader: Ae,
      getRaycastMesh: Z,
      useRaycastMeshes: it
    }
  };
  if (!globalThis.Needle)
    globalThis.Needle = i;
  else
    for (const t in i)
      globalThis.Needle[t] = i[t];
}
export {
  oe as LODsManager,
  y as NEEDLE_progressive,
  Te as addDracoAndKTX2Loaders,
  Ae as configureLoader,
  we as createLoaders,
  Z as getRaycastMesh,
  Je as setDracoDecoderLocation,
  Ze as setKTX2TranscoderLocation
};
