From ce03c05d845fff6ebb0bc9301c146f7e454e180b Mon Sep 17 00:00:00 2001 From: Jens Neuber Date: Thu, 19 Nov 2026 13:25:47 +0100 Subject: [PATCH] Add 3D roof view card for optimizer power The integration now serves solaredge-roof-card and loads it in every frontend session. The card shows the building in 3D with the current power in W and the Panel-Position on every panel; the colour runs from dark (0 W) to bright (Skalenmaximum, default 460 W). Failed panels are grey and hatched, a tap opens the more-info dialog. scripts/convert_portal_layout.py turns the SolarEdge portal's physical layout and site model into the card's layout once, so nothing depends on the portal at runtime. Co-Authored-By: Claude Opus 5.5 --- GLOSSARY.md | 27 + README.md | 57 + .../solaredge_optimizers/__init__.py | 10 + .../solaredge_optimizers/frontend.py | 35 + .../frontend/solaredge-roof-card.js | 20227 ++++++++++++++++ .../solaredge_optimizers/manifest.json | 10 +- frontend/.gitignore | 1 + frontend/bun.lock | 241 + frontend/package.json | 19 + frontend/src/geometry.test.ts | 30 + frontend/src/geometry.ts | 71 + frontend/src/panel-state.test.ts | 96 + frontend/src/panel-state.ts | 119 + frontend/src/scene.ts | 311 + frontend/src/solaredge-roof-card.ts | 192 + frontend/src/types.ts | 40 + frontend/tsconfig.json | 13 + frontend/vite.config.ts | 19 + pyproject.toml | 2 +- scripts/convert_portal_layout.py | 392 + tests/test_convert_portal_layout.py | 107 + tests/test_frontend.py | 33 + uv.lock | 4 +- 23 files changed, 22051 insertions(+), 5 deletions(-) create mode 100644 GLOSSARY.md create mode 100644 custom_components/solaredge_optimizers/frontend.py create mode 100644 custom_components/solaredge_optimizers/frontend/solaredge-roof-card.js create mode 100644 frontend/.gitignore create mode 100644 frontend/bun.lock create mode 100644 frontend/package.json create mode 100644 frontend/src/geometry.test.ts create mode 100644 frontend/src/geometry.ts create mode 100644 frontend/src/panel-state.test.ts create mode 100644 frontend/src/panel-state.ts create mode 100644 frontend/src/scene.ts create mode 100644 frontend/src/solaredge-roof-card.ts create mode 100644 frontend/src/types.ts create mode 100644 frontend/tsconfig.json create mode 100644 frontend/vite.config.ts create mode 100644 scripts/convert_portal_layout.py create mode 100644 tests/test_convert_portal_layout.py create mode 100644 tests/test_frontend.py diff --git a/GLOSSARY.md b/GLOSSARY.md new file mode 100644 index 0000000..1f03610 --- /dev/null +++ b/GLOSSARY.md @@ -0,0 +1,27 @@ +# Glossary + +## Photovoltaik + +**Panel** +Ein Solarmodul samt dem SolarEdge-Optimizer darunter, als eine Einheit betrachtet. Jedes Panel liefert eine eigene Leistung. +_Avoid_: Modul, Optimizer (wenn das Ganze gemeint ist) + +**Panel-Position** +Die Kennung eines Panels in der Form Wechselrichter.String.Modul, z. B. `1.2.7`. +_Avoid_: Optimizer-ID, Seriennummer + +**Dachfläche** +Eine zusammenhängende, gleich geneigte und gleich ausgerichtete Fläche, auf der Panels liegen (west1, west2, gaube, süd, ost1, ost2). In der Integration `solaredge_optimizers` heißt sie „Area“. +_Avoid_: Area, Feld, Teilfläche + +**Aktuelle Leistung** +Die zuletzt gemessene Leistung eines Panels in Watt. Sie ist bis zu 10 Minuten alt, weil das Portal nicht häufiger abgefragt wird. +_Avoid_: Echtzeitwert, Ertrag (das ist Energie in Wh) + +**Skalenmaximum** +Die Leistung, bei der ein Panel in der Dachansicht die hellste Farbe erreicht. Sie ist einstellbar und nicht dasselbe wie die Nennleistung des Moduls. +_Avoid_: Peak, Wp, Maximalleistung + +**Ausgefallenes Panel** +Ein Panel, dessen Optimizer keinen Wert liefert. Das ist nicht dasselbe wie ein Panel, das 0 W meldet, etwa nachts. +_Avoid_: inaktives Panel, Panel mit 0 W diff --git a/README.md b/README.md index d24bcd8..8451ce3 100644 --- a/README.md +++ b/README.md @@ -87,6 +87,52 @@ Flächen werden beim Speichern abgewiesen. Für Site `4886699` sind `west1`, `west2`, `gaube`, `süd`, `ost1` und `ost2` bereits als Startwert hinterlegt. Mit `{}` können alle Flächensensoren deaktiviert werden. +## Dachansicht (solaredge-roof-card) + +Die Integration bringt eine Lovelace-Karte mit, die das Gebäude in 3D zeigt. +Auf jedem Panel stehen die aktuelle Leistung in W und die Panel-Position. Die +Integration lädt die Karte beim Start selbst; eine Dashboard-Ressource ist +nicht nötig. + +- Die Farbe läuft von dunkel (0 W) bis hell (`max_power`, Standard 460 W). +- Ausgefallene Panels (kein Wert oder mehr als 30 Minuten älter als die neueste + Messung) sind grau schraffiert mit rotem Rand. +- Ein Tipp auf ein Panel öffnet den Detaildialog der Leistungsentität. +- „Stand“ ist der Zeitpunkt der neuesten Messung. + +Die Karte findet die Entitäten über das Attribut `optimizer_id`. Die Geometrie +steht in der Kartenkonfiguration: + +```yaml +type: custom:solaredge-roof-card +title: Dach # optional +max_power: 460 # optional, Skalenmaximum in W +layout: + roofs: + - name: west1 + outline: [[x, y, z], ...] # Meter, x = Ost, y = Nord, z = Höhe + panels: + - id: "1.1.1" + roof: west1 + corners: [[x, y, z], ...] # unten links, unten rechts, oben rechts, oben links +``` + +### Layout aus dem SolarEdge-Portal erzeugen + +Das Portal liefert unter +`GET /services/layout/physical/site/{siteId}` das physische Layout. Dessen +`awsJsonModelDownloadLink` zeigt auf das 3D-Modell, das das Portal selbst +rendert. Beide Dokumente einmalig speichern (z. B. mit dem Portal-Client aus +`solaredge-optimizers/packages/solaredgeapi`) und umrechnen: + +```shell +python scripts/convert_portal_layout.py physical.json model.json \ + --areas areas.json > card.yaml +``` + +`areas.json` hat dasselbe Format wie die Flächen-Zuordnung und benennt die +Dachflächen. Die Ausgabe ist die vollständige Kartenkonfiguration. + ## Entwicklung ```shell @@ -94,3 +140,14 @@ uv sync uv run ruff check . uv run pytest ``` + +Die Karte liegt unter `frontend/`. Das gebaute Bundle in +`custom_components/solaredge_optimizers/frontend/` wird mit eingecheckt, damit +die Installation ohne Build auskommt: + +```shell +cd frontend +bun install +bun run test +bun run build +``` diff --git a/custom_components/solaredge_optimizers/__init__.py b/custom_components/solaredge_optimizers/__init__.py index 6a74a03..0921332 100644 --- a/custom_components/solaredge_optimizers/__init__.py +++ b/custom_components/solaredge_optimizers/__init__.py @@ -7,8 +7,10 @@ from datetime import timedelta from homeassistant.config_entries import ConfigEntry from homeassistant.const import CONF_URL, Platform from homeassistant.core import HomeAssistant +from homeassistant.helpers import config_validation as cv from homeassistant.helpers import device_registry as dr from homeassistant.helpers.aiohttp_client import async_get_clientsession +from homeassistant.helpers.typing import ConfigType from .api import SolarEdgeOptimizerApiClient from .const import ( @@ -19,11 +21,19 @@ from .const import ( LOGGER, ) from .coordinator import SolarEdgeOptimizerCoordinator +from .frontend import async_register_card PLATFORMS = [Platform.SENSOR] +CONFIG_SCHEMA = cv.config_entry_only_config_schema(DOMAIN) type SolarEdgeOptimizerConfigEntry = ConfigEntry[SolarEdgeOptimizerCoordinator] +async def async_setup(hass: HomeAssistant, config: ConfigType) -> bool: + """Serve the solaredge-roof-card.""" + await async_register_card(hass) + return True + + async def async_migrate_entry( hass: HomeAssistant, entry: SolarEdgeOptimizerConfigEntry ) -> bool: diff --git a/custom_components/solaredge_optimizers/frontend.py b/custom_components/solaredge_optimizers/frontend.py new file mode 100644 index 0000000..3025149 --- /dev/null +++ b/custom_components/solaredge_optimizers/frontend.py @@ -0,0 +1,35 @@ +"""Serve the solaredge-roof-card from the integration.""" + +from __future__ import annotations + +import hashlib +from pathlib import Path + +from homeassistant.components.frontend import add_extra_js_url +from homeassistant.components.http import StaticPathConfig +from homeassistant.core import HomeAssistant + +from .const import DOMAIN, LOGGER + +CARD_FILE = Path(__file__).parent / "frontend" / "solaredge-roof-card.js" +CARD_URL = f"/{DOMAIN}/solaredge-roof-card.js" + + +def _file_hash(path: Path) -> str: + return hashlib.sha256(path.read_bytes()).hexdigest()[:12] + + +async def async_register_card(hass: HomeAssistant) -> None: + """Serve the card and load it in every frontend session.""" + if hass.http is None or "frontend" not in hass.config.components: + LOGGER.debug("Frontend not loaded, solaredge-roof-card is not registered") + return + if not CARD_FILE.is_file(): + LOGGER.warning("solaredge-roof-card bundle missing at %s", CARD_FILE) + return + version = await hass.async_add_executor_job(_file_hash, CARD_FILE) + await hass.http.async_register_static_paths( + [StaticPathConfig(CARD_URL, str(CARD_FILE), cache_headers=True)] + ) + # The hash in the URL makes browsers load a new bundle after an update. + add_extra_js_url(hass, f"{CARD_URL}?v={version}") diff --git a/custom_components/solaredge_optimizers/frontend/solaredge-roof-card.js b/custom_components/solaredge_optimizers/frontend/solaredge-roof-card.js new file mode 100644 index 0000000..47d63e3 --- /dev/null +++ b/custom_components/solaredge_optimizers/frontend/solaredge-roof-card.js @@ -0,0 +1,20227 @@ +function jo(i, t) { + const e = new Set(t), n = /* @__PURE__ */ new Map(); + for (const s of Object.values(i)) { + const r = s.attributes.optimizer_id; + typeof r == "string" && e.has(r) && s.attributes.device_class === "power" && s.entity_id.startsWith("sensor.") && n.set(r, s.entity_id); + } + return n; +} +function Zo(i) { + if (typeof i != "string") return; + const t = Date.parse(i); + return Number.isNaN(t) ? void 0 : t; +} +function $o(i, t, e) { + const n = /* @__PURE__ */ new Map(); + let s; + for (const r of e) { + const a = t.get(r), o = a ? i[a] : void 0; + if (!a || !o) { + n.set(r, { status: "failed", entityId: a }); + continue; + } + const c = Number(o.state); + if (o.state === "" || !Number.isFinite(c)) { + n.set(r, { status: "failed", entityId: a }); + continue; + } + const l = Zo(o.attributes.last_measurement); + l !== void 0 && (s === void 0 || l > s) && (s = l), n.set(r, { status: "ok", entityId: a, power: c, lastMeasurement: l }); + } + if (s !== void 0) + for (const [r, a] of n) + a.status === "ok" && a.lastMeasurement !== void 0 && s - a.lastMeasurement > 18e5 && n.set(r, { status: "failed", entityId: a.entityId }); + return { panels: n, newestMeasurement: s }; +} +const Jn = [ + [0, [22, 32, 58]], + [0.5, [44, 104, 214]], + [1, [255, 214, 74]] +]; +function Jo(i, t) { + const e = Math.min(1, Math.max(0, t > 0 ? i / t : 0)); + for (let n = 1; n < Jn.length; n++) { + const [s, r] = Jn[n], [a, o] = Jn[n - 1]; + if (e <= s) { + const c = (e - a) / (s - a); + return [0, 1, 2].map((l) => Math.round(o[l] + (r[l] - o[l]) * c)); + } + } + return Jn[Jn.length - 1][1]; +} +function Qo([i, t, e]) { + return (0.2126 * i + 0.7152 * t + 0.0722 * e) / 255 > 0.55 ? "#1b1b1f" : "#ffffff"; +} +function tl(i) { + return `${Math.round(i)} W`; +} +function el() { + return Jn.map(([i, [t, e, n]]) => `rgb(${t},${e},${n}) ${i * 100}%`).join(", "); +} +/** + * @license + * Copyright 2010-2025 Three.js Authors + * SPDX-License-Identifier: MIT + */ +const Br = "180", ei = { ROTATE: 0, DOLLY: 1, PAN: 2 }, Qn = { ROTATE: 0, PAN: 1, DOLLY_PAN: 2, DOLLY_ROTATE: 3 }, nl = 0, oa = 1, il = 2, fo = 1, sl = 2, nn = 3, vn = 0, Ae = 1, De = 2, _n = 0, ni = 1, la = 2, ca = 3, ha = 4, rl = 5, Cn = 100, al = 101, ol = 102, ll = 103, cl = 104, hl = 200, ul = 201, dl = 202, fl = 203, Ks = 204, js = 205, pl = 206, ml = 207, _l = 208, gl = 209, vl = 210, xl = 211, Ml = 212, Sl = 213, El = 214, Zs = 0, $s = 1, Js = 2, si = 3, Qs = 4, tr = 5, er = 6, nr = 7, zr = 0, yl = 1, Tl = 2, gn = 0, bl = 1, Al = 2, Rl = 3, wl = 4, Cl = 5, Pl = 6, Dl = 7, po = 300, ri = 301, ai = 302, ir = 303, sr = 304, ls = 306, rr = 1e3, Dn = 1001, ar = 1002, Ge = 1003, Ll = 1004, Ci = 1005, Xe = 1006, fs = 1007, Ln = 1008, Ke = 1009, mo = 1010, _o = 1011, gi = 1012, Hr = 1013, Un = 1014, sn = 1015, Ei = 1016, Vr = 1017, Gr = 1018, vi = 1020, go = 35902, vo = 35899, xo = 1021, Mo = 1022, Ve = 1023, xi = 1026, Mi = 1027, So = 1028, kr = 1029, Eo = 1030, Wr = 1031, Xr = 1033, Qi = 33776, ts = 33777, es = 33778, ns = 33779, or = 35840, lr = 35841, cr = 35842, hr = 35843, ur = 36196, dr = 37492, fr = 37496, pr = 37808, mr = 37809, _r = 37810, gr = 37811, vr = 37812, xr = 37813, Mr = 37814, Sr = 37815, Er = 37816, yr = 37817, Tr = 37818, br = 37819, Ar = 37820, Rr = 37821, wr = 36492, Cr = 36494, Pr = 36495, Dr = 36283, Lr = 36284, Ur = 36285, Ir = 36286, Ul = 3200, Il = 3201, yo = 0, Nl = 1, mn = "", Te = "srgb", oi = "srgb-linear", rs = "linear", qt = "srgb", Bn = 7680, ua = 519, Fl = 512, Ol = 513, Bl = 514, To = 515, zl = 516, Hl = 517, Vl = 518, Gl = 519, da = 35044, fa = "300 es", Ye = 2e3, as = 2001; +class Fn { + /** + * 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(t, e) { + this._listeners === void 0 && (this._listeners = {}); + const n = this._listeners; + n[t] === void 0 && (n[t] = []), n[t].indexOf(e) === -1 && n[t].push(e); + } + /** + * 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(t, e) { + const n = this._listeners; + return n === void 0 ? !1 : n[t] !== void 0 && n[t].indexOf(e) !== -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(t, e) { + const n = this._listeners; + if (n === void 0) return; + const s = n[t]; + if (s !== void 0) { + const r = s.indexOf(e); + r !== -1 && s.splice(r, 1); + } + } + /** + * Dispatches an event object. + * + * @param {Object} event - The event that gets fired. + */ + dispatchEvent(t) { + const e = this._listeners; + if (e === void 0) return; + const n = e[t.type]; + if (n !== void 0) { + t.target = this; + const s = n.slice(0); + for (let r = 0, a = s.length; r < a; r++) + s[r].call(this, t); + t.target = null; + } + } +} +const me = ["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"], is = Math.PI / 180, Nr = 180 / Math.PI; +function yi() { + const i = Math.random() * 4294967295 | 0, t = Math.random() * 4294967295 | 0, e = Math.random() * 4294967295 | 0, n = Math.random() * 4294967295 | 0; + return (me[i & 255] + me[i >> 8 & 255] + me[i >> 16 & 255] + me[i >> 24 & 255] + "-" + me[t & 255] + me[t >> 8 & 255] + "-" + me[t >> 16 & 15 | 64] + me[t >> 24 & 255] + "-" + me[e & 63 | 128] + me[e >> 8 & 255] + "-" + me[e >> 16 & 255] + me[e >> 24 & 255] + me[n & 255] + me[n >> 8 & 255] + me[n >> 16 & 255] + me[n >> 24 & 255]).toLowerCase(); +} +function Bt(i, t, e) { + return Math.max(t, Math.min(e, i)); +} +function kl(i, t) { + return (i % t + t) % t; +} +function ps(i, t, e) { + return (1 - e) * i + e * t; +} +function ui(i, t) { + switch (t.constructor) { + case Float32Array: + return i; + case Uint32Array: + return i / 4294967295; + case Uint16Array: + return i / 65535; + case Uint8Array: + return i / 255; + case Int32Array: + return Math.max(i / 2147483647, -1); + case Int16Array: + return Math.max(i / 32767, -1); + case Int8Array: + return Math.max(i / 127, -1); + default: + throw new Error("Invalid component type."); + } +} +function Ee(i, t) { + switch (t.constructor) { + case Float32Array: + return i; + case Uint32Array: + return Math.round(i * 4294967295); + case Uint16Array: + return Math.round(i * 65535); + case Uint8Array: + return Math.round(i * 255); + case Int32Array: + return Math.round(i * 2147483647); + case Int16Array: + return Math.round(i * 32767); + case Int8Array: + return Math.round(i * 127); + default: + throw new Error("Invalid component type."); + } +} +const Wl = { + DEG2RAD: is +}; +class Ct { + /** + * 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(t = 0, e = 0) { + Ct.prototype.isVector2 = !0, this.x = t, this.y = e; + } + /** + * Alias for {@link Vector2#x}. + * + * @type {number} + */ + get width() { + return this.x; + } + set width(t) { + this.x = t; + } + /** + * Alias for {@link Vector2#y}. + * + * @type {number} + */ + get height() { + return this.y; + } + set height(t) { + this.y = t; + } + /** + * 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(t, e) { + return this.x = t, this.y = e, 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(t) { + return this.x = t, this.y = t, 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(t) { + return this.x = t, 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(t) { + return this.y = t, 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(t, e) { + switch (t) { + case 0: + this.x = e; + break; + case 1: + this.y = e; + break; + default: + throw new Error("index is out of range: " + t); + } + 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(t) { + switch (t) { + case 0: + return this.x; + case 1: + return this.y; + default: + throw new Error("index is out of range: " + t); + } + } + /** + * 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(t) { + return this.x = t.x, this.y = t.y, this; + } + /** + * Adds the given vector to this instance. + * + * @param {Vector2} v - The vector to add. + * @return {Vector2} A reference to this vector. + */ + add(t) { + return this.x += t.x, this.y += t.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(t) { + return this.x += t, this.y += t, 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(t, e) { + return this.x = t.x + e.x, this.y = t.y + e.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(t, e) { + return this.x += t.x * e, this.y += t.y * e, this; + } + /** + * Subtracts the given vector from this instance. + * + * @param {Vector2} v - The vector to subtract. + * @return {Vector2} A reference to this vector. + */ + sub(t) { + return this.x -= t.x, this.y -= t.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(t) { + return this.x -= t, this.y -= t, 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(t, e) { + return this.x = t.x - e.x, this.y = t.y - e.y, this; + } + /** + * Multiplies the given vector with this instance. + * + * @param {Vector2} v - The vector to multiply. + * @return {Vector2} A reference to this vector. + */ + multiply(t) { + return this.x *= t.x, this.y *= t.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(t) { + return this.x *= t, this.y *= t, this; + } + /** + * Divides this instance by the given vector. + * + * @param {Vector2} v - The vector to divide. + * @return {Vector2} A reference to this vector. + */ + divide(t) { + return this.x /= t.x, this.y /= t.y, this; + } + /** + * Divides this vector by the given scalar. + * + * @param {number} scalar - The scalar to divide. + * @return {Vector2} A reference to this vector. + */ + divideScalar(t) { + return this.multiplyScalar(1 / t); + } + /** + * 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(t) { + const e = this.x, n = this.y, s = t.elements; + return this.x = s[0] * e + s[3] * n + s[6], this.y = s[1] * e + s[4] * n + s[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(t) { + return this.x = Math.min(this.x, t.x), this.y = Math.min(this.y, t.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(t) { + return this.x = Math.max(this.x, t.x), this.y = Math.max(this.y, t.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(t, e) { + return this.x = Bt(this.x, t.x, e.x), this.y = Bt(this.y, t.y, e.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(t, e) { + return this.x = Bt(this.x, t, e), this.y = Bt(this.y, t, e), 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(t, e) { + const n = this.length(); + return this.divideScalar(n || 1).multiplyScalar(Bt(n, t, e)); + } + /** + * 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(t) { + return this.x * t.x + this.y * t.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(t) { + return this.x * t.y - this.y * t.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(t) { + const e = Math.sqrt(this.lengthSq() * t.lengthSq()); + if (e === 0) return Math.PI / 2; + const n = this.dot(t) / e; + return Math.acos(Bt(n, -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(t) { + return Math.sqrt(this.distanceToSquared(t)); + } + /** + * 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(t) { + const e = this.x - t.x, n = this.y - t.y; + return e * e + n * n; + } + /** + * 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(t) { + return Math.abs(this.x - t.x) + Math.abs(this.y - t.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(t) { + return this.normalize().multiplyScalar(t); + } + /** + * 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(t, e) { + return this.x += (t.x - this.x) * e, this.y += (t.y - this.y) * e, 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(t, e, n) { + return this.x = t.x + (e.x - t.x) * n, this.y = t.y + (e.y - t.y) * n, 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(t) { + return t.x === this.x && t.y === this.y; + } + /** + * Sets this vector's x value to be `array[ offset ]` and y + * value to be `array[ offset + 1 ]`. + * + * @param {Array} 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(t, e = 0) { + return this.x = t[e], this.y = t[e + 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} [array=[]] - The target array holding the vector components. + * @param {number} [offset=0] - Index of the first element in the array. + * @return {Array} The vector components. + */ + toArray(t = [], e = 0) { + return t[e] = this.x, t[e + 1] = this.y, t; + } + /** + * 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(t, e) { + return this.x = t.getX(e), this.y = t.getY(e), 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(t, e) { + const n = Math.cos(e), s = Math.sin(e), r = this.x - t.x, a = this.y - t.y; + return this.x = r * n - a * s + t.x, this.y = r * s + a * n + t.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 In { + /** + * 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(t = 0, e = 0, n = 0, s = 1) { + this.isQuaternion = !0, this._x = t, this._y = e, this._z = n, this._w = s; + } + /** + * Interpolates between two quaternions via SLERP. This implementation assumes the + * quaternion data are managed in flat arrays. + * + * @param {Array} dst - The destination array. + * @param {number} dstOffset - An offset into the destination array. + * @param {Array} src0 - The source array of the first quaternion. + * @param {number} srcOffset0 - An offset into the first source array. + * @param {Array} 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(t, e, n, s, r, a, o) { + let c = n[s + 0], l = n[s + 1], u = n[s + 2], d = n[s + 3]; + const f = r[a + 0], m = r[a + 1], v = r[a + 2], x = r[a + 3]; + if (o === 0) { + t[e + 0] = c, t[e + 1] = l, t[e + 2] = u, t[e + 3] = d; + return; + } + if (o === 1) { + t[e + 0] = f, t[e + 1] = m, t[e + 2] = v, t[e + 3] = x; + return; + } + if (d !== x || c !== f || l !== m || u !== v) { + let p = 1 - o; + const h = c * f + l * m + u * v + d * x, A = h >= 0 ? 1 : -1, b = 1 - h * h; + if (b > Number.EPSILON) { + const D = Math.sqrt(b), P = Math.atan2(D, h * A); + p = Math.sin(p * P) / D, o = Math.sin(o * P) / D; + } + const y = o * A; + if (c = c * p + f * y, l = l * p + m * y, u = u * p + v * y, d = d * p + x * y, p === 1 - o) { + const D = 1 / Math.sqrt(c * c + l * l + u * u + d * d); + c *= D, l *= D, u *= D, d *= D; + } + } + t[e] = c, t[e + 1] = l, t[e + 2] = u, t[e + 3] = d; + } + /** + * Multiplies two quaternions. This implementation assumes the quaternion data are managed + * in flat arrays. + * + * @param {Array} dst - The destination array. + * @param {number} dstOffset - An offset into the destination array. + * @param {Array} src0 - The source array of the first quaternion. + * @param {number} srcOffset0 - An offset into the first source array. + * @param {Array} src1 - The source array of the second quaternion. + * @param {number} srcOffset1 - An offset into the second source array. + * @return {Array} The destination array. + * @see {@link Quaternion#multiplyQuaternions}. + */ + static multiplyQuaternionsFlat(t, e, n, s, r, a) { + const o = n[s], c = n[s + 1], l = n[s + 2], u = n[s + 3], d = r[a], f = r[a + 1], m = r[a + 2], v = r[a + 3]; + return t[e] = o * v + u * d + c * m - l * f, t[e + 1] = c * v + u * f + l * d - o * m, t[e + 2] = l * v + u * m + o * f - c * d, t[e + 3] = u * v - o * d - c * f - l * m, t; + } + /** + * The x value of this quaternion. + * + * @type {number} + * @default 0 + */ + get x() { + return this._x; + } + set x(t) { + this._x = t, this._onChangeCallback(); + } + /** + * The y value of this quaternion. + * + * @type {number} + * @default 0 + */ + get y() { + return this._y; + } + set y(t) { + this._y = t, this._onChangeCallback(); + } + /** + * The z value of this quaternion. + * + * @type {number} + * @default 0 + */ + get z() { + return this._z; + } + set z(t) { + this._z = t, this._onChangeCallback(); + } + /** + * The w value of this quaternion. + * + * @type {number} + * @default 1 + */ + get w() { + return this._w; + } + set w(t) { + this._w = t, 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(t, e, n, s) { + return this._x = t, this._y = e, this._z = n, this._w = s, 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(t) { + return this._x = t.x, this._y = t.y, this._z = t.z, this._w = t.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(t, e = !0) { + const n = t._x, s = t._y, r = t._z, a = t._order, o = Math.cos, c = Math.sin, l = o(n / 2), u = o(s / 2), d = o(r / 2), f = c(n / 2), m = c(s / 2), v = c(r / 2); + switch (a) { + case "XYZ": + this._x = f * u * d + l * m * v, this._y = l * m * d - f * u * v, this._z = l * u * v + f * m * d, this._w = l * u * d - f * m * v; + break; + case "YXZ": + this._x = f * u * d + l * m * v, this._y = l * m * d - f * u * v, this._z = l * u * v - f * m * d, this._w = l * u * d + f * m * v; + break; + case "ZXY": + this._x = f * u * d - l * m * v, this._y = l * m * d + f * u * v, this._z = l * u * v + f * m * d, this._w = l * u * d - f * m * v; + break; + case "ZYX": + this._x = f * u * d - l * m * v, this._y = l * m * d + f * u * v, this._z = l * u * v - f * m * d, this._w = l * u * d + f * m * v; + break; + case "YZX": + this._x = f * u * d + l * m * v, this._y = l * m * d + f * u * v, this._z = l * u * v - f * m * d, this._w = l * u * d - f * m * v; + break; + case "XZY": + this._x = f * u * d - l * m * v, this._y = l * m * d - f * u * v, this._z = l * u * v + f * m * d, this._w = l * u * d + f * m * v; + break; + default: + console.warn("THREE.Quaternion: .setFromEuler() encountered an unknown order: " + a); + } + return e === !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(t, e) { + const n = e / 2, s = Math.sin(n); + return this._x = t.x * s, this._y = t.y * s, this._z = t.z * s, this._w = Math.cos(n), 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(t) { + const e = t.elements, n = e[0], s = e[4], r = e[8], a = e[1], o = e[5], c = e[9], l = e[2], u = e[6], d = e[10], f = n + o + d; + if (f > 0) { + const m = 0.5 / Math.sqrt(f + 1); + this._w = 0.25 / m, this._x = (u - c) * m, this._y = (r - l) * m, this._z = (a - s) * m; + } else if (n > o && n > d) { + const m = 2 * Math.sqrt(1 + n - o - d); + this._w = (u - c) / m, this._x = 0.25 * m, this._y = (s + a) / m, this._z = (r + l) / m; + } else if (o > d) { + const m = 2 * Math.sqrt(1 + o - n - d); + this._w = (r - l) / m, this._x = (s + a) / m, this._y = 0.25 * m, this._z = (c + u) / m; + } else { + const m = 2 * Math.sqrt(1 + d - n - o); + this._w = (a - s) / m, this._x = (r + l) / m, this._y = (c + u) / m, this._z = 0.25 * m; + } + 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(t, e) { + let n = t.dot(e) + 1; + return n < 1e-8 ? (n = 0, Math.abs(t.x) > Math.abs(t.z) ? (this._x = -t.y, this._y = t.x, this._z = 0, this._w = n) : (this._x = 0, this._y = -t.z, this._z = t.y, this._w = n)) : (this._x = t.y * e.z - t.z * e.y, this._y = t.z * e.x - t.x * e.z, this._z = t.x * e.y - t.y * e.x, this._w = n), 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(t) { + return 2 * Math.acos(Math.abs(Bt(this.dot(t), -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(t, e) { + const n = this.angleTo(t); + if (n === 0) return this; + const s = Math.min(1, e / n); + return this.slerp(t, s), 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(t) { + return this._x * t._x + this._y * t._y + this._z * t._z + this._w * t._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 t = this.length(); + return t === 0 ? (this._x = 0, this._y = 0, this._z = 0, this._w = 1) : (t = 1 / t, this._x = this._x * t, this._y = this._y * t, this._z = this._z * t, this._w = this._w * t), this._onChangeCallback(), this; + } + /** + * Multiplies this quaternion by the given one. + * + * @param {Quaternion} q - The quaternion. + * @return {Quaternion} A reference to this quaternion. + */ + multiply(t) { + return this.multiplyQuaternions(this, t); + } + /** + * Pre-multiplies this quaternion by the given one. + * + * @param {Quaternion} q - The quaternion. + * @return {Quaternion} A reference to this quaternion. + */ + premultiply(t) { + return this.multiplyQuaternions(t, 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(t, e) { + const n = t._x, s = t._y, r = t._z, a = t._w, o = e._x, c = e._y, l = e._z, u = e._w; + return this._x = n * u + a * o + s * l - r * c, this._y = s * u + a * c + r * o - n * l, this._z = r * u + a * l + n * c - s * o, this._w = a * u - n * o - s * c - r * l, 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(t, e) { + if (e === 0) return this; + if (e === 1) return this.copy(t); + const n = this._x, s = this._y, r = this._z, a = this._w; + let o = a * t._w + n * t._x + s * t._y + r * t._z; + if (o < 0 ? (this._w = -t._w, this._x = -t._x, this._y = -t._y, this._z = -t._z, o = -o) : this.copy(t), o >= 1) + return this._w = a, this._x = n, this._y = s, this._z = r, this; + const c = 1 - o * o; + if (c <= Number.EPSILON) { + const m = 1 - e; + return this._w = m * a + e * this._w, this._x = m * n + e * this._x, this._y = m * s + e * this._y, this._z = m * r + e * this._z, this.normalize(), this; + } + const l = Math.sqrt(c), u = Math.atan2(l, o), d = Math.sin((1 - e) * u) / l, f = Math.sin(e * u) / l; + return this._w = a * d + this._w * f, this._x = n * d + this._x * f, this._y = s * d + this._y * f, this._z = r * d + this._z * f, 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(t, e, n) { + return this.copy(t).slerp(e, n); + } + /** + * Sets this quaternion to a uniformly random, normalized quaternion. + * + * @return {Quaternion} A reference to this quaternion. + */ + random() { + const t = 2 * Math.PI * Math.random(), e = 2 * Math.PI * Math.random(), n = Math.random(), s = Math.sqrt(1 - n), r = Math.sqrt(n); + return this.set( + s * Math.sin(t), + s * Math.cos(t), + r * Math.sin(e), + r * Math.cos(e) + ); + } + /** + * 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(t) { + return t._x === this._x && t._y === this._y && t._z === this._z && t._w === this._w; + } + /** + * Sets this quaternion's components from the given array. + * + * @param {Array} 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(t, e = 0) { + return this._x = t[e], this._y = t[e + 1], this._z = t[e + 2], this._w = t[e + 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} [array=[]] - The target array holding the quaternion components. + * @param {number} [offset=0] - Index of the first element in the array. + * @return {Array} The quaternion components. + */ + toArray(t = [], e = 0) { + return t[e] = this._x, t[e + 1] = this._y, t[e + 2] = this._z, t[e + 3] = this._w, t; + } + /** + * 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(t, e) { + return this._x = t.getX(e), this._y = t.getY(e), this._z = t.getZ(e), this._w = t.getW(e), 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} The serialized quaternion. + */ + toJSON() { + return this.toArray(); + } + _onChange(t) { + return this._onChangeCallback = t, this; + } + _onChangeCallback() { + } + *[Symbol.iterator]() { + yield this._x, yield this._y, yield this._z, yield this._w; + } +} +class N { + /** + * 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(t = 0, e = 0, n = 0) { + N.prototype.isVector3 = !0, this.x = t, this.y = e, this.z = n; + } + /** + * 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(t, e, n) { + return n === void 0 && (n = this.z), this.x = t, this.y = e, this.z = n, 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(t) { + return this.x = t, this.y = t, this.z = t, 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(t) { + return this.x = t, 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(t) { + return this.y = t, 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(t) { + return this.z = t, 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(t, e) { + switch (t) { + case 0: + this.x = e; + break; + case 1: + this.y = e; + break; + case 2: + this.z = e; + break; + default: + throw new Error("index is out of range: " + t); + } + 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(t) { + switch (t) { + case 0: + return this.x; + case 1: + return this.y; + case 2: + return this.z; + default: + throw new Error("index is out of range: " + t); + } + } + /** + * 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(t) { + return this.x = t.x, this.y = t.y, this.z = t.z, this; + } + /** + * Adds the given vector to this instance. + * + * @param {Vector3} v - The vector to add. + * @return {Vector3} A reference to this vector. + */ + add(t) { + return this.x += t.x, this.y += t.y, this.z += t.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(t) { + return this.x += t, this.y += t, this.z += t, 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(t, e) { + return this.x = t.x + e.x, this.y = t.y + e.y, this.z = t.z + e.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(t, e) { + return this.x += t.x * e, this.y += t.y * e, this.z += t.z * e, this; + } + /** + * Subtracts the given vector from this instance. + * + * @param {Vector3} v - The vector to subtract. + * @return {Vector3} A reference to this vector. + */ + sub(t) { + return this.x -= t.x, this.y -= t.y, this.z -= t.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(t) { + return this.x -= t, this.y -= t, this.z -= t, 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(t, e) { + return this.x = t.x - e.x, this.y = t.y - e.y, this.z = t.z - e.z, this; + } + /** + * Multiplies the given vector with this instance. + * + * @param {Vector3} v - The vector to multiply. + * @return {Vector3} A reference to this vector. + */ + multiply(t) { + return this.x *= t.x, this.y *= t.y, this.z *= t.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(t) { + return this.x *= t, this.y *= t, this.z *= t, 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(t, e) { + return this.x = t.x * e.x, this.y = t.y * e.y, this.z = t.z * e.z, this; + } + /** + * Applies the given Euler rotation to this vector. + * + * @param {Euler} euler - The Euler angles. + * @return {Vector3} A reference to this vector. + */ + applyEuler(t) { + return this.applyQuaternion(pa.setFromEuler(t)); + } + /** + * 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(t, e) { + return this.applyQuaternion(pa.setFromAxisAngle(t, e)); + } + /** + * Multiplies this vector with the given 3x3 matrix. + * + * @param {Matrix3} m - The 3x3 matrix. + * @return {Vector3} A reference to this vector. + */ + applyMatrix3(t) { + const e = this.x, n = this.y, s = this.z, r = t.elements; + return this.x = r[0] * e + r[3] * n + r[6] * s, this.y = r[1] * e + r[4] * n + r[7] * s, this.z = r[2] * e + r[5] * n + r[8] * s, 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(t) { + return this.applyMatrix3(t).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(t) { + const e = this.x, n = this.y, s = this.z, r = t.elements, a = 1 / (r[3] * e + r[7] * n + r[11] * s + r[15]); + return this.x = (r[0] * e + r[4] * n + r[8] * s + r[12]) * a, this.y = (r[1] * e + r[5] * n + r[9] * s + r[13]) * a, this.z = (r[2] * e + r[6] * n + r[10] * s + r[14]) * a, this; + } + /** + * Applies the given Quaternion to this vector. + * + * @param {Quaternion} q - The Quaternion. + * @return {Vector3} A reference to this vector. + */ + applyQuaternion(t) { + const e = this.x, n = this.y, s = this.z, r = t.x, a = t.y, o = t.z, c = t.w, l = 2 * (a * s - o * n), u = 2 * (o * e - r * s), d = 2 * (r * n - a * e); + return this.x = e + c * l + a * d - o * u, this.y = n + c * u + o * l - r * d, this.z = s + c * d + r * u - a * l, 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(t) { + return this.applyMatrix4(t.matrixWorldInverse).applyMatrix4(t.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(t) { + return this.applyMatrix4(t.projectionMatrixInverse).applyMatrix4(t.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(t) { + const e = this.x, n = this.y, s = this.z, r = t.elements; + return this.x = r[0] * e + r[4] * n + r[8] * s, this.y = r[1] * e + r[5] * n + r[9] * s, this.z = r[2] * e + r[6] * n + r[10] * s, this.normalize(); + } + /** + * Divides this instance by the given vector. + * + * @param {Vector3} v - The vector to divide. + * @return {Vector3} A reference to this vector. + */ + divide(t) { + return this.x /= t.x, this.y /= t.y, this.z /= t.z, this; + } + /** + * Divides this vector by the given scalar. + * + * @param {number} scalar - The scalar to divide. + * @return {Vector3} A reference to this vector. + */ + divideScalar(t) { + return this.multiplyScalar(1 / t); + } + /** + * 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(t) { + return this.x = Math.min(this.x, t.x), this.y = Math.min(this.y, t.y), this.z = Math.min(this.z, t.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(t) { + return this.x = Math.max(this.x, t.x), this.y = Math.max(this.y, t.y), this.z = Math.max(this.z, t.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(t, e) { + return this.x = Bt(this.x, t.x, e.x), this.y = Bt(this.y, t.y, e.y), this.z = Bt(this.z, t.z, e.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(t, e) { + return this.x = Bt(this.x, t, e), this.y = Bt(this.y, t, e), this.z = Bt(this.z, t, e), 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(t, e) { + const n = this.length(); + return this.divideScalar(n || 1).multiplyScalar(Bt(n, t, e)); + } + /** + * 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(t) { + return this.x * t.x + this.y * t.y + this.z * t.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(t) { + return this.normalize().multiplyScalar(t); + } + /** + * 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(t, e) { + return this.x += (t.x - this.x) * e, this.y += (t.y - this.y) * e, this.z += (t.z - this.z) * e, 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(t, e, n) { + return this.x = t.x + (e.x - t.x) * n, this.y = t.y + (e.y - t.y) * n, this.z = t.z + (e.z - t.z) * n, 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(t) { + return this.crossVectors(this, t); + } + /** + * 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(t, e) { + const n = t.x, s = t.y, r = t.z, a = e.x, o = e.y, c = e.z; + return this.x = s * c - r * o, this.y = r * a - n * c, this.z = n * o - s * 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(t) { + const e = t.lengthSq(); + if (e === 0) return this.set(0, 0, 0); + const n = t.dot(this) / e; + return this.copy(t).multiplyScalar(n); + } + /** + * 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(t) { + return ms.copy(this).projectOnVector(t), this.sub(ms); + } + /** + * 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(t) { + return this.sub(ms.copy(t).multiplyScalar(2 * this.dot(t))); + } + /** + * 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(t) { + const e = Math.sqrt(this.lengthSq() * t.lengthSq()); + if (e === 0) return Math.PI / 2; + const n = this.dot(t) / e; + return Math.acos(Bt(n, -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(t) { + return Math.sqrt(this.distanceToSquared(t)); + } + /** + * 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(t) { + const e = this.x - t.x, n = this.y - t.y, s = this.z - t.z; + return e * e + n * n + s * s; + } + /** + * 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(t) { + return Math.abs(this.x - t.x) + Math.abs(this.y - t.y) + Math.abs(this.z - t.z); + } + /** + * Sets the vector components from the given spherical coordinates. + * + * @param {Spherical} s - The spherical coordinates. + * @return {Vector3} A reference to this vector. + */ + setFromSpherical(t) { + return this.setFromSphericalCoords(t.radius, t.phi, t.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(t, e, n) { + const s = Math.sin(e) * t; + return this.x = s * Math.sin(n), this.y = Math.cos(e) * t, this.z = s * Math.cos(n), this; + } + /** + * Sets the vector components from the given cylindrical coordinates. + * + * @param {Cylindrical} c - The cylindrical coordinates. + * @return {Vector3} A reference to this vector. + */ + setFromCylindrical(t) { + return this.setFromCylindricalCoords(t.radius, t.theta, t.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(t, e, n) { + return this.x = t * Math.sin(e), this.y = n, this.z = t * Math.cos(e), 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(t) { + const e = t.elements; + return this.x = e[12], this.y = e[13], this.z = e[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(t) { + const e = this.setFromMatrixColumn(t, 0).length(), n = this.setFromMatrixColumn(t, 1).length(), s = this.setFromMatrixColumn(t, 2).length(); + return this.x = e, this.y = n, this.z = s, 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(t, e) { + return this.fromArray(t.elements, e * 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(t, e) { + return this.fromArray(t.elements, e * 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(t) { + return this.x = t._x, this.y = t._y, this.z = t._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(t) { + return this.x = t.r, this.y = t.g, this.z = t.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(t) { + return t.x === this.x && t.y === this.y && t.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} 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(t, e = 0) { + return this.x = t[e], this.y = t[e + 1], this.z = t[e + 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} [array=[]] - The target array holding the vector components. + * @param {number} [offset=0] - Index of the first element in the array. + * @return {Array} The vector components. + */ + toArray(t = [], e = 0) { + return t[e] = this.x, t[e + 1] = this.y, t[e + 2] = this.z, t; + } + /** + * 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(t, e) { + return this.x = t.getX(e), this.y = t.getY(e), this.z = t.getZ(e), 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 t = Math.random() * Math.PI * 2, e = Math.random() * 2 - 1, n = Math.sqrt(1 - e * e); + return this.x = n * Math.cos(t), this.y = e, this.z = n * Math.sin(t), this; + } + *[Symbol.iterator]() { + yield this.x, yield this.y, yield this.z; + } +} +const ms = /* @__PURE__ */ new N(), pa = /* @__PURE__ */ new In(); +class It { + /** + * 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(t, e, n, s, r, a, o, c, l) { + It.prototype.isMatrix3 = !0, this.elements = [ + 1, + 0, + 0, + 0, + 1, + 0, + 0, + 0, + 1 + ], t !== void 0 && this.set(t, e, n, s, r, a, o, c, l); + } + /** + * 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(t, e, n, s, r, a, o, c, l) { + const u = this.elements; + return u[0] = t, u[1] = s, u[2] = o, u[3] = e, u[4] = r, u[5] = c, u[6] = n, u[7] = a, u[8] = l, 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(t) { + const e = this.elements, n = t.elements; + return e[0] = n[0], e[1] = n[1], e[2] = n[2], e[3] = n[3], e[4] = n[4], e[5] = n[5], e[6] = n[6], e[7] = n[7], e[8] = n[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(t, e, n) { + return t.setFromMatrix3Column(this, 0), e.setFromMatrix3Column(this, 1), n.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(t) { + const e = t.elements; + return this.set( + e[0], + e[4], + e[8], + e[1], + e[5], + e[9], + e[2], + e[6], + e[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(t) { + return this.multiplyMatrices(this, t); + } + /** + * 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(t) { + return this.multiplyMatrices(t, 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(t, e) { + const n = t.elements, s = e.elements, r = this.elements, a = n[0], o = n[3], c = n[6], l = n[1], u = n[4], d = n[7], f = n[2], m = n[5], v = n[8], x = s[0], p = s[3], h = s[6], A = s[1], b = s[4], y = s[7], D = s[2], P = s[5], w = s[8]; + return r[0] = a * x + o * A + c * D, r[3] = a * p + o * b + c * P, r[6] = a * h + o * y + c * w, r[1] = l * x + u * A + d * D, r[4] = l * p + u * b + d * P, r[7] = l * h + u * y + d * w, r[2] = f * x + m * A + v * D, r[5] = f * p + m * b + v * P, r[8] = f * h + m * y + v * w, this; + } + /** + * Multiplies every component of the matrix by the given scalar. + * + * @param {number} s - The scalar. + * @return {Matrix3} A reference to this matrix. + */ + multiplyScalar(t) { + const e = this.elements; + return e[0] *= t, e[3] *= t, e[6] *= t, e[1] *= t, e[4] *= t, e[7] *= t, e[2] *= t, e[5] *= t, e[8] *= t, this; + } + /** + * Computes and returns the determinant of this matrix. + * + * @return {number} The determinant. + */ + determinant() { + const t = this.elements, e = t[0], n = t[1], s = t[2], r = t[3], a = t[4], o = t[5], c = t[6], l = t[7], u = t[8]; + return e * a * u - e * o * l - n * r * u + n * o * c + s * r * l - s * a * c; + } + /** + * 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 t = this.elements, e = t[0], n = t[1], s = t[2], r = t[3], a = t[4], o = t[5], c = t[6], l = t[7], u = t[8], d = u * a - o * l, f = o * c - u * r, m = l * r - a * c, v = e * d + n * f + s * m; + if (v === 0) return this.set(0, 0, 0, 0, 0, 0, 0, 0, 0); + const x = 1 / v; + return t[0] = d * x, t[1] = (s * l - u * n) * x, t[2] = (o * n - s * a) * x, t[3] = f * x, t[4] = (u * e - s * c) * x, t[5] = (s * r - o * e) * x, t[6] = m * x, t[7] = (n * c - l * e) * x, t[8] = (a * e - n * r) * x, this; + } + /** + * Transposes this matrix in place. + * + * @return {Matrix3} A reference to this matrix. + */ + transpose() { + let t; + const e = this.elements; + return t = e[1], e[1] = e[3], e[3] = t, t = e[2], e[2] = e[6], e[6] = t, t = e[5], e[5] = e[7], e[7] = t, 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(t) { + return this.setFromMatrix4(t).invert().transpose(); + } + /** + * Transposes this matrix into the supplied array, and returns itself unchanged. + * + * @param {Array} r - An array to store the transposed matrix elements. + * @return {Matrix3} A reference to this matrix. + */ + transposeIntoArray(t) { + const e = this.elements; + return t[0] = e[0], t[1] = e[3], t[2] = e[6], t[3] = e[1], t[4] = e[4], t[5] = e[7], t[6] = e[2], t[7] = e[5], t[8] = e[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(t, e, n, s, r, a, o) { + const c = Math.cos(r), l = Math.sin(r); + return this.set( + n * c, + n * l, + -n * (c * a + l * o) + a + t, + -s * l, + s * c, + -s * (-l * a + c * o) + o + e, + 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(t, e) { + return this.premultiply(_s.makeScale(t, e)), this; + } + /** + * Rotates this matrix by the given angle. + * + * @param {number} theta - The rotation in radians. + * @return {Matrix3} A reference to this matrix. + */ + rotate(t) { + return this.premultiply(_s.makeRotation(-t)), 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(t, e) { + return this.premultiply(_s.makeTranslation(t, e)), 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(t, e) { + return t.isVector2 ? this.set( + 1, + 0, + t.x, + 0, + 1, + t.y, + 0, + 0, + 1 + ) : this.set( + 1, + 0, + t, + 0, + 1, + e, + 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(t) { + const e = Math.cos(t), n = Math.sin(t); + return this.set( + e, + -n, + 0, + n, + e, + 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(t, e) { + return this.set( + t, + 0, + 0, + 0, + e, + 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(t) { + const e = this.elements, n = t.elements; + for (let s = 0; s < 9; s++) + if (e[s] !== n[s]) return !1; + return !0; + } + /** + * Sets the elements of the matrix from the given array. + * + * @param {Array} 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(t, e = 0) { + for (let n = 0; n < 9; n++) + this.elements[n] = t[n + e]; + 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} [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} The matrix elements in column-major order. + */ + toArray(t = [], e = 0) { + const n = this.elements; + return t[e] = n[0], t[e + 1] = n[1], t[e + 2] = n[2], t[e + 3] = n[3], t[e + 4] = n[4], t[e + 5] = n[5], t[e + 6] = n[6], t[e + 7] = n[7], t[e + 8] = n[8], t; + } + /** + * 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 _s = /* @__PURE__ */ new It(); +function bo(i) { + for (let t = i.length - 1; t >= 0; --t) + if (i[t] >= 65535) return !0; + return !1; +} +function os(i) { + return document.createElementNS("http://www.w3.org/1999/xhtml", i); +} +function Xl() { + const i = os("canvas"); + return i.style.display = "block", i; +} +const ma = {}; +function Si(i) { + i in ma || (ma[i] = !0, console.warn(i)); +} +function Yl(i, t, e) { + return new Promise(function(n, s) { + function r() { + switch (i.clientWaitSync(t, i.SYNC_FLUSH_COMMANDS_BIT, 0)) { + case i.WAIT_FAILED: + s(); + break; + case i.TIMEOUT_EXPIRED: + setTimeout(r, e); + break; + default: + n(); + } + } + setTimeout(r, e); + }); +} +const _a = /* @__PURE__ */ new It().set( + 0.4123908, + 0.3575843, + 0.1804808, + 0.212639, + 0.7151687, + 0.0721923, + 0.0193308, + 0.1191948, + 0.9505322 +), ga = /* @__PURE__ */ new It().set( + 3.2409699, + -1.5373832, + -0.4986108, + -0.9692436, + 1.8759675, + 0.0415551, + 0.0556301, + -0.203977, + 1.0569715 +); +function ql() { + const i = { + enabled: !0, + workingColorSpace: oi, + /** + * 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(s, r, a) { + return this.enabled === !1 || r === a || !r || !a || (this.spaces[r].transfer === qt && (s.r = rn(s.r), s.g = rn(s.g), s.b = rn(s.b)), this.spaces[r].primaries !== this.spaces[a].primaries && (s.applyMatrix3(this.spaces[r].toXYZ), s.applyMatrix3(this.spaces[a].fromXYZ)), this.spaces[a].transfer === qt && (s.r = ii(s.r), s.g = ii(s.g), s.b = ii(s.b))), s; + }, + workingToColorSpace: function(s, r) { + return this.convert(s, this.workingColorSpace, r); + }, + colorSpaceToWorking: function(s, r) { + return this.convert(s, r, this.workingColorSpace); + }, + getPrimaries: function(s) { + return this.spaces[s].primaries; + }, + getTransfer: function(s) { + return s === mn ? rs : this.spaces[s].transfer; + }, + getToneMappingMode: function(s) { + return this.spaces[s].outputColorSpaceConfig.toneMappingMode || "standard"; + }, + getLuminanceCoefficients: function(s, r = this.workingColorSpace) { + return s.fromArray(this.spaces[r].luminanceCoefficients); + }, + define: function(s) { + Object.assign(this.spaces, s); + }, + // Internal APIs + _getMatrix: function(s, r, a) { + return s.copy(this.spaces[r].toXYZ).multiply(this.spaces[a].fromXYZ); + }, + _getDrawingBufferColorSpace: function(s) { + return this.spaces[s].outputColorSpaceConfig.drawingBufferColorSpace; + }, + _getUnpackColorSpace: function(s = this.workingColorSpace) { + return this.spaces[s].workingColorSpaceConfig.unpackColorSpace; + }, + // Deprecated + fromWorkingColorSpace: function(s, r) { + return Si("THREE.ColorManagement: .fromWorkingColorSpace() has been renamed to .workingToColorSpace()."), i.workingToColorSpace(s, r); + }, + toWorkingColorSpace: function(s, r) { + return Si("THREE.ColorManagement: .toWorkingColorSpace() has been renamed to .colorSpaceToWorking()."), i.colorSpaceToWorking(s, r); + } + }, t = [0.64, 0.33, 0.3, 0.6, 0.15, 0.06], e = [0.2126, 0.7152, 0.0722], n = [0.3127, 0.329]; + return i.define({ + [oi]: { + primaries: t, + whitePoint: n, + transfer: rs, + toXYZ: _a, + fromXYZ: ga, + luminanceCoefficients: e, + workingColorSpaceConfig: { unpackColorSpace: Te }, + outputColorSpaceConfig: { drawingBufferColorSpace: Te } + }, + [Te]: { + primaries: t, + whitePoint: n, + transfer: qt, + toXYZ: _a, + fromXYZ: ga, + luminanceCoefficients: e, + outputColorSpaceConfig: { drawingBufferColorSpace: Te } + } + }), i; +} +const kt = /* @__PURE__ */ ql(); +function rn(i) { + return i < 0.04045 ? i * 0.0773993808 : Math.pow(i * 0.9478672986 + 0.0521327014, 2.4); +} +function ii(i) { + return i < 31308e-7 ? i * 12.92 : 1.055 * Math.pow(i, 0.41666) - 0.055; +} +let zn; +class Kl { + /** + * 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(t, e = "image/png") { + if (/^data:/i.test(t.src) || typeof HTMLCanvasElement > "u") + return t.src; + let n; + if (t instanceof HTMLCanvasElement) + n = t; + else { + zn === void 0 && (zn = os("canvas")), zn.width = t.width, zn.height = t.height; + const s = zn.getContext("2d"); + t instanceof ImageData ? s.putImageData(t, 0, 0) : s.drawImage(t, 0, 0, t.width, t.height), n = zn; + } + return n.toDataURL(e); + } + /** + * 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(t) { + if (typeof HTMLImageElement < "u" && t instanceof HTMLImageElement || typeof HTMLCanvasElement < "u" && t instanceof HTMLCanvasElement || typeof ImageBitmap < "u" && t instanceof ImageBitmap) { + const e = os("canvas"); + e.width = t.width, e.height = t.height; + const n = e.getContext("2d"); + n.drawImage(t, 0, 0, t.width, t.height); + const s = n.getImageData(0, 0, t.width, t.height), r = s.data; + for (let a = 0; a < r.length; a++) + r[a] = rn(r[a] / 255) * 255; + return n.putImageData(s, 0, 0), e; + } else if (t.data) { + const e = t.data.slice(0); + for (let n = 0; n < e.length; n++) + e instanceof Uint8Array || e instanceof Uint8ClampedArray ? e[n] = Math.floor(rn(e[n] / 255) * 255) : e[n] = rn(e[n]); + return { + data: e, + width: t.width, + height: t.height + }; + } else + return console.warn("THREE.ImageUtils.sRGBToLinear(): Unsupported image type. No color space conversion applied."), t; + } +} +let jl = 0; +class Yr { + /** + * Constructs a new video texture. + * + * @param {any} [data=null] - The data definition of a texture. + */ + constructor(t = null) { + this.isSource = !0, Object.defineProperty(this, "id", { value: jl++ }), this.uuid = yi(), this.data = t, 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(t) { + const e = this.data; + return typeof HTMLVideoElement < "u" && e instanceof HTMLVideoElement ? t.set(e.videoWidth, e.videoHeight, 0) : e instanceof VideoFrame ? t.set(e.displayHeight, e.displayWidth, 0) : e !== null ? t.set(e.width, e.height, e.depth || 0) : t.set(0, 0, 0), t; + } + /** + * 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(t) { + t === !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(t) { + const e = t === void 0 || typeof t == "string"; + if (!e && t.images[this.uuid] !== void 0) + return t.images[this.uuid]; + const n = { + uuid: this.uuid, + url: "" + }, s = this.data; + if (s !== null) { + let r; + if (Array.isArray(s)) { + r = []; + for (let a = 0, o = s.length; a < o; a++) + s[a].isDataTexture ? r.push(gs(s[a].image)) : r.push(gs(s[a])); + } else + r = gs(s); + n.url = r; + } + return e || (t.images[this.uuid] = n), n; + } +} +function gs(i) { + return typeof HTMLImageElement < "u" && i instanceof HTMLImageElement || typeof HTMLCanvasElement < "u" && i instanceof HTMLCanvasElement || typeof ImageBitmap < "u" && i instanceof ImageBitmap ? Kl.getDataURL(i) : i.data ? { + data: Array.from(i.data), + width: i.width, + height: i.height, + type: i.data.constructor.name + } : (console.warn("THREE.Texture: Unable to serialize Texture."), {}); +} +let Zl = 0; +const vs = /* @__PURE__ */ new N(); +class Me extends Fn { + /** + * 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(t = Me.DEFAULT_IMAGE, e = Me.DEFAULT_MAPPING, n = Dn, s = Dn, r = Xe, a = Ln, o = Ve, c = Ke, l = Me.DEFAULT_ANISOTROPY, u = mn) { + super(), this.isTexture = !0, Object.defineProperty(this, "id", { value: Zl++ }), this.uuid = yi(), this.name = "", this.source = new Yr(t), this.mipmaps = [], this.mapping = e, this.channel = 0, this.wrapS = n, this.wrapT = s, this.magFilter = r, this.minFilter = a, this.anisotropy = l, this.format = o, this.internalFormat = null, this.type = c, this.offset = new Ct(0, 0), this.repeat = new Ct(1, 1), this.center = new Ct(0, 0), this.rotation = 0, this.matrixAutoUpdate = !0, this.matrix = new It(), this.generateMipmaps = !0, this.premultiplyAlpha = !1, this.flipY = !0, this.unpackAlignment = 4, this.colorSpace = u, this.userData = {}, this.updateRanges = [], this.version = 0, this.onUpdate = null, this.renderTarget = null, this.isRenderTargetTexture = !1, this.isArrayTexture = !!(t && t.depth && t.depth > 1), this.pmremVersion = 0; + } + /** + * The width of the texture in pixels. + */ + get width() { + return this.source.getSize(vs).x; + } + /** + * The height of the texture in pixels. + */ + get height() { + return this.source.getSize(vs).y; + } + /** + * The depth of the texture in pixels. + */ + get depth() { + return this.source.getSize(vs).z; + } + /** + * The image object holding the texture data. + * + * @type {?Object} + */ + get image() { + return this.source.data; + } + set image(t = null) { + this.source.data = t; + } + /** + * 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(t, e) { + this.updateRanges.push({ start: t, count: e }); + } + /** + * 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(t) { + return this.name = t.name, this.source = t.source, this.mipmaps = t.mipmaps.slice(0), this.mapping = t.mapping, this.channel = t.channel, this.wrapS = t.wrapS, this.wrapT = t.wrapT, this.magFilter = t.magFilter, this.minFilter = t.minFilter, this.anisotropy = t.anisotropy, this.format = t.format, this.internalFormat = t.internalFormat, this.type = t.type, this.offset.copy(t.offset), this.repeat.copy(t.repeat), this.center.copy(t.center), this.rotation = t.rotation, this.matrixAutoUpdate = t.matrixAutoUpdate, this.matrix.copy(t.matrix), this.generateMipmaps = t.generateMipmaps, this.premultiplyAlpha = t.premultiplyAlpha, this.flipY = t.flipY, this.unpackAlignment = t.unpackAlignment, this.colorSpace = t.colorSpace, this.renderTarget = t.renderTarget, this.isRenderTargetTexture = t.isRenderTargetTexture, this.isArrayTexture = t.isArrayTexture, this.userData = JSON.parse(JSON.stringify(t.userData)), this.needsUpdate = !0, this; + } + /** + * Sets this texture's properties based on `values`. + * @param {Object} values - A container with texture parameters. + */ + setValues(t) { + for (const e in t) { + const n = t[e]; + if (n === void 0) { + console.warn(`THREE.Texture.setValues(): parameter '${e}' has value of undefined.`); + continue; + } + const s = this[e]; + if (s === void 0) { + console.warn(`THREE.Texture.setValues(): property '${e}' does not exist.`); + continue; + } + s && n && s.isVector2 && n.isVector2 || s && n && s.isVector3 && n.isVector3 || s && n && s.isMatrix3 && n.isMatrix3 ? s.copy(n) : this[e] = n; + } + } + /** + * 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(t) { + const e = t === void 0 || typeof t == "string"; + if (!e && t.textures[this.uuid] !== void 0) + return t.textures[this.uuid]; + const n = { + metadata: { + version: 4.7, + type: "Texture", + generator: "Texture.toJSON" + }, + uuid: this.uuid, + name: this.name, + image: this.source.toJSON(t).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 && (n.userData = this.userData), e || (t.textures[this.uuid] = n), n; + } + /** + * 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(t) { + if (this.mapping !== po) return t; + if (t.applyMatrix3(this.matrix), t.x < 0 || t.x > 1) + switch (this.wrapS) { + case rr: + t.x = t.x - Math.floor(t.x); + break; + case Dn: + t.x = t.x < 0 ? 0 : 1; + break; + case ar: + Math.abs(Math.floor(t.x) % 2) === 1 ? t.x = Math.ceil(t.x) - t.x : t.x = t.x - Math.floor(t.x); + break; + } + if (t.y < 0 || t.y > 1) + switch (this.wrapT) { + case rr: + t.y = t.y - Math.floor(t.y); + break; + case Dn: + t.y = t.y < 0 ? 0 : 1; + break; + case ar: + Math.abs(Math.floor(t.y) % 2) === 1 ? t.y = Math.ceil(t.y) - t.y : t.y = t.y - Math.floor(t.y); + break; + } + return this.flipY && (t.y = 1 - t.y), t; + } + /** + * 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(t) { + t === !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(t) { + t === !0 && this.pmremVersion++; + } +} +Me.DEFAULT_IMAGE = null; +Me.DEFAULT_MAPPING = po; +Me.DEFAULT_ANISOTROPY = 1; +class re { + /** + * 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(t = 0, e = 0, n = 0, s = 1) { + re.prototype.isVector4 = !0, this.x = t, this.y = e, this.z = n, this.w = s; + } + /** + * Alias for {@link Vector4#z}. + * + * @type {number} + */ + get width() { + return this.z; + } + set width(t) { + this.z = t; + } + /** + * Alias for {@link Vector4#w}. + * + * @type {number} + */ + get height() { + return this.w; + } + set height(t) { + this.w = t; + } + /** + * 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(t, e, n, s) { + return this.x = t, this.y = e, this.z = n, this.w = s, 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(t) { + return this.x = t, this.y = t, this.z = t, this.w = t, 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(t) { + return this.x = t, 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(t) { + return this.y = t, 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(t) { + return this.z = t, 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(t) { + return this.w = t, 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(t, e) { + switch (t) { + case 0: + this.x = e; + break; + case 1: + this.y = e; + break; + case 2: + this.z = e; + break; + case 3: + this.w = e; + break; + default: + throw new Error("index is out of range: " + t); + } + 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(t) { + switch (t) { + 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: " + t); + } + } + /** + * 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(t) { + return this.x = t.x, this.y = t.y, this.z = t.z, this.w = t.w !== void 0 ? t.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(t) { + return this.x += t.x, this.y += t.y, this.z += t.z, this.w += t.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(t) { + return this.x += t, this.y += t, this.z += t, this.w += t, 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(t, e) { + return this.x = t.x + e.x, this.y = t.y + e.y, this.z = t.z + e.z, this.w = t.w + e.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(t, e) { + return this.x += t.x * e, this.y += t.y * e, this.z += t.z * e, this.w += t.w * e, this; + } + /** + * Subtracts the given vector from this instance. + * + * @param {Vector4} v - The vector to subtract. + * @return {Vector4} A reference to this vector. + */ + sub(t) { + return this.x -= t.x, this.y -= t.y, this.z -= t.z, this.w -= t.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(t) { + return this.x -= t, this.y -= t, this.z -= t, this.w -= t, 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(t, e) { + return this.x = t.x - e.x, this.y = t.y - e.y, this.z = t.z - e.z, this.w = t.w - e.w, this; + } + /** + * Multiplies the given vector with this instance. + * + * @param {Vector4} v - The vector to multiply. + * @return {Vector4} A reference to this vector. + */ + multiply(t) { + return this.x *= t.x, this.y *= t.y, this.z *= t.z, this.w *= t.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(t) { + return this.x *= t, this.y *= t, this.z *= t, this.w *= t, this; + } + /** + * Multiplies this vector with the given 4x4 matrix. + * + * @param {Matrix4} m - The 4x4 matrix. + * @return {Vector4} A reference to this vector. + */ + applyMatrix4(t) { + const e = this.x, n = this.y, s = this.z, r = this.w, a = t.elements; + return this.x = a[0] * e + a[4] * n + a[8] * s + a[12] * r, this.y = a[1] * e + a[5] * n + a[9] * s + a[13] * r, this.z = a[2] * e + a[6] * n + a[10] * s + a[14] * r, this.w = a[3] * e + a[7] * n + a[11] * s + a[15] * r, this; + } + /** + * Divides this instance by the given vector. + * + * @param {Vector4} v - The vector to divide. + * @return {Vector4} A reference to this vector. + */ + divide(t) { + return this.x /= t.x, this.y /= t.y, this.z /= t.z, this.w /= t.w, this; + } + /** + * Divides this vector by the given scalar. + * + * @param {number} scalar - The scalar to divide. + * @return {Vector4} A reference to this vector. + */ + divideScalar(t) { + return this.multiplyScalar(1 / t); + } + /** + * 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(t) { + this.w = 2 * Math.acos(t.w); + const e = Math.sqrt(1 - t.w * t.w); + return e < 1e-4 ? (this.x = 1, this.y = 0, this.z = 0) : (this.x = t.x / e, this.y = t.y / e, this.z = t.z / e), 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(t) { + let e, n, s, r; + const c = t.elements, l = c[0], u = c[4], d = c[8], f = c[1], m = c[5], v = c[9], x = c[2], p = c[6], h = c[10]; + if (Math.abs(u - f) < 0.01 && Math.abs(d - x) < 0.01 && Math.abs(v - p) < 0.01) { + if (Math.abs(u + f) < 0.1 && Math.abs(d + x) < 0.1 && Math.abs(v + p) < 0.1 && Math.abs(l + m + h - 3) < 0.1) + return this.set(1, 0, 0, 0), this; + e = Math.PI; + const b = (l + 1) / 2, y = (m + 1) / 2, D = (h + 1) / 2, P = (u + f) / 4, w = (d + x) / 4, F = (v + p) / 4; + return b > y && b > D ? b < 0.01 ? (n = 0, s = 0.707106781, r = 0.707106781) : (n = Math.sqrt(b), s = P / n, r = w / n) : y > D ? y < 0.01 ? (n = 0.707106781, s = 0, r = 0.707106781) : (s = Math.sqrt(y), n = P / s, r = F / s) : D < 0.01 ? (n = 0.707106781, s = 0.707106781, r = 0) : (r = Math.sqrt(D), n = w / r, s = F / r), this.set(n, s, r, e), this; + } + let A = Math.sqrt((p - v) * (p - v) + (d - x) * (d - x) + (f - u) * (f - u)); + return Math.abs(A) < 1e-3 && (A = 1), this.x = (p - v) / A, this.y = (d - x) / A, this.z = (f - u) / A, this.w = Math.acos((l + m + h - 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(t) { + const e = t.elements; + return this.x = e[12], this.y = e[13], this.z = e[14], this.w = e[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(t) { + return this.x = Math.min(this.x, t.x), this.y = Math.min(this.y, t.y), this.z = Math.min(this.z, t.z), this.w = Math.min(this.w, t.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(t) { + return this.x = Math.max(this.x, t.x), this.y = Math.max(this.y, t.y), this.z = Math.max(this.z, t.z), this.w = Math.max(this.w, t.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(t, e) { + return this.x = Bt(this.x, t.x, e.x), this.y = Bt(this.y, t.y, e.y), this.z = Bt(this.z, t.z, e.z), this.w = Bt(this.w, t.w, e.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(t, e) { + return this.x = Bt(this.x, t, e), this.y = Bt(this.y, t, e), this.z = Bt(this.z, t, e), this.w = Bt(this.w, t, e), 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(t, e) { + const n = this.length(); + return this.divideScalar(n || 1).multiplyScalar(Bt(n, t, e)); + } + /** + * 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(t) { + return this.x * t.x + this.y * t.y + this.z * t.z + this.w * t.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(t) { + return this.normalize().multiplyScalar(t); + } + /** + * 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(t, e) { + return this.x += (t.x - this.x) * e, this.y += (t.y - this.y) * e, this.z += (t.z - this.z) * e, this.w += (t.w - this.w) * e, 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(t, e, n) { + return this.x = t.x + (e.x - t.x) * n, this.y = t.y + (e.y - t.y) * n, this.z = t.z + (e.z - t.z) * n, this.w = t.w + (e.w - t.w) * n, 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(t) { + return t.x === this.x && t.y === this.y && t.z === this.z && t.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} 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(t, e = 0) { + return this.x = t[e], this.y = t[e + 1], this.z = t[e + 2], this.w = t[e + 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} [array=[]] - The target array holding the vector components. + * @param {number} [offset=0] - Index of the first element in the array. + * @return {Array} The vector components. + */ + toArray(t = [], e = 0) { + return t[e] = this.x, t[e + 1] = this.y, t[e + 2] = this.z, t[e + 3] = this.w, t; + } + /** + * 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(t, e) { + return this.x = t.getX(e), this.y = t.getY(e), this.z = t.getZ(e), this.w = t.getW(e), 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 $l extends Fn { + /** + * 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(t = 1, e = 1, n = {}) { + super(), n = Object.assign({ + generateMipmaps: !1, + internalFormat: null, + minFilter: Xe, + depthBuffer: !0, + stencilBuffer: !1, + resolveDepthBuffer: !0, + resolveStencilBuffer: !0, + depthTexture: null, + samples: 0, + count: 1, + depth: 1, + multiview: !1 + }, n), this.isRenderTarget = !0, this.width = t, this.height = e, this.depth = n.depth, this.scissor = new re(0, 0, t, e), this.scissorTest = !1, this.viewport = new re(0, 0, t, e); + const s = { width: t, height: e, depth: n.depth }, r = new Me(s); + this.textures = []; + const a = n.count; + for (let o = 0; o < a; o++) + this.textures[o] = r.clone(), this.textures[o].isRenderTargetTexture = !0, this.textures[o].renderTarget = this; + this._setTextureOptions(n), this.depthBuffer = n.depthBuffer, this.stencilBuffer = n.stencilBuffer, this.resolveDepthBuffer = n.resolveDepthBuffer, this.resolveStencilBuffer = n.resolveStencilBuffer, this._depthTexture = null, this.depthTexture = n.depthTexture, this.samples = n.samples, this.multiview = n.multiview; + } + _setTextureOptions(t = {}) { + const e = { + minFilter: Xe, + generateMipmaps: !1, + flipY: !1, + internalFormat: null + }; + t.mapping !== void 0 && (e.mapping = t.mapping), t.wrapS !== void 0 && (e.wrapS = t.wrapS), t.wrapT !== void 0 && (e.wrapT = t.wrapT), t.wrapR !== void 0 && (e.wrapR = t.wrapR), t.magFilter !== void 0 && (e.magFilter = t.magFilter), t.minFilter !== void 0 && (e.minFilter = t.minFilter), t.format !== void 0 && (e.format = t.format), t.type !== void 0 && (e.type = t.type), t.anisotropy !== void 0 && (e.anisotropy = t.anisotropy), t.colorSpace !== void 0 && (e.colorSpace = t.colorSpace), t.flipY !== void 0 && (e.flipY = t.flipY), t.generateMipmaps !== void 0 && (e.generateMipmaps = t.generateMipmaps), t.internalFormat !== void 0 && (e.internalFormat = t.internalFormat); + for (let n = 0; n < this.textures.length; n++) + this.textures[n].setValues(e); + } + /** + * The texture representing the default color attachment. + * + * @type {Texture} + */ + get texture() { + return this.textures[0]; + } + set texture(t) { + this.textures[0] = t; + } + set depthTexture(t) { + this._depthTexture !== null && (this._depthTexture.renderTarget = null), t !== null && (t.renderTarget = this), this._depthTexture = t; + } + /** + * 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(t, e, n = 1) { + if (this.width !== t || this.height !== e || this.depth !== n) { + this.width = t, this.height = e, this.depth = n; + for (let s = 0, r = this.textures.length; s < r; s++) + this.textures[s].image.width = t, this.textures[s].image.height = e, this.textures[s].image.depth = n, this.textures[s].isArrayTexture = this.textures[s].image.depth > 1; + this.dispose(); + } + this.viewport.set(0, 0, t, e), this.scissor.set(0, 0, t, e); + } + /** + * 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(t) { + this.width = t.width, this.height = t.height, this.depth = t.depth, this.scissor.copy(t.scissor), this.scissorTest = t.scissorTest, this.viewport.copy(t.viewport), this.textures.length = 0; + for (let e = 0, n = t.textures.length; e < n; e++) { + this.textures[e] = t.textures[e].clone(), this.textures[e].isRenderTargetTexture = !0, this.textures[e].renderTarget = this; + const s = Object.assign({}, t.textures[e].image); + this.textures[e].source = new Yr(s); + } + return this.depthBuffer = t.depthBuffer, this.stencilBuffer = t.stencilBuffer, this.resolveDepthBuffer = t.resolveDepthBuffer, this.resolveStencilBuffer = t.resolveStencilBuffer, t.depthTexture !== null && (this.depthTexture = t.depthTexture.clone()), this.samples = t.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 $l { + /** + * 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(t = 1, e = 1, n = {}) { + super(t, e, n), this.isWebGLRenderTarget = !0; + } +} +class Ao extends Me { + /** + * 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(t = null, e = 1, n = 1, s = 1) { + super(null), this.isDataArrayTexture = !0, this.image = { data: t, width: e, height: n, depth: s }, this.magFilter = Ge, this.minFilter = Ge, this.wrapR = Dn, 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(t) { + this.layerUpdates.add(t); + } + /** + * Resets the layer updates registry. + */ + clearLayerUpdates() { + this.layerUpdates.clear(); + } +} +class Jl extends Me { + /** + * 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(t = null, e = 1, n = 1, s = 1) { + super(null), this.isData3DTexture = !0, this.image = { data: t, width: e, height: n, depth: s }, this.magFilter = Ge, this.minFilter = Ge, this.wrapR = Dn, this.generateMipmaps = !1, this.flipY = !1, this.unpackAlignment = 1; + } +} +class Ti { + /** + * 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(t = new N(1 / 0, 1 / 0, 1 / 0), e = new N(-1 / 0, -1 / 0, -1 / 0)) { + this.isBox3 = !0, this.min = t, this.max = e; + } + /** + * 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(t, e) { + return this.min.copy(t), this.max.copy(e), this; + } + /** + * Sets the upper and lower bounds of this box so it encloses the position data + * in the given array. + * + * @param {Array} array - An array holding 3D position data. + * @return {Box3} A reference to this bounding box. + */ + setFromArray(t) { + this.makeEmpty(); + for (let e = 0, n = t.length; e < n; e += 3) + this.expandByPoint(Oe.fromArray(t, e)); + 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(t) { + this.makeEmpty(); + for (let e = 0, n = t.count; e < n; e++) + this.expandByPoint(Oe.fromBufferAttribute(t, e)); + return this; + } + /** + * Sets the upper and lower bounds of this box so it encloses the position data + * in the given array. + * + * @param {Array} points - An array holding 3D position data as instances of {@link Vector3}. + * @return {Box3} A reference to this bounding box. + */ + setFromPoints(t) { + this.makeEmpty(); + for (let e = 0, n = t.length; e < n; e++) + this.expandByPoint(t[e]); + 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(t, e) { + const n = Oe.copy(e).multiplyScalar(0.5); + return this.min.copy(t).sub(n), this.max.copy(t).add(n), 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(t, e = !1) { + return this.makeEmpty(), this.expandByObject(t, e); + } + /** + * 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(t) { + return this.min.copy(t.min), this.max.copy(t.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(t) { + return this.isEmpty() ? t.set(0, 0, 0) : t.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(t) { + return this.isEmpty() ? t.set(0, 0, 0) : t.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(t) { + return this.min.min(t), this.max.max(t), 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(t) { + return this.min.sub(t), this.max.add(t), 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(t) { + return this.min.addScalar(-t), this.max.addScalar(t), 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(t, e = !1) { + t.updateWorldMatrix(!1, !1); + const n = t.geometry; + if (n !== void 0) { + const r = n.getAttribute("position"); + if (e === !0 && r !== void 0 && t.isInstancedMesh !== !0) + for (let a = 0, o = r.count; a < o; a++) + t.isMesh === !0 ? t.getVertexPosition(a, Oe) : Oe.fromBufferAttribute(r, a), Oe.applyMatrix4(t.matrixWorld), this.expandByPoint(Oe); + else + t.boundingBox !== void 0 ? (t.boundingBox === null && t.computeBoundingBox(), Pi.copy(t.boundingBox)) : (n.boundingBox === null && n.computeBoundingBox(), Pi.copy(n.boundingBox)), Pi.applyMatrix4(t.matrixWorld), this.union(Pi); + } + const s = t.children; + for (let r = 0, a = s.length; r < a; r++) + this.expandByObject(s[r], e); + 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(t) { + return t.x >= this.min.x && t.x <= this.max.x && t.y >= this.min.y && t.y <= this.max.y && t.z >= this.min.z && t.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(t) { + return this.min.x <= t.min.x && t.max.x <= this.max.x && this.min.y <= t.min.y && t.max.y <= this.max.y && this.min.z <= t.min.z && t.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(t, e) { + return e.set( + (t.x - this.min.x) / (this.max.x - this.min.x), + (t.y - this.min.y) / (this.max.y - this.min.y), + (t.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(t) { + return t.max.x >= this.min.x && t.min.x <= this.max.x && t.max.y >= this.min.y && t.min.y <= this.max.y && t.max.z >= this.min.z && t.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(t) { + return this.clampPoint(t.center, Oe), Oe.distanceToSquared(t.center) <= t.radius * t.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(t) { + let e, n; + return t.normal.x > 0 ? (e = t.normal.x * this.min.x, n = t.normal.x * this.max.x) : (e = t.normal.x * this.max.x, n = t.normal.x * this.min.x), t.normal.y > 0 ? (e += t.normal.y * this.min.y, n += t.normal.y * this.max.y) : (e += t.normal.y * this.max.y, n += t.normal.y * this.min.y), t.normal.z > 0 ? (e += t.normal.z * this.min.z, n += t.normal.z * this.max.z) : (e += t.normal.z * this.max.z, n += t.normal.z * this.min.z), e <= -t.constant && n >= -t.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(t) { + if (this.isEmpty()) + return !1; + this.getCenter(di), Di.subVectors(this.max, di), Hn.subVectors(t.a, di), Vn.subVectors(t.b, di), Gn.subVectors(t.c, di), on.subVectors(Vn, Hn), ln.subVectors(Gn, Vn), En.subVectors(Hn, Gn); + let e = [ + 0, + -on.z, + on.y, + 0, + -ln.z, + ln.y, + 0, + -En.z, + En.y, + on.z, + 0, + -on.x, + ln.z, + 0, + -ln.x, + En.z, + 0, + -En.x, + -on.y, + on.x, + 0, + -ln.y, + ln.x, + 0, + -En.y, + En.x, + 0 + ]; + return !xs(e, Hn, Vn, Gn, Di) || (e = [1, 0, 0, 0, 1, 0, 0, 0, 1], !xs(e, Hn, Vn, Gn, Di)) ? !1 : (Li.crossVectors(on, ln), e = [Li.x, Li.y, Li.z], xs(e, Hn, Vn, Gn, Di)); + } + /** + * 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(t, e) { + return e.copy(t).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(t) { + return this.clampPoint(t, Oe).distanceTo(t); + } + /** + * 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(t) { + return this.isEmpty() ? t.makeEmpty() : (this.getCenter(t.center), t.radius = this.getSize(Oe).length() * 0.5), t; + } + /** + * 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(t) { + return this.min.max(t.min), this.max.min(t.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(t) { + return this.min.min(t.min), this.max.max(t.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(t) { + return this.isEmpty() ? this : ($e[0].set(this.min.x, this.min.y, this.min.z).applyMatrix4(t), $e[1].set(this.min.x, this.min.y, this.max.z).applyMatrix4(t), $e[2].set(this.min.x, this.max.y, this.min.z).applyMatrix4(t), $e[3].set(this.min.x, this.max.y, this.max.z).applyMatrix4(t), $e[4].set(this.max.x, this.min.y, this.min.z).applyMatrix4(t), $e[5].set(this.max.x, this.min.y, this.max.z).applyMatrix4(t), $e[6].set(this.max.x, this.max.y, this.min.z).applyMatrix4(t), $e[7].set(this.max.x, this.max.y, this.max.z).applyMatrix4(t), this.setFromPoints($e), 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(t) { + return this.min.add(t), this.max.add(t), 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(t) { + return t.min.equals(this.min) && t.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(t) { + return this.min.fromArray(t.min), this.max.fromArray(t.max), this; + } +} +const $e = [ + /* @__PURE__ */ new N(), + /* @__PURE__ */ new N(), + /* @__PURE__ */ new N(), + /* @__PURE__ */ new N(), + /* @__PURE__ */ new N(), + /* @__PURE__ */ new N(), + /* @__PURE__ */ new N(), + /* @__PURE__ */ new N() +], Oe = /* @__PURE__ */ new N(), Pi = /* @__PURE__ */ new Ti(), Hn = /* @__PURE__ */ new N(), Vn = /* @__PURE__ */ new N(), Gn = /* @__PURE__ */ new N(), on = /* @__PURE__ */ new N(), ln = /* @__PURE__ */ new N(), En = /* @__PURE__ */ new N(), di = /* @__PURE__ */ new N(), Di = /* @__PURE__ */ new N(), Li = /* @__PURE__ */ new N(), yn = /* @__PURE__ */ new N(); +function xs(i, t, e, n, s) { + for (let r = 0, a = i.length - 3; r <= a; r += 3) { + yn.fromArray(i, r); + const o = s.x * Math.abs(yn.x) + s.y * Math.abs(yn.y) + s.z * Math.abs(yn.z), c = t.dot(yn), l = e.dot(yn), u = n.dot(yn); + if (Math.max(-Math.max(c, l, u), Math.min(c, l, u)) > o) + return !1; + } + return !0; +} +const Ql = /* @__PURE__ */ new Ti(), fi = /* @__PURE__ */ new N(), Ms = /* @__PURE__ */ new N(); +class qr { + /** + * 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(t = new N(), e = -1) { + this.isSphere = !0, this.center = t, this.radius = e; + } + /** + * 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(t, e) { + return this.center.copy(t), this.radius = e, 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} points - A list of points in 3D space. + * @param {Vector3} [optionalCenter] - The center of the sphere. + * @return {Sphere} A reference to this sphere. + */ + setFromPoints(t, e) { + const n = this.center; + e !== void 0 ? n.copy(e) : Ql.setFromPoints(t).getCenter(n); + let s = 0; + for (let r = 0, a = t.length; r < a; r++) + s = Math.max(s, n.distanceToSquared(t[r])); + return this.radius = Math.sqrt(s), 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(t) { + return this.center.copy(t.center), this.radius = t.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(t) { + return t.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(t) { + return t.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(t) { + const e = this.radius + t.radius; + return t.center.distanceToSquared(this.center) <= e * e; + } + /** + * 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(t) { + return t.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(t) { + return Math.abs(t.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(t, e) { + const n = this.center.distanceToSquared(t); + return e.copy(t), n > this.radius * this.radius && (e.sub(this.center).normalize(), e.multiplyScalar(this.radius).add(this.center)), e; + } + /** + * 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(t) { + return this.isEmpty() ? (t.makeEmpty(), t) : (t.set(this.center, this.center), t.expandByScalar(this.radius), t); + } + /** + * Transforms this sphere with the given 4x4 transformation matrix. + * + * @param {Matrix4} matrix - The transformation matrix. + * @return {Sphere} A reference to this sphere. + */ + applyMatrix4(t) { + return this.center.applyMatrix4(t), this.radius = this.radius * t.getMaxScaleOnAxis(), this; + } + /** + * Translates the sphere's center by the given offset. + * + * @param {Vector3} offset - The offset. + * @return {Sphere} A reference to this sphere. + */ + translate(t) { + return this.center.add(t), 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(t) { + if (this.isEmpty()) + return this.center.copy(t), this.radius = 0, this; + fi.subVectors(t, this.center); + const e = fi.lengthSq(); + if (e > this.radius * this.radius) { + const n = Math.sqrt(e), s = (n - this.radius) * 0.5; + this.center.addScaledVector(fi, s / n), this.radius += s; + } + 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(t) { + return t.isEmpty() ? this : this.isEmpty() ? (this.copy(t), this) : (this.center.equals(t.center) === !0 ? this.radius = Math.max(this.radius, t.radius) : (Ms.subVectors(t.center, this.center).setLength(t.radius), this.expandByPoint(fi.copy(t.center).add(Ms)), this.expandByPoint(fi.copy(t.center).sub(Ms))), 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(t) { + return t.center.equals(this.center) && t.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(t) { + return this.radius = t.radius, this.center.fromArray(t.center), this; + } +} +const Je = /* @__PURE__ */ new N(), Ss = /* @__PURE__ */ new N(), Ui = /* @__PURE__ */ new N(), cn = /* @__PURE__ */ new N(), Es = /* @__PURE__ */ new N(), Ii = /* @__PURE__ */ new N(), ys = /* @__PURE__ */ new N(); +class Kr { + /** + * 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(t = new N(), e = new N(0, 0, -1)) { + this.origin = t, this.direction = e; + } + /** + * 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(t, e) { + return this.origin.copy(t), this.direction.copy(e), 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(t) { + return this.origin.copy(t.origin), this.direction.copy(t.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(t, e) { + return e.copy(this.origin).addScaledVector(this.direction, t); + } + /** + * 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(t) { + return this.direction.copy(t).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(t) { + return this.origin.copy(this.at(t, Je)), 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(t, e) { + e.subVectors(t, this.origin); + const n = e.dot(this.direction); + return n < 0 ? e.copy(this.origin) : e.copy(this.origin).addScaledVector(this.direction, n); + } + /** + * 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(t) { + return Math.sqrt(this.distanceSqToPoint(t)); + } + /** + * 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(t) { + const e = Je.subVectors(t, this.origin).dot(this.direction); + return e < 0 ? this.origin.distanceToSquared(t) : (Je.copy(this.origin).addScaledVector(this.direction, e), Je.distanceToSquared(t)); + } + /** + * 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(t, e, n, s) { + Ss.copy(t).add(e).multiplyScalar(0.5), Ui.copy(e).sub(t).normalize(), cn.copy(this.origin).sub(Ss); + const r = t.distanceTo(e) * 0.5, a = -this.direction.dot(Ui), o = cn.dot(this.direction), c = -cn.dot(Ui), l = cn.lengthSq(), u = Math.abs(1 - a * a); + let d, f, m, v; + if (u > 0) + if (d = a * c - o, f = a * o - c, v = r * u, d >= 0) + if (f >= -v) + if (f <= v) { + const x = 1 / u; + d *= x, f *= x, m = d * (d + a * f + 2 * o) + f * (a * d + f + 2 * c) + l; + } else + f = r, d = Math.max(0, -(a * f + o)), m = -d * d + f * (f + 2 * c) + l; + else + f = -r, d = Math.max(0, -(a * f + o)), m = -d * d + f * (f + 2 * c) + l; + else + f <= -v ? (d = Math.max(0, -(-a * r + o)), f = d > 0 ? -r : Math.min(Math.max(-r, -c), r), m = -d * d + f * (f + 2 * c) + l) : f <= v ? (d = 0, f = Math.min(Math.max(-r, -c), r), m = f * (f + 2 * c) + l) : (d = Math.max(0, -(a * r + o)), f = d > 0 ? r : Math.min(Math.max(-r, -c), r), m = -d * d + f * (f + 2 * c) + l); + else + f = a > 0 ? -r : r, d = Math.max(0, -(a * f + o)), m = -d * d + f * (f + 2 * c) + l; + return n && n.copy(this.origin).addScaledVector(this.direction, d), s && s.copy(Ss).addScaledVector(Ui, f), m; + } + /** + * 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(t, e) { + Je.subVectors(t.center, this.origin); + const n = Je.dot(this.direction), s = Je.dot(Je) - n * n, r = t.radius * t.radius; + if (s > r) return null; + const a = Math.sqrt(r - s), o = n - a, c = n + a; + return c < 0 ? null : o < 0 ? this.at(c, e) : this.at(o, e); + } + /** + * 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(t) { + return t.radius < 0 ? !1 : this.distanceSqToPoint(t.center) <= t.radius * t.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(t) { + const e = t.normal.dot(this.direction); + if (e === 0) + return t.distanceToPoint(this.origin) === 0 ? 0 : null; + const n = -(this.origin.dot(t.normal) + t.constant) / e; + return n >= 0 ? n : 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(t, e) { + const n = this.distanceToPlane(t); + return n === null ? null : this.at(n, e); + } + /** + * 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(t) { + const e = t.distanceToPoint(this.origin); + return e === 0 || t.normal.dot(this.direction) * e < 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(t, e) { + let n, s, r, a, o, c; + const l = 1 / this.direction.x, u = 1 / this.direction.y, d = 1 / this.direction.z, f = this.origin; + return l >= 0 ? (n = (t.min.x - f.x) * l, s = (t.max.x - f.x) * l) : (n = (t.max.x - f.x) * l, s = (t.min.x - f.x) * l), u >= 0 ? (r = (t.min.y - f.y) * u, a = (t.max.y - f.y) * u) : (r = (t.max.y - f.y) * u, a = (t.min.y - f.y) * u), n > a || r > s || ((r > n || isNaN(n)) && (n = r), (a < s || isNaN(s)) && (s = a), d >= 0 ? (o = (t.min.z - f.z) * d, c = (t.max.z - f.z) * d) : (o = (t.max.z - f.z) * d, c = (t.min.z - f.z) * d), n > c || o > s) || ((o > n || n !== n) && (n = o), (c < s || s !== s) && (s = c), s < 0) ? null : this.at(n >= 0 ? n : s, e); + } + /** + * 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(t) { + return this.intersectBox(t, Je) !== 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(t, e, n, s, r) { + Es.subVectors(e, t), Ii.subVectors(n, t), ys.crossVectors(Es, Ii); + let a = this.direction.dot(ys), o; + if (a > 0) { + if (s) return null; + o = 1; + } else if (a < 0) + o = -1, a = -a; + else + return null; + cn.subVectors(this.origin, t); + const c = o * this.direction.dot(Ii.crossVectors(cn, Ii)); + if (c < 0) + return null; + const l = o * this.direction.dot(Es.cross(cn)); + if (l < 0 || c + l > a) + return null; + const u = -o * cn.dot(ys); + return u < 0 ? null : this.at(u / a, r); + } + /** + * Transforms this ray with the given 4x4 transformation matrix. + * + * @param {Matrix4} matrix4 - The transformation matrix. + * @return {Ray} A reference to this ray. + */ + applyMatrix4(t) { + return this.origin.applyMatrix4(t), this.direction.transformDirection(t), 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(t) { + return t.origin.equals(this.origin) && t.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 ae { + /** + * 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(t, e, n, s, r, a, o, c, l, u, d, f, m, v, x, p) { + ae.prototype.isMatrix4 = !0, this.elements = [ + 1, + 0, + 0, + 0, + 0, + 1, + 0, + 0, + 0, + 0, + 1, + 0, + 0, + 0, + 0, + 1 + ], t !== void 0 && this.set(t, e, n, s, r, a, o, c, l, u, d, f, m, v, x, p); + } + /** + * 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(t, e, n, s, r, a, o, c, l, u, d, f, m, v, x, p) { + const h = this.elements; + return h[0] = t, h[4] = e, h[8] = n, h[12] = s, h[1] = r, h[5] = a, h[9] = o, h[13] = c, h[2] = l, h[6] = u, h[10] = d, h[14] = f, h[3] = m, h[7] = v, h[11] = x, h[15] = p, 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 ae().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(t) { + const e = this.elements, n = t.elements; + return e[0] = n[0], e[1] = n[1], e[2] = n[2], e[3] = n[3], e[4] = n[4], e[5] = n[5], e[6] = n[6], e[7] = n[7], e[8] = n[8], e[9] = n[9], e[10] = n[10], e[11] = n[11], e[12] = n[12], e[13] = n[13], e[14] = n[14], e[15] = n[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(t) { + const e = this.elements, n = t.elements; + return e[12] = n[12], e[13] = n[13], e[14] = n[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(t) { + const e = t.elements; + return this.set( + e[0], + e[3], + e[6], + 0, + e[1], + e[4], + e[7], + 0, + e[2], + e[5], + e[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(t, e, n) { + return t.setFromMatrixColumn(this, 0), e.setFromMatrixColumn(this, 1), n.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(t, e, n) { + return this.set( + t.x, + e.x, + n.x, + 0, + t.y, + e.y, + n.y, + 0, + t.z, + e.z, + n.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(t) { + const e = this.elements, n = t.elements, s = 1 / kn.setFromMatrixColumn(t, 0).length(), r = 1 / kn.setFromMatrixColumn(t, 1).length(), a = 1 / kn.setFromMatrixColumn(t, 2).length(); + return e[0] = n[0] * s, e[1] = n[1] * s, e[2] = n[2] * s, e[3] = 0, e[4] = n[4] * r, e[5] = n[5] * r, e[6] = n[6] * r, e[7] = 0, e[8] = n[8] * a, e[9] = n[9] * a, e[10] = n[10] * a, e[11] = 0, e[12] = 0, e[13] = 0, e[14] = 0, e[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(t) { + const e = this.elements, n = t.x, s = t.y, r = t.z, a = Math.cos(n), o = Math.sin(n), c = Math.cos(s), l = Math.sin(s), u = Math.cos(r), d = Math.sin(r); + if (t.order === "XYZ") { + const f = a * u, m = a * d, v = o * u, x = o * d; + e[0] = c * u, e[4] = -c * d, e[8] = l, e[1] = m + v * l, e[5] = f - x * l, e[9] = -o * c, e[2] = x - f * l, e[6] = v + m * l, e[10] = a * c; + } else if (t.order === "YXZ") { + const f = c * u, m = c * d, v = l * u, x = l * d; + e[0] = f + x * o, e[4] = v * o - m, e[8] = a * l, e[1] = a * d, e[5] = a * u, e[9] = -o, e[2] = m * o - v, e[6] = x + f * o, e[10] = a * c; + } else if (t.order === "ZXY") { + const f = c * u, m = c * d, v = l * u, x = l * d; + e[0] = f - x * o, e[4] = -a * d, e[8] = v + m * o, e[1] = m + v * o, e[5] = a * u, e[9] = x - f * o, e[2] = -a * l, e[6] = o, e[10] = a * c; + } else if (t.order === "ZYX") { + const f = a * u, m = a * d, v = o * u, x = o * d; + e[0] = c * u, e[4] = v * l - m, e[8] = f * l + x, e[1] = c * d, e[5] = x * l + f, e[9] = m * l - v, e[2] = -l, e[6] = o * c, e[10] = a * c; + } else if (t.order === "YZX") { + const f = a * c, m = a * l, v = o * c, x = o * l; + e[0] = c * u, e[4] = x - f * d, e[8] = v * d + m, e[1] = d, e[5] = a * u, e[9] = -o * u, e[2] = -l * u, e[6] = m * d + v, e[10] = f - x * d; + } else if (t.order === "XZY") { + const f = a * c, m = a * l, v = o * c, x = o * l; + e[0] = c * u, e[4] = -d, e[8] = l * u, e[1] = f * d + x, e[5] = a * u, e[9] = m * d - v, e[2] = v * d - m, e[6] = o * u, e[10] = x * d + f; + } + return e[3] = 0, e[7] = 0, e[11] = 0, e[12] = 0, e[13] = 0, e[14] = 0, e[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(t) { + return this.compose(tc, t, ec); + } + /** + * 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(t, e, n) { + const s = this.elements; + return Ce.subVectors(t, e), Ce.lengthSq() === 0 && (Ce.z = 1), Ce.normalize(), hn.crossVectors(n, Ce), hn.lengthSq() === 0 && (Math.abs(n.z) === 1 ? Ce.x += 1e-4 : Ce.z += 1e-4, Ce.normalize(), hn.crossVectors(n, Ce)), hn.normalize(), Ni.crossVectors(Ce, hn), s[0] = hn.x, s[4] = Ni.x, s[8] = Ce.x, s[1] = hn.y, s[5] = Ni.y, s[9] = Ce.y, s[2] = hn.z, s[6] = Ni.z, s[10] = Ce.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(t) { + return this.multiplyMatrices(this, t); + } + /** + * 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(t) { + return this.multiplyMatrices(t, 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(t, e) { + const n = t.elements, s = e.elements, r = this.elements, a = n[0], o = n[4], c = n[8], l = n[12], u = n[1], d = n[5], f = n[9], m = n[13], v = n[2], x = n[6], p = n[10], h = n[14], A = n[3], b = n[7], y = n[11], D = n[15], P = s[0], w = s[4], F = s[8], S = s[12], M = s[1], C = s[5], z = s[9], G = s[13], K = s[2], W = s[6], Y = s[10], Z = s[14], H = s[3], rt = s[7], ct = s[11], Et = s[15]; + return r[0] = a * P + o * M + c * K + l * H, r[4] = a * w + o * C + c * W + l * rt, r[8] = a * F + o * z + c * Y + l * ct, r[12] = a * S + o * G + c * Z + l * Et, r[1] = u * P + d * M + f * K + m * H, r[5] = u * w + d * C + f * W + m * rt, r[9] = u * F + d * z + f * Y + m * ct, r[13] = u * S + d * G + f * Z + m * Et, r[2] = v * P + x * M + p * K + h * H, r[6] = v * w + x * C + p * W + h * rt, r[10] = v * F + x * z + p * Y + h * ct, r[14] = v * S + x * G + p * Z + h * Et, r[3] = A * P + b * M + y * K + D * H, r[7] = A * w + b * C + y * W + D * rt, r[11] = A * F + b * z + y * Y + D * ct, r[15] = A * S + b * G + y * Z + D * Et, this; + } + /** + * Multiplies every component of the matrix by the given scalar. + * + * @param {number} s - The scalar. + * @return {Matrix4} A reference to this matrix. + */ + multiplyScalar(t) { + const e = this.elements; + return e[0] *= t, e[4] *= t, e[8] *= t, e[12] *= t, e[1] *= t, e[5] *= t, e[9] *= t, e[13] *= t, e[2] *= t, e[6] *= t, e[10] *= t, e[14] *= t, e[3] *= t, e[7] *= t, e[11] *= t, e[15] *= t, 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 t = this.elements, e = t[0], n = t[4], s = t[8], r = t[12], a = t[1], o = t[5], c = t[9], l = t[13], u = t[2], d = t[6], f = t[10], m = t[14], v = t[3], x = t[7], p = t[11], h = t[15]; + return v * (+r * c * d - s * l * d - r * o * f + n * l * f + s * o * m - n * c * m) + x * (+e * c * m - e * l * f + r * a * f - s * a * m + s * l * u - r * c * u) + p * (+e * l * d - e * o * m - r * a * d + n * a * m + r * o * u - n * l * u) + h * (-s * o * u - e * c * d + e * o * f + s * a * d - n * a * f + n * c * u); + } + /** + * Transposes this matrix in place. + * + * @return {Matrix4} A reference to this matrix. + */ + transpose() { + const t = this.elements; + let e; + return e = t[1], t[1] = t[4], t[4] = e, e = t[2], t[2] = t[8], t[8] = e, e = t[6], t[6] = t[9], t[9] = e, e = t[3], t[3] = t[12], t[12] = e, e = t[7], t[7] = t[13], t[13] = e, e = t[11], t[11] = t[14], t[14] = e, 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(t, e, n) { + const s = this.elements; + return t.isVector3 ? (s[12] = t.x, s[13] = t.y, s[14] = t.z) : (s[12] = t, s[13] = e, s[14] = n), 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 t = this.elements, e = t[0], n = t[1], s = t[2], r = t[3], a = t[4], o = t[5], c = t[6], l = t[7], u = t[8], d = t[9], f = t[10], m = t[11], v = t[12], x = t[13], p = t[14], h = t[15], A = d * p * l - x * f * l + x * c * m - o * p * m - d * c * h + o * f * h, b = v * f * l - u * p * l - v * c * m + a * p * m + u * c * h - a * f * h, y = u * x * l - v * d * l + v * o * m - a * x * m - u * o * h + a * d * h, D = v * d * c - u * x * c - v * o * f + a * x * f + u * o * p - a * d * p, P = e * A + n * b + s * y + r * D; + if (P === 0) return this.set(0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0); + const w = 1 / P; + return t[0] = A * w, t[1] = (x * f * r - d * p * r - x * s * m + n * p * m + d * s * h - n * f * h) * w, t[2] = (o * p * r - x * c * r + x * s * l - n * p * l - o * s * h + n * c * h) * w, t[3] = (d * c * r - o * f * r - d * s * l + n * f * l + o * s * m - n * c * m) * w, t[4] = b * w, t[5] = (u * p * r - v * f * r + v * s * m - e * p * m - u * s * h + e * f * h) * w, t[6] = (v * c * r - a * p * r - v * s * l + e * p * l + a * s * h - e * c * h) * w, t[7] = (a * f * r - u * c * r + u * s * l - e * f * l - a * s * m + e * c * m) * w, t[8] = y * w, t[9] = (v * d * r - u * x * r - v * n * m + e * x * m + u * n * h - e * d * h) * w, t[10] = (a * x * r - v * o * r + v * n * l - e * x * l - a * n * h + e * o * h) * w, t[11] = (u * o * r - a * d * r - u * n * l + e * d * l + a * n * m - e * o * m) * w, t[12] = D * w, t[13] = (u * x * s - v * d * s + v * n * f - e * x * f - u * n * p + e * d * p) * w, t[14] = (v * o * s - a * x * s - v * n * c + e * x * c + a * n * p - e * o * p) * w, t[15] = (a * d * s - u * o * s + u * n * c - e * d * c - a * n * f + e * o * f) * w, 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(t) { + const e = this.elements, n = t.x, s = t.y, r = t.z; + return e[0] *= n, e[4] *= s, e[8] *= r, e[1] *= n, e[5] *= s, e[9] *= r, e[2] *= n, e[6] *= s, e[10] *= r, e[3] *= n, e[7] *= s, e[11] *= r, this; + } + /** + * Gets the maximum scale value of the three axes. + * + * @return {number} The maximum scale. + */ + getMaxScaleOnAxis() { + const t = this.elements, e = t[0] * t[0] + t[1] * t[1] + t[2] * t[2], n = t[4] * t[4] + t[5] * t[5] + t[6] * t[6], s = t[8] * t[8] + t[9] * t[9] + t[10] * t[10]; + return Math.sqrt(Math.max(e, n, s)); + } + /** + * 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(t, e, n) { + return t.isVector3 ? this.set( + 1, + 0, + 0, + t.x, + 0, + 1, + 0, + t.y, + 0, + 0, + 1, + t.z, + 0, + 0, + 0, + 1 + ) : this.set( + 1, + 0, + 0, + t, + 0, + 1, + 0, + e, + 0, + 0, + 1, + n, + 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(t) { + const e = Math.cos(t), n = Math.sin(t); + return this.set( + 1, + 0, + 0, + 0, + 0, + e, + -n, + 0, + 0, + n, + e, + 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(t) { + const e = Math.cos(t), n = Math.sin(t); + return this.set( + e, + 0, + n, + 0, + 0, + 1, + 0, + 0, + -n, + 0, + e, + 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(t) { + const e = Math.cos(t), n = Math.sin(t); + return this.set( + e, + -n, + 0, + 0, + n, + e, + 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(t, e) { + const n = Math.cos(e), s = Math.sin(e), r = 1 - n, a = t.x, o = t.y, c = t.z, l = r * a, u = r * o; + return this.set( + l * a + n, + l * o - s * c, + l * c + s * o, + 0, + l * o + s * c, + u * o + n, + u * c - s * a, + 0, + l * c - s * o, + u * c + s * a, + r * c * c + n, + 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(t, e, n) { + return this.set( + t, + 0, + 0, + 0, + 0, + e, + 0, + 0, + 0, + 0, + n, + 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(t, e, n, s, r, a) { + return this.set( + 1, + n, + r, + 0, + t, + 1, + a, + 0, + e, + s, + 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(t, e, n) { + const s = this.elements, r = e._x, a = e._y, o = e._z, c = e._w, l = r + r, u = a + a, d = o + o, f = r * l, m = r * u, v = r * d, x = a * u, p = a * d, h = o * d, A = c * l, b = c * u, y = c * d, D = n.x, P = n.y, w = n.z; + return s[0] = (1 - (x + h)) * D, s[1] = (m + y) * D, s[2] = (v - b) * D, s[3] = 0, s[4] = (m - y) * P, s[5] = (1 - (f + h)) * P, s[6] = (p + A) * P, s[7] = 0, s[8] = (v + b) * w, s[9] = (p - A) * w, s[10] = (1 - (f + x)) * w, s[11] = 0, s[12] = t.x, s[13] = t.y, s[14] = t.z, s[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(t, e, n) { + const s = this.elements; + let r = kn.set(s[0], s[1], s[2]).length(); + const a = kn.set(s[4], s[5], s[6]).length(), o = kn.set(s[8], s[9], s[10]).length(); + this.determinant() < 0 && (r = -r), t.x = s[12], t.y = s[13], t.z = s[14], Be.copy(this); + const l = 1 / r, u = 1 / a, d = 1 / o; + return Be.elements[0] *= l, Be.elements[1] *= l, Be.elements[2] *= l, Be.elements[4] *= u, Be.elements[5] *= u, Be.elements[6] *= u, Be.elements[8] *= d, Be.elements[9] *= d, Be.elements[10] *= d, e.setFromRotationMatrix(Be), n.x = r, n.y = a, n.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(t, e, n, s, r, a, o = Ye, c = !1) { + const l = this.elements, u = 2 * r / (e - t), d = 2 * r / (n - s), f = (e + t) / (e - t), m = (n + s) / (n - s); + let v, x; + if (c) + v = r / (a - r), x = a * r / (a - r); + else if (o === Ye) + v = -(a + r) / (a - r), x = -2 * a * r / (a - r); + else if (o === as) + v = -a / (a - r), x = -a * r / (a - r); + else + throw new Error("THREE.Matrix4.makePerspective(): Invalid coordinate system: " + o); + return l[0] = u, l[4] = 0, l[8] = f, l[12] = 0, l[1] = 0, l[5] = d, l[9] = m, l[13] = 0, l[2] = 0, l[6] = 0, l[10] = v, l[14] = x, l[3] = 0, l[7] = 0, l[11] = -1, l[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(t, e, n, s, r, a, o = Ye, c = !1) { + const l = this.elements, u = 2 / (e - t), d = 2 / (n - s), f = -(e + t) / (e - t), m = -(n + s) / (n - s); + let v, x; + if (c) + v = 1 / (a - r), x = a / (a - r); + else if (o === Ye) + v = -2 / (a - r), x = -(a + r) / (a - r); + else if (o === as) + v = -1 / (a - r), x = -r / (a - r); + else + throw new Error("THREE.Matrix4.makeOrthographic(): Invalid coordinate system: " + o); + return l[0] = u, l[4] = 0, l[8] = 0, l[12] = f, l[1] = 0, l[5] = d, l[9] = 0, l[13] = m, l[2] = 0, l[6] = 0, l[10] = v, l[14] = x, l[3] = 0, l[7] = 0, l[11] = 0, l[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(t) { + const e = this.elements, n = t.elements; + for (let s = 0; s < 16; s++) + if (e[s] !== n[s]) return !1; + return !0; + } + /** + * Sets the elements of the matrix from the given array. + * + * @param {Array} 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(t, e = 0) { + for (let n = 0; n < 16; n++) + this.elements[n] = t[n + e]; + 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} [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} The matrix elements in column-major order. + */ + toArray(t = [], e = 0) { + const n = this.elements; + return t[e] = n[0], t[e + 1] = n[1], t[e + 2] = n[2], t[e + 3] = n[3], t[e + 4] = n[4], t[e + 5] = n[5], t[e + 6] = n[6], t[e + 7] = n[7], t[e + 8] = n[8], t[e + 9] = n[9], t[e + 10] = n[10], t[e + 11] = n[11], t[e + 12] = n[12], t[e + 13] = n[13], t[e + 14] = n[14], t[e + 15] = n[15], t; + } +} +const kn = /* @__PURE__ */ new N(), Be = /* @__PURE__ */ new ae(), tc = /* @__PURE__ */ new N(0, 0, 0), ec = /* @__PURE__ */ new N(1, 1, 1), hn = /* @__PURE__ */ new N(), Ni = /* @__PURE__ */ new N(), Ce = /* @__PURE__ */ new N(), va = /* @__PURE__ */ new ae(), xa = /* @__PURE__ */ new In(); +class je { + /** + * 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(t = 0, e = 0, n = 0, s = je.DEFAULT_ORDER) { + this.isEuler = !0, this._x = t, this._y = e, this._z = n, this._order = s; + } + /** + * The angle of the x axis in radians. + * + * @type {number} + * @default 0 + */ + get x() { + return this._x; + } + set x(t) { + this._x = t, this._onChangeCallback(); + } + /** + * The angle of the y axis in radians. + * + * @type {number} + * @default 0 + */ + get y() { + return this._y; + } + set y(t) { + this._y = t, this._onChangeCallback(); + } + /** + * The angle of the z axis in radians. + * + * @type {number} + * @default 0 + */ + get z() { + return this._z; + } + set z(t) { + this._z = t, this._onChangeCallback(); + } + /** + * A string representing the order that the rotations are applied. + * + * @type {string} + * @default 'XYZ' + */ + get order() { + return this._order; + } + set order(t) { + this._order = t, 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(t, e, n, s = this._order) { + return this._x = t, this._y = e, this._z = n, this._order = s, 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(t) { + return this._x = t._x, this._y = t._y, this._z = t._z, this._order = t._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(t, e = this._order, n = !0) { + const s = t.elements, r = s[0], a = s[4], o = s[8], c = s[1], l = s[5], u = s[9], d = s[2], f = s[6], m = s[10]; + switch (e) { + case "XYZ": + this._y = Math.asin(Bt(o, -1, 1)), Math.abs(o) < 0.9999999 ? (this._x = Math.atan2(-u, m), this._z = Math.atan2(-a, r)) : (this._x = Math.atan2(f, l), this._z = 0); + break; + case "YXZ": + this._x = Math.asin(-Bt(u, -1, 1)), Math.abs(u) < 0.9999999 ? (this._y = Math.atan2(o, m), this._z = Math.atan2(c, l)) : (this._y = Math.atan2(-d, r), this._z = 0); + break; + case "ZXY": + this._x = Math.asin(Bt(f, -1, 1)), Math.abs(f) < 0.9999999 ? (this._y = Math.atan2(-d, m), this._z = Math.atan2(-a, l)) : (this._y = 0, this._z = Math.atan2(c, r)); + break; + case "ZYX": + this._y = Math.asin(-Bt(d, -1, 1)), Math.abs(d) < 0.9999999 ? (this._x = Math.atan2(f, m), this._z = Math.atan2(c, r)) : (this._x = 0, this._z = Math.atan2(-a, l)); + break; + case "YZX": + this._z = Math.asin(Bt(c, -1, 1)), Math.abs(c) < 0.9999999 ? (this._x = Math.atan2(-u, l), this._y = Math.atan2(-d, r)) : (this._x = 0, this._y = Math.atan2(o, m)); + break; + case "XZY": + this._z = Math.asin(-Bt(a, -1, 1)), Math.abs(a) < 0.9999999 ? (this._x = Math.atan2(f, l), this._y = Math.atan2(o, r)) : (this._x = Math.atan2(-u, m), this._y = 0); + break; + default: + console.warn("THREE.Euler: .setFromRotationMatrix() encountered an unknown order: " + e); + } + return this._order = e, n === !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(t, e, n) { + return va.makeRotationFromQuaternion(t), this.setFromRotationMatrix(va, e, n); + } + /** + * 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(t, e = this._order) { + return this.set(t.x, t.y, t.z, e); + } + /** + * 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(t) { + return xa.setFromEuler(this), this.setFromQuaternion(xa, t); + } + /** + * 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(t) { + return t._x === this._x && t._y === this._y && t._z === this._z && t._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} array - An array holding the Euler component values. + * @return {Euler} A reference to this Euler instance. + */ + fromArray(t) { + return this._x = t[0], this._y = t[1], this._z = t[2], t[3] !== void 0 && (this._order = t[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} [array=[]] - The target array holding the Euler components. + * @param {number} [offset=0] - Index of the first element in the array. + * @return {Array} The Euler components. + */ + toArray(t = [], e = 0) { + return t[e] = this._x, t[e + 1] = this._y, t[e + 2] = this._z, t[e + 3] = this._order, t; + } + _onChange(t) { + return this._onChangeCallback = t, this; + } + _onChangeCallback() { + } + *[Symbol.iterator]() { + yield this._x, yield this._y, yield this._z, yield this._order; + } +} +je.DEFAULT_ORDER = "XYZ"; +class jr { + /** + * 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(t) { + this.mask = (1 << t | 0) >>> 0; + } + /** + * Adds membership of the given layer. + * + * @param {number} layer - The layer to enable. + */ + enable(t) { + this.mask |= 1 << t | 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(t) { + this.mask ^= 1 << t | 0; + } + /** + * Removes membership of the given layer. + * + * @param {number} layer - The layer to enable. + */ + disable(t) { + this.mask &= ~(1 << t | 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(t) { + return (this.mask & t.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(t) { + return (this.mask & (1 << t | 0)) !== 0; + } +} +let nc = 0; +const Ma = /* @__PURE__ */ new N(), Wn = /* @__PURE__ */ new In(), Qe = /* @__PURE__ */ new ae(), Fi = /* @__PURE__ */ new N(), pi = /* @__PURE__ */ new N(), ic = /* @__PURE__ */ new N(), sc = /* @__PURE__ */ new In(), Sa = /* @__PURE__ */ new N(1, 0, 0), Ea = /* @__PURE__ */ new N(0, 1, 0), ya = /* @__PURE__ */ new N(0, 0, 1), Ta = { type: "added" }, rc = { type: "removed" }, Xn = { type: "childadded", child: null }, Ts = { type: "childremoved", child: null }; +class ge extends Fn { + /** + * Constructs a new 3D object. + */ + constructor() { + super(), this.isObject3D = !0, Object.defineProperty(this, "id", { value: nc++ }), this.uuid = yi(), this.name = "", this.type = "Object3D", this.parent = null, this.children = [], this.up = ge.DEFAULT_UP.clone(); + const t = new N(), e = new je(), n = new In(), s = new N(1, 1, 1); + function r() { + n.setFromEuler(e, !1); + } + function a() { + e.setFromQuaternion(n, void 0, !1); + } + e._onChange(r), n._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: t + }, + /** + * 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: e + }, + /** + * Represents the object's local rotation as Quaternions. + * + * @name Object3D#quaternion + * @type {Quaternion} + */ + quaternion: { + configurable: !0, + enumerable: !0, + value: n + }, + /** + * Represents the object's local scale. + * + * @name Object3D#scale + * @type {Vector3} + * @default (1,1,1) + */ + scale: { + configurable: !0, + enumerable: !0, + value: s + }, + /** + * Represents the object's model-view matrix. + * + * @name Object3D#modelViewMatrix + * @type {Matrix4} + */ + modelViewMatrix: { + value: new ae() + }, + /** + * Represents the object's normal matrix. + * + * @name Object3D#normalMatrix + * @type {Matrix3} + */ + normalMatrix: { + value: new It() + } + }), this.matrix = new ae(), this.matrixWorld = new ae(), this.matrixAutoUpdate = ge.DEFAULT_MATRIX_AUTO_UPDATE, this.matrixWorldAutoUpdate = ge.DEFAULT_MATRIX_WORLD_AUTO_UPDATE, this.matrixWorldNeedsUpdate = !1, this.layers = new jr(), 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(t) { + this.matrixAutoUpdate && this.updateMatrix(), this.matrix.premultiply(t), 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(t) { + return this.quaternion.premultiply(t), 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(t, e) { + this.quaternion.setFromAxisAngle(t, e); + } + /** + * Sets the given rotation represented as Euler angles to the 3D object. + * + * @param {Euler} euler - The Euler angles. + */ + setRotationFromEuler(t) { + this.quaternion.setFromEuler(t, !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(t) { + this.quaternion.setFromRotationMatrix(t); + } + /** + * Sets the given rotation represented as a Quaternion to the 3D object. + * + * @param {Quaternion} q - The Quaternion + */ + setRotationFromQuaternion(t) { + this.quaternion.copy(t); + } + /** + * 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(t, e) { + return Wn.setFromAxisAngle(t, e), this.quaternion.multiply(Wn), 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(t, e) { + return Wn.setFromAxisAngle(t, e), this.quaternion.premultiply(Wn), 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(t) { + return this.rotateOnAxis(Sa, t); + } + /** + * 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(t) { + return this.rotateOnAxis(Ea, t); + } + /** + * 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(t) { + return this.rotateOnAxis(ya, t); + } + /** + * 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(t, e) { + return Ma.copy(t).applyQuaternion(this.quaternion), this.position.add(Ma.multiplyScalar(e)), 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(t) { + return this.translateOnAxis(Sa, t); + } + /** + * 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(t) { + return this.translateOnAxis(Ea, t); + } + /** + * 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(t) { + return this.translateOnAxis(ya, t); + } + /** + * 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(t) { + return this.updateWorldMatrix(!0, !1), t.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(t) { + return this.updateWorldMatrix(!0, !1), t.applyMatrix4(Qe.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(t, e, n) { + t.isVector3 ? Fi.copy(t) : Fi.set(t, e, n); + const s = this.parent; + this.updateWorldMatrix(!0, !1), pi.setFromMatrixPosition(this.matrixWorld), this.isCamera || this.isLight ? Qe.lookAt(pi, Fi, this.up) : Qe.lookAt(Fi, pi, this.up), this.quaternion.setFromRotationMatrix(Qe), s && (Qe.extractRotation(s.matrixWorld), Wn.setFromRotationMatrix(Qe), this.quaternion.premultiply(Wn.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(t) { + if (arguments.length > 1) { + for (let e = 0; e < arguments.length; e++) + this.add(arguments[e]); + return this; + } + return t === this ? (console.error("THREE.Object3D.add: object can't be added as a child of itself.", t), this) : (t && t.isObject3D ? (t.removeFromParent(), t.parent = this, this.children.push(t), t.dispatchEvent(Ta), Xn.child = t, this.dispatchEvent(Xn), Xn.child = null) : console.error("THREE.Object3D.add: object not an instance of THREE.Object3D.", t), 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(t) { + if (arguments.length > 1) { + for (let n = 0; n < arguments.length; n++) + this.remove(arguments[n]); + return this; + } + const e = this.children.indexOf(t); + return e !== -1 && (t.parent = null, this.children.splice(e, 1), t.dispatchEvent(rc), Ts.child = t, this.dispatchEvent(Ts), Ts.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 t = this.parent; + return t !== null && t.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(t) { + return this.updateWorldMatrix(!0, !1), Qe.copy(this.matrixWorld).invert(), t.parent !== null && (t.parent.updateWorldMatrix(!0, !1), Qe.multiply(t.parent.matrixWorld)), t.applyMatrix4(Qe), t.removeFromParent(), t.parent = this, this.children.push(t), t.updateWorldMatrix(!1, !0), t.dispatchEvent(Ta), Xn.child = t, this.dispatchEvent(Xn), Xn.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(t) { + return this.getObjectByProperty("id", t); + } + /** + * 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(t) { + return this.getObjectByProperty("name", t); + } + /** + * 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(t, e) { + if (this[t] === e) return this; + for (let n = 0, s = this.children.length; n < s; n++) { + const a = this.children[n].getObjectByProperty(t, e); + 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} result - The method stores the result in this array. + * @return {Array} The found 3D objects. + */ + getObjectsByProperty(t, e, n = []) { + this[t] === e && n.push(this); + const s = this.children; + for (let r = 0, a = s.length; r < a; r++) + s[r].getObjectsByProperty(t, e, n); + return n; + } + /** + * 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(t) { + return this.updateWorldMatrix(!0, !1), t.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(t) { + return this.updateWorldMatrix(!0, !1), this.matrixWorld.decompose(pi, t, ic), t; + } + /** + * 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(t) { + return this.updateWorldMatrix(!0, !1), this.matrixWorld.decompose(pi, sc, t), t; + } + /** + * 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(t) { + this.updateWorldMatrix(!0, !1); + const e = this.matrixWorld.elements; + return t.set(e[8], e[9], e[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} 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(t) { + t(this); + const e = this.children; + for (let n = 0, s = e.length; n < s; n++) + e[n].traverse(t); + } + /** + * 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(t) { + if (this.visible === !1) return; + t(this); + const e = this.children; + for (let n = 0, s = e.length; n < s; n++) + e[n].traverseVisible(t); + } + /** + * 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(t) { + const e = this.parent; + e !== null && (t(e), e.traverseAncestors(t)); + } + /** + * 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(t) { + this.matrixAutoUpdate && this.updateMatrix(), (this.matrixWorldNeedsUpdate || t) && (this.matrixWorldAutoUpdate === !0 && (this.parent === null ? this.matrixWorld.copy(this.matrix) : this.matrixWorld.multiplyMatrices(this.parent.matrixWorld, this.matrix)), this.matrixWorldNeedsUpdate = !1, t = !0); + const e = this.children; + for (let n = 0, s = e.length; n < s; n++) + e[n].updateMatrixWorld(t); + } + /** + * 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(t, e) { + const n = this.parent; + if (t === !0 && n !== null && n.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)), e === !0) { + const s = this.children; + for (let r = 0, a = s.length; r < a; r++) + s[r].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(t) { + const e = t === void 0 || typeof t == "string", n = {}; + e && (t = { + geometries: {}, + materials: {}, + textures: {}, + images: {}, + shapes: {}, + skeletons: {}, + animations: {}, + nodes: {} + }, n.metadata = { + version: 4.7, + type: "Object", + generator: "Object3D.toJSON" + }); + const s = {}; + s.uuid = this.uuid, s.type = this.type, this.name !== "" && (s.name = this.name), this.castShadow === !0 && (s.castShadow = !0), this.receiveShadow === !0 && (s.receiveShadow = !0), this.visible === !1 && (s.visible = !1), this.frustumCulled === !1 && (s.frustumCulled = !1), this.renderOrder !== 0 && (s.renderOrder = this.renderOrder), Object.keys(this.userData).length > 0 && (s.userData = this.userData), s.layers = this.layers.mask, s.matrix = this.matrix.toArray(), s.up = this.up.toArray(), this.matrixAutoUpdate === !1 && (s.matrixAutoUpdate = !1), this.isInstancedMesh && (s.type = "InstancedMesh", s.count = this.count, s.instanceMatrix = this.instanceMatrix.toJSON(), this.instanceColor !== null && (s.instanceColor = this.instanceColor.toJSON())), this.isBatchedMesh && (s.type = "BatchedMesh", s.perObjectFrustumCulled = this.perObjectFrustumCulled, s.sortObjects = this.sortObjects, s.drawRanges = this._drawRanges, s.reservedRanges = this._reservedRanges, s.geometryInfo = this._geometryInfo.map((o) => ({ + ...o, + boundingBox: o.boundingBox ? o.boundingBox.toJSON() : void 0, + boundingSphere: o.boundingSphere ? o.boundingSphere.toJSON() : void 0 + })), s.instanceInfo = this._instanceInfo.map((o) => ({ ...o })), s.availableInstanceIds = this._availableInstanceIds.slice(), s.availableGeometryIds = this._availableGeometryIds.slice(), s.nextIndexStart = this._nextIndexStart, s.nextVertexStart = this._nextVertexStart, s.geometryCount = this._geometryCount, s.maxInstanceCount = this._maxInstanceCount, s.maxVertexCount = this._maxVertexCount, s.maxIndexCount = this._maxIndexCount, s.geometryInitialized = this._geometryInitialized, s.matricesTexture = this._matricesTexture.toJSON(t), s.indirectTexture = this._indirectTexture.toJSON(t), this._colorsTexture !== null && (s.colorsTexture = this._colorsTexture.toJSON(t)), this.boundingSphere !== null && (s.boundingSphere = this.boundingSphere.toJSON()), this.boundingBox !== null && (s.boundingBox = this.boundingBox.toJSON())); + function r(o, c) { + return o[c.uuid] === void 0 && (o[c.uuid] = c.toJSON(t)), c.uuid; + } + if (this.isScene) + this.background && (this.background.isColor ? s.background = this.background.toJSON() : this.background.isTexture && (s.background = this.background.toJSON(t).uuid)), this.environment && this.environment.isTexture && this.environment.isRenderTargetTexture !== !0 && (s.environment = this.environment.toJSON(t).uuid); + else if (this.isMesh || this.isLine || this.isPoints) { + s.geometry = r(t.geometries, this.geometry); + const o = this.geometry.parameters; + if (o !== void 0 && o.shapes !== void 0) { + const c = o.shapes; + if (Array.isArray(c)) + for (let l = 0, u = c.length; l < u; l++) { + const d = c[l]; + r(t.shapes, d); + } + else + r(t.shapes, c); + } + } + if (this.isSkinnedMesh && (s.bindMode = this.bindMode, s.bindMatrix = this.bindMatrix.toArray(), this.skeleton !== void 0 && (r(t.skeletons, this.skeleton), s.skeleton = this.skeleton.uuid)), this.material !== void 0) + if (Array.isArray(this.material)) { + const o = []; + for (let c = 0, l = this.material.length; c < l; c++) + o.push(r(t.materials, this.material[c])); + s.material = o; + } else + s.material = r(t.materials, this.material); + if (this.children.length > 0) { + s.children = []; + for (let o = 0; o < this.children.length; o++) + s.children.push(this.children[o].toJSON(t).object); + } + if (this.animations.length > 0) { + s.animations = []; + for (let o = 0; o < this.animations.length; o++) { + const c = this.animations[o]; + s.animations.push(r(t.animations, c)); + } + } + if (e) { + const o = a(t.geometries), c = a(t.materials), l = a(t.textures), u = a(t.images), d = a(t.shapes), f = a(t.skeletons), m = a(t.animations), v = a(t.nodes); + o.length > 0 && (n.geometries = o), c.length > 0 && (n.materials = c), l.length > 0 && (n.textures = l), u.length > 0 && (n.images = u), d.length > 0 && (n.shapes = d), f.length > 0 && (n.skeletons = f), m.length > 0 && (n.animations = m), v.length > 0 && (n.nodes = v); + } + return n.object = s, n; + function a(o) { + const c = []; + for (const l in o) { + const u = o[l]; + delete u.metadata, c.push(u); + } + return c; + } + } + /** + * 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(t) { + return new this.constructor().copy(this, t); + } + /** + * 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(t, e = !0) { + if (this.name = t.name, this.up.copy(t.up), this.position.copy(t.position), this.rotation.order = t.rotation.order, this.quaternion.copy(t.quaternion), this.scale.copy(t.scale), this.matrix.copy(t.matrix), this.matrixWorld.copy(t.matrixWorld), this.matrixAutoUpdate = t.matrixAutoUpdate, this.matrixWorldAutoUpdate = t.matrixWorldAutoUpdate, this.matrixWorldNeedsUpdate = t.matrixWorldNeedsUpdate, this.layers.mask = t.layers.mask, this.visible = t.visible, this.castShadow = t.castShadow, this.receiveShadow = t.receiveShadow, this.frustumCulled = t.frustumCulled, this.renderOrder = t.renderOrder, this.animations = t.animations.slice(), this.userData = JSON.parse(JSON.stringify(t.userData)), e === !0) + for (let n = 0; n < t.children.length; n++) { + const s = t.children[n]; + this.add(s.clone()); + } + return this; + } +} +ge.DEFAULT_UP = /* @__PURE__ */ new N(0, 1, 0); +ge.DEFAULT_MATRIX_AUTO_UPDATE = !0; +ge.DEFAULT_MATRIX_WORLD_AUTO_UPDATE = !0; +const ze = /* @__PURE__ */ new N(), tn = /* @__PURE__ */ new N(), bs = /* @__PURE__ */ new N(), en = /* @__PURE__ */ new N(), Yn = /* @__PURE__ */ new N(), qn = /* @__PURE__ */ new N(), ba = /* @__PURE__ */ new N(), As = /* @__PURE__ */ new N(), Rs = /* @__PURE__ */ new N(), ws = /* @__PURE__ */ new N(), Cs = /* @__PURE__ */ new re(), Ps = /* @__PURE__ */ new re(), Ds = /* @__PURE__ */ new re(); +class He { + /** + * 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(t = new N(), e = new N(), n = new N()) { + this.a = t, this.b = e, this.c = n; + } + /** + * 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(t, e, n, s) { + s.subVectors(n, e), ze.subVectors(t, e), s.cross(ze); + const r = s.lengthSq(); + return r > 0 ? s.multiplyScalar(1 / Math.sqrt(r)) : s.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(t, e, n, s, r) { + ze.subVectors(s, e), tn.subVectors(n, e), bs.subVectors(t, e); + const a = ze.dot(ze), o = ze.dot(tn), c = ze.dot(bs), l = tn.dot(tn), u = tn.dot(bs), d = a * l - o * o; + if (d === 0) + return r.set(0, 0, 0), null; + const f = 1 / d, m = (l * c - o * u) * f, v = (a * u - o * c) * f; + return r.set(1 - m - v, v, m); + } + /** + * 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(t, e, n, s) { + return this.getBarycoord(t, e, n, s, en) === null ? !1 : en.x >= 0 && en.y >= 0 && en.x + en.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(t, e, n, s, r, a, o, c) { + return this.getBarycoord(t, e, n, s, en) === null ? (c.x = 0, c.y = 0, "z" in c && (c.z = 0), "w" in c && (c.w = 0), null) : (c.setScalar(0), c.addScaledVector(r, en.x), c.addScaledVector(a, en.y), c.addScaledVector(o, en.z), c); + } + /** + * 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(t, e, n, s, r, a) { + return Cs.setScalar(0), Ps.setScalar(0), Ds.setScalar(0), Cs.fromBufferAttribute(t, e), Ps.fromBufferAttribute(t, n), Ds.fromBufferAttribute(t, s), a.setScalar(0), a.addScaledVector(Cs, r.x), a.addScaledVector(Ps, r.y), a.addScaledVector(Ds, r.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(t, e, n, s) { + return ze.subVectors(n, e), tn.subVectors(t, e), ze.cross(tn).dot(s) < 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(t, e, n) { + return this.a.copy(t), this.b.copy(e), this.c.copy(n), this; + } + /** + * Sets the triangle's vertices by copying the given array values. + * + * @param {Array} 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(t, e, n, s) { + return this.a.copy(t[e]), this.b.copy(t[n]), this.c.copy(t[s]), 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(t, e, n, s) { + return this.a.fromBufferAttribute(t, e), this.b.fromBufferAttribute(t, n), this.c.fromBufferAttribute(t, s), 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(t) { + return this.a.copy(t.a), this.b.copy(t.b), this.c.copy(t.c), this; + } + /** + * Computes the area of the triangle. + * + * @return {number} The triangle's area. + */ + getArea() { + return ze.subVectors(this.c, this.b), tn.subVectors(this.a, this.b), ze.cross(tn).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(t) { + return t.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(t) { + return He.getNormal(this.a, this.b, this.c, t); + } + /** + * 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(t) { + return t.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(t, e) { + return He.getBarycoord(t, this.a, this.b, this.c, e); + } + /** + * 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(t, e, n, s, r) { + return He.getInterpolation(t, this.a, this.b, this.c, e, n, s, r); + } + /** + * 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(t) { + return He.containsPoint(t, 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(t) { + return He.isFrontFacing(this.a, this.b, this.c, t); + } + /** + * 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(t) { + return t.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(t, e) { + const n = this.a, s = this.b, r = this.c; + let a, o; + Yn.subVectors(s, n), qn.subVectors(r, n), As.subVectors(t, n); + const c = Yn.dot(As), l = qn.dot(As); + if (c <= 0 && l <= 0) + return e.copy(n); + Rs.subVectors(t, s); + const u = Yn.dot(Rs), d = qn.dot(Rs); + if (u >= 0 && d <= u) + return e.copy(s); + const f = c * d - u * l; + if (f <= 0 && c >= 0 && u <= 0) + return a = c / (c - u), e.copy(n).addScaledVector(Yn, a); + ws.subVectors(t, r); + const m = Yn.dot(ws), v = qn.dot(ws); + if (v >= 0 && m <= v) + return e.copy(r); + const x = m * l - c * v; + if (x <= 0 && l >= 0 && v <= 0) + return o = l / (l - v), e.copy(n).addScaledVector(qn, o); + const p = u * v - m * d; + if (p <= 0 && d - u >= 0 && m - v >= 0) + return ba.subVectors(r, s), o = (d - u) / (d - u + (m - v)), e.copy(s).addScaledVector(ba, o); + const h = 1 / (p + x + f); + return a = x * h, o = f * h, e.copy(n).addScaledVector(Yn, a).addScaledVector(qn, 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(t) { + return t.a.equals(this.a) && t.b.equals(this.b) && t.c.equals(this.c); + } +} +const Ro = { + 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 +}, un = { h: 0, s: 0, l: 0 }, Oi = { h: 0, s: 0, l: 0 }; +function Ls(i, t, e) { + return e < 0 && (e += 1), e > 1 && (e -= 1), e < 1 / 6 ? i + (t - i) * 6 * e : e < 1 / 2 ? t : e < 2 / 3 ? i + (t - i) * 6 * (2 / 3 - e) : i; +} +class Vt { + /** + * 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(t, e, n) { + return this.isColor = !0, this.r = 1, this.g = 1, this.b = 1, this.set(t, e, n); + } + /** + * 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(t, e, n) { + if (e === void 0 && n === void 0) { + const s = t; + s && s.isColor ? this.copy(s) : typeof s == "number" ? this.setHex(s) : typeof s == "string" && this.setStyle(s); + } else + this.setRGB(t, e, n); + 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(t) { + return this.r = t, this.g = t, this.b = t, 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(t, e = Te) { + return t = Math.floor(t), this.r = (t >> 16 & 255) / 255, this.g = (t >> 8 & 255) / 255, this.b = (t & 255) / 255, kt.colorSpaceToWorking(this, e), 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(t, e, n, s = kt.workingColorSpace) { + return this.r = t, this.g = e, this.b = n, kt.colorSpaceToWorking(this, s), 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(t, e, n, s = kt.workingColorSpace) { + if (t = kl(t, 1), e = Bt(e, 0, 1), n = Bt(n, 0, 1), e === 0) + this.r = this.g = this.b = n; + else { + const r = n <= 0.5 ? n * (1 + e) : n + e - n * e, a = 2 * n - r; + this.r = Ls(a, r, t + 1 / 3), this.g = Ls(a, r, t), this.b = Ls(a, r, t - 1 / 3); + } + return kt.colorSpaceToWorking(this, s), 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(t, e = Te) { + function n(r) { + r !== void 0 && parseFloat(r) < 1 && console.warn("THREE.Color: Alpha component of " + t + " will be ignored."); + } + let s; + if (s = /^(\w+)\(([^\)]*)\)/.exec(t)) { + let r; + const a = s[1], o = s[2]; + switch (a) { + case "rgb": + case "rgba": + if (r = /^\s*(\d+)\s*,\s*(\d+)\s*,\s*(\d+)\s*(?:,\s*(\d*\.?\d+)\s*)?$/.exec(o)) + return n(r[4]), this.setRGB( + Math.min(255, parseInt(r[1], 10)) / 255, + Math.min(255, parseInt(r[2], 10)) / 255, + Math.min(255, parseInt(r[3], 10)) / 255, + e + ); + if (r = /^\s*(\d+)\%\s*,\s*(\d+)\%\s*,\s*(\d+)\%\s*(?:,\s*(\d*\.?\d+)\s*)?$/.exec(o)) + return n(r[4]), this.setRGB( + Math.min(100, parseInt(r[1], 10)) / 100, + Math.min(100, parseInt(r[2], 10)) / 100, + Math.min(100, parseInt(r[3], 10)) / 100, + e + ); + break; + case "hsl": + case "hsla": + if (r = /^\s*(\d*\.?\d+)\s*,\s*(\d*\.?\d+)\%\s*,\s*(\d*\.?\d+)\%\s*(?:,\s*(\d*\.?\d+)\s*)?$/.exec(o)) + return n(r[4]), this.setHSL( + parseFloat(r[1]) / 360, + parseFloat(r[2]) / 100, + parseFloat(r[3]) / 100, + e + ); + break; + default: + console.warn("THREE.Color: Unknown color model " + t); + } + } else if (s = /^\#([A-Fa-f\d]+)$/.exec(t)) { + const r = s[1], a = r.length; + if (a === 3) + return this.setRGB( + parseInt(r.charAt(0), 16) / 15, + parseInt(r.charAt(1), 16) / 15, + parseInt(r.charAt(2), 16) / 15, + e + ); + if (a === 6) + return this.setHex(parseInt(r, 16), e); + console.warn("THREE.Color: Invalid hex color " + t); + } else if (t && t.length > 0) + return this.setColorName(t, e); + 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(t, e = Te) { + const n = Ro[t.toLowerCase()]; + return n !== void 0 ? this.setHex(n, e) : console.warn("THREE.Color: Unknown color " + t), 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(t) { + return this.r = t.r, this.g = t.g, this.b = t.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(t) { + return this.r = rn(t.r), this.g = rn(t.g), this.b = rn(t.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(t) { + return this.r = ii(t.r), this.g = ii(t.g), this.b = ii(t.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(t = Te) { + return kt.workingToColorSpace(_e.copy(this), t), Math.round(Bt(_e.r * 255, 0, 255)) * 65536 + Math.round(Bt(_e.g * 255, 0, 255)) * 256 + Math.round(Bt(_e.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(t = Te) { + return ("000000" + this.getHex(t).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(t, e = kt.workingColorSpace) { + kt.workingToColorSpace(_e.copy(this), e); + const n = _e.r, s = _e.g, r = _e.b, a = Math.max(n, s, r), o = Math.min(n, s, r); + let c, l; + const u = (o + a) / 2; + if (o === a) + c = 0, l = 0; + else { + const d = a - o; + switch (l = u <= 0.5 ? d / (a + o) : d / (2 - a - o), a) { + case n: + c = (s - r) / d + (s < r ? 6 : 0); + break; + case s: + c = (r - n) / d + 2; + break; + case r: + c = (n - s) / d + 4; + break; + } + c /= 6; + } + return t.h = c, t.s = l, t.l = u, t; + } + /** + * 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(t, e = kt.workingColorSpace) { + return kt.workingToColorSpace(_e.copy(this), e), t.r = _e.r, t.g = _e.g, t.b = _e.b, t; + } + /** + * 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(t = Te) { + kt.workingToColorSpace(_e.copy(this), t); + const e = _e.r, n = _e.g, s = _e.b; + return t !== Te ? `color(${t} ${e.toFixed(3)} ${n.toFixed(3)} ${s.toFixed(3)})` : `rgb(${Math.round(e * 255)},${Math.round(n * 255)},${Math.round(s * 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(t, e, n) { + return this.getHSL(un), this.setHSL(un.h + t, un.s + e, un.l + n); + } + /** + * 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(t) { + return this.r += t.r, this.g += t.g, this.b += t.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(t, e) { + return this.r = t.r + e.r, this.g = t.g + e.g, this.b = t.b + e.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(t) { + return this.r += t, this.g += t, this.b += t, 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(t) { + return this.r = Math.max(0, this.r - t.r), this.g = Math.max(0, this.g - t.g), this.b = Math.max(0, this.b - t.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(t) { + return this.r *= t.r, this.g *= t.g, this.b *= t.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(t) { + return this.r *= t, this.g *= t, this.b *= t, 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(t, e) { + return this.r += (t.r - this.r) * e, this.g += (t.g - this.g) * e, this.b += (t.b - this.b) * e, 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(t, e, n) { + return this.r = t.r + (e.r - t.r) * n, this.g = t.g + (e.g - t.g) * n, this.b = t.b + (e.b - t.b) * n, 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(t, e) { + this.getHSL(un), t.getHSL(Oi); + const n = ps(un.h, Oi.h, e), s = ps(un.s, Oi.s, e), r = ps(un.l, Oi.l, e); + return this.setHSL(n, s, r), 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(t) { + return this.r = t.x, this.g = t.y, this.b = t.z, this; + } + /** + * Transforms this color with the given 3x3 matrix. + * + * @param {Matrix3} m - The matrix. + * @return {Color} A reference to this color. + */ + applyMatrix3(t) { + const e = this.r, n = this.g, s = this.b, r = t.elements; + return this.r = r[0] * e + r[3] * n + r[6] * s, this.g = r[1] * e + r[4] * n + r[7] * s, this.b = r[2] * e + r[5] * n + r[8] * s, 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(t) { + return t.r === this.r && t.g === this.g && t.b === this.b; + } + /** + * Sets this color's RGB components from the given array. + * + * @param {Array} array - An array holding the RGB values. + * @param {number} [offset=0] - The offset into the array. + * @return {Color} A reference to this color. + */ + fromArray(t, e = 0) { + return this.r = t[e], this.g = t[e + 1], this.b = t[e + 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} [array=[]] - The target array holding the color components. + * @param {number} [offset=0] - Index of the first element in the array. + * @return {Array} The color components. + */ + toArray(t = [], e = 0) { + return t[e] = this.r, t[e + 1] = this.g, t[e + 2] = this.b, t; + } + /** + * 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(t, e) { + return this.r = t.getX(e), this.g = t.getY(e), this.b = t.getZ(e), 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 _e = /* @__PURE__ */ new Vt(); +Vt.NAMES = Ro; +let ac = 0; +class bi extends Fn { + /** + * Constructs a new material. + */ + constructor() { + super(), this.isMaterial = !0, Object.defineProperty(this, "id", { value: ac++ }), this.uuid = yi(), this.name = "", this.type = "Material", this.blending = ni, this.side = vn, this.vertexColors = !1, this.opacity = 1, this.transparent = !1, this.alphaHash = !1, this.blendSrc = Ks, this.blendDst = js, this.blendEquation = Cn, this.blendSrcAlpha = null, this.blendDstAlpha = null, this.blendEquationAlpha = null, this.blendColor = new Vt(0, 0, 0), this.blendAlpha = 0, this.depthFunc = si, this.depthTest = !0, this.depthWrite = !0, this.stencilWriteMask = 255, this.stencilFunc = ua, this.stencilRef = 0, this.stencilFuncMask = 255, this.stencilFail = Bn, this.stencilZFail = Bn, this.stencilZPass = Bn, 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(t) { + this._alphaTest > 0 != t > 0 && this.version++, this._alphaTest = t; + } + /** + * 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(t) { + if (t !== void 0) + for (const e in t) { + const n = t[e]; + if (n === void 0) { + console.warn(`THREE.Material: parameter '${e}' has value of undefined.`); + continue; + } + const s = this[e]; + if (s === void 0) { + console.warn(`THREE.Material: '${e}' is not a property of THREE.${this.type}.`); + continue; + } + s && s.isColor ? s.set(n) : s && s.isVector3 && n && n.isVector3 ? s.copy(n) : this[e] = n; + } + } + /** + * 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(t) { + const e = t === void 0 || typeof t == "string"; + e && (t = { + textures: {}, + images: {} + }); + const n = { + metadata: { + version: 4.7, + type: "Material", + generator: "Material.toJSON" + } + }; + n.uuid = this.uuid, n.type = this.type, this.name !== "" && (n.name = this.name), this.color && this.color.isColor && (n.color = this.color.getHex()), this.roughness !== void 0 && (n.roughness = this.roughness), this.metalness !== void 0 && (n.metalness = this.metalness), this.sheen !== void 0 && (n.sheen = this.sheen), this.sheenColor && this.sheenColor.isColor && (n.sheenColor = this.sheenColor.getHex()), this.sheenRoughness !== void 0 && (n.sheenRoughness = this.sheenRoughness), this.emissive && this.emissive.isColor && (n.emissive = this.emissive.getHex()), this.emissiveIntensity !== void 0 && this.emissiveIntensity !== 1 && (n.emissiveIntensity = this.emissiveIntensity), this.specular && this.specular.isColor && (n.specular = this.specular.getHex()), this.specularIntensity !== void 0 && (n.specularIntensity = this.specularIntensity), this.specularColor && this.specularColor.isColor && (n.specularColor = this.specularColor.getHex()), this.shininess !== void 0 && (n.shininess = this.shininess), this.clearcoat !== void 0 && (n.clearcoat = this.clearcoat), this.clearcoatRoughness !== void 0 && (n.clearcoatRoughness = this.clearcoatRoughness), this.clearcoatMap && this.clearcoatMap.isTexture && (n.clearcoatMap = this.clearcoatMap.toJSON(t).uuid), this.clearcoatRoughnessMap && this.clearcoatRoughnessMap.isTexture && (n.clearcoatRoughnessMap = this.clearcoatRoughnessMap.toJSON(t).uuid), this.clearcoatNormalMap && this.clearcoatNormalMap.isTexture && (n.clearcoatNormalMap = this.clearcoatNormalMap.toJSON(t).uuid, n.clearcoatNormalScale = this.clearcoatNormalScale.toArray()), this.sheenColorMap && this.sheenColorMap.isTexture && (n.sheenColorMap = this.sheenColorMap.toJSON(t).uuid), this.sheenRoughnessMap && this.sheenRoughnessMap.isTexture && (n.sheenRoughnessMap = this.sheenRoughnessMap.toJSON(t).uuid), this.dispersion !== void 0 && (n.dispersion = this.dispersion), this.iridescence !== void 0 && (n.iridescence = this.iridescence), this.iridescenceIOR !== void 0 && (n.iridescenceIOR = this.iridescenceIOR), this.iridescenceThicknessRange !== void 0 && (n.iridescenceThicknessRange = this.iridescenceThicknessRange), this.iridescenceMap && this.iridescenceMap.isTexture && (n.iridescenceMap = this.iridescenceMap.toJSON(t).uuid), this.iridescenceThicknessMap && this.iridescenceThicknessMap.isTexture && (n.iridescenceThicknessMap = this.iridescenceThicknessMap.toJSON(t).uuid), this.anisotropy !== void 0 && (n.anisotropy = this.anisotropy), this.anisotropyRotation !== void 0 && (n.anisotropyRotation = this.anisotropyRotation), this.anisotropyMap && this.anisotropyMap.isTexture && (n.anisotropyMap = this.anisotropyMap.toJSON(t).uuid), this.map && this.map.isTexture && (n.map = this.map.toJSON(t).uuid), this.matcap && this.matcap.isTexture && (n.matcap = this.matcap.toJSON(t).uuid), this.alphaMap && this.alphaMap.isTexture && (n.alphaMap = this.alphaMap.toJSON(t).uuid), this.lightMap && this.lightMap.isTexture && (n.lightMap = this.lightMap.toJSON(t).uuid, n.lightMapIntensity = this.lightMapIntensity), this.aoMap && this.aoMap.isTexture && (n.aoMap = this.aoMap.toJSON(t).uuid, n.aoMapIntensity = this.aoMapIntensity), this.bumpMap && this.bumpMap.isTexture && (n.bumpMap = this.bumpMap.toJSON(t).uuid, n.bumpScale = this.bumpScale), this.normalMap && this.normalMap.isTexture && (n.normalMap = this.normalMap.toJSON(t).uuid, n.normalMapType = this.normalMapType, n.normalScale = this.normalScale.toArray()), this.displacementMap && this.displacementMap.isTexture && (n.displacementMap = this.displacementMap.toJSON(t).uuid, n.displacementScale = this.displacementScale, n.displacementBias = this.displacementBias), this.roughnessMap && this.roughnessMap.isTexture && (n.roughnessMap = this.roughnessMap.toJSON(t).uuid), this.metalnessMap && this.metalnessMap.isTexture && (n.metalnessMap = this.metalnessMap.toJSON(t).uuid), this.emissiveMap && this.emissiveMap.isTexture && (n.emissiveMap = this.emissiveMap.toJSON(t).uuid), this.specularMap && this.specularMap.isTexture && (n.specularMap = this.specularMap.toJSON(t).uuid), this.specularIntensityMap && this.specularIntensityMap.isTexture && (n.specularIntensityMap = this.specularIntensityMap.toJSON(t).uuid), this.specularColorMap && this.specularColorMap.isTexture && (n.specularColorMap = this.specularColorMap.toJSON(t).uuid), this.envMap && this.envMap.isTexture && (n.envMap = this.envMap.toJSON(t).uuid, this.combine !== void 0 && (n.combine = this.combine)), this.envMapRotation !== void 0 && (n.envMapRotation = this.envMapRotation.toArray()), this.envMapIntensity !== void 0 && (n.envMapIntensity = this.envMapIntensity), this.reflectivity !== void 0 && (n.reflectivity = this.reflectivity), this.refractionRatio !== void 0 && (n.refractionRatio = this.refractionRatio), this.gradientMap && this.gradientMap.isTexture && (n.gradientMap = this.gradientMap.toJSON(t).uuid), this.transmission !== void 0 && (n.transmission = this.transmission), this.transmissionMap && this.transmissionMap.isTexture && (n.transmissionMap = this.transmissionMap.toJSON(t).uuid), this.thickness !== void 0 && (n.thickness = this.thickness), this.thicknessMap && this.thicknessMap.isTexture && (n.thicknessMap = this.thicknessMap.toJSON(t).uuid), this.attenuationDistance !== void 0 && this.attenuationDistance !== 1 / 0 && (n.attenuationDistance = this.attenuationDistance), this.attenuationColor !== void 0 && (n.attenuationColor = this.attenuationColor.getHex()), this.size !== void 0 && (n.size = this.size), this.shadowSide !== null && (n.shadowSide = this.shadowSide), this.sizeAttenuation !== void 0 && (n.sizeAttenuation = this.sizeAttenuation), this.blending !== ni && (n.blending = this.blending), this.side !== vn && (n.side = this.side), this.vertexColors === !0 && (n.vertexColors = !0), this.opacity < 1 && (n.opacity = this.opacity), this.transparent === !0 && (n.transparent = !0), this.blendSrc !== Ks && (n.blendSrc = this.blendSrc), this.blendDst !== js && (n.blendDst = this.blendDst), this.blendEquation !== Cn && (n.blendEquation = this.blendEquation), this.blendSrcAlpha !== null && (n.blendSrcAlpha = this.blendSrcAlpha), this.blendDstAlpha !== null && (n.blendDstAlpha = this.blendDstAlpha), this.blendEquationAlpha !== null && (n.blendEquationAlpha = this.blendEquationAlpha), this.blendColor && this.blendColor.isColor && (n.blendColor = this.blendColor.getHex()), this.blendAlpha !== 0 && (n.blendAlpha = this.blendAlpha), this.depthFunc !== si && (n.depthFunc = this.depthFunc), this.depthTest === !1 && (n.depthTest = this.depthTest), this.depthWrite === !1 && (n.depthWrite = this.depthWrite), this.colorWrite === !1 && (n.colorWrite = this.colorWrite), this.stencilWriteMask !== 255 && (n.stencilWriteMask = this.stencilWriteMask), this.stencilFunc !== ua && (n.stencilFunc = this.stencilFunc), this.stencilRef !== 0 && (n.stencilRef = this.stencilRef), this.stencilFuncMask !== 255 && (n.stencilFuncMask = this.stencilFuncMask), this.stencilFail !== Bn && (n.stencilFail = this.stencilFail), this.stencilZFail !== Bn && (n.stencilZFail = this.stencilZFail), this.stencilZPass !== Bn && (n.stencilZPass = this.stencilZPass), this.stencilWrite === !0 && (n.stencilWrite = this.stencilWrite), this.rotation !== void 0 && this.rotation !== 0 && (n.rotation = this.rotation), this.polygonOffset === !0 && (n.polygonOffset = !0), this.polygonOffsetFactor !== 0 && (n.polygonOffsetFactor = this.polygonOffsetFactor), this.polygonOffsetUnits !== 0 && (n.polygonOffsetUnits = this.polygonOffsetUnits), this.linewidth !== void 0 && this.linewidth !== 1 && (n.linewidth = this.linewidth), this.dashSize !== void 0 && (n.dashSize = this.dashSize), this.gapSize !== void 0 && (n.gapSize = this.gapSize), this.scale !== void 0 && (n.scale = this.scale), this.dithering === !0 && (n.dithering = !0), this.alphaTest > 0 && (n.alphaTest = this.alphaTest), this.alphaHash === !0 && (n.alphaHash = !0), this.alphaToCoverage === !0 && (n.alphaToCoverage = !0), this.premultipliedAlpha === !0 && (n.premultipliedAlpha = !0), this.forceSinglePass === !0 && (n.forceSinglePass = !0), this.wireframe === !0 && (n.wireframe = !0), this.wireframeLinewidth > 1 && (n.wireframeLinewidth = this.wireframeLinewidth), this.wireframeLinecap !== "round" && (n.wireframeLinecap = this.wireframeLinecap), this.wireframeLinejoin !== "round" && (n.wireframeLinejoin = this.wireframeLinejoin), this.flatShading === !0 && (n.flatShading = !0), this.visible === !1 && (n.visible = !1), this.toneMapped === !1 && (n.toneMapped = !1), this.fog === !1 && (n.fog = !1), Object.keys(this.userData).length > 0 && (n.userData = this.userData); + function s(r) { + const a = []; + for (const o in r) { + const c = r[o]; + delete c.metadata, a.push(c); + } + return a; + } + if (e) { + const r = s(t.textures), a = s(t.images); + r.length > 0 && (n.textures = r), a.length > 0 && (n.images = a); + } + return n; + } + /** + * 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(t) { + this.name = t.name, this.blending = t.blending, this.side = t.side, this.vertexColors = t.vertexColors, this.opacity = t.opacity, this.transparent = t.transparent, this.blendSrc = t.blendSrc, this.blendDst = t.blendDst, this.blendEquation = t.blendEquation, this.blendSrcAlpha = t.blendSrcAlpha, this.blendDstAlpha = t.blendDstAlpha, this.blendEquationAlpha = t.blendEquationAlpha, this.blendColor.copy(t.blendColor), this.blendAlpha = t.blendAlpha, this.depthFunc = t.depthFunc, this.depthTest = t.depthTest, this.depthWrite = t.depthWrite, this.stencilWriteMask = t.stencilWriteMask, this.stencilFunc = t.stencilFunc, this.stencilRef = t.stencilRef, this.stencilFuncMask = t.stencilFuncMask, this.stencilFail = t.stencilFail, this.stencilZFail = t.stencilZFail, this.stencilZPass = t.stencilZPass, this.stencilWrite = t.stencilWrite; + const e = t.clippingPlanes; + let n = null; + if (e !== null) { + const s = e.length; + n = new Array(s); + for (let r = 0; r !== s; ++r) + n[r] = e[r].clone(); + } + return this.clippingPlanes = n, this.clipIntersection = t.clipIntersection, this.clipShadows = t.clipShadows, this.shadowSide = t.shadowSide, this.colorWrite = t.colorWrite, this.precision = t.precision, this.polygonOffset = t.polygonOffset, this.polygonOffsetFactor = t.polygonOffsetFactor, this.polygonOffsetUnits = t.polygonOffsetUnits, this.dithering = t.dithering, this.alphaTest = t.alphaTest, this.alphaHash = t.alphaHash, this.alphaToCoverage = t.alphaToCoverage, this.premultipliedAlpha = t.premultipliedAlpha, this.forceSinglePass = t.forceSinglePass, this.visible = t.visible, this.toneMapped = t.toneMapped, this.userData = JSON.parse(JSON.stringify(t.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(t) { + t === !0 && this.version++; + } +} +class Zr extends bi { + /** + * 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(t) { + super(), this.isMeshBasicMaterial = !0, this.type = "MeshBasicMaterial", this.color = new Vt(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 je(), this.combine = zr, this.reflectivity = 1, this.refractionRatio = 0.98, this.wireframe = !1, this.wireframeLinewidth = 1, this.wireframeLinecap = "round", this.wireframeLinejoin = "round", this.fog = !0, this.setValues(t); + } + copy(t) { + return super.copy(t), this.color.copy(t.color), this.map = t.map, this.lightMap = t.lightMap, this.lightMapIntensity = t.lightMapIntensity, this.aoMap = t.aoMap, this.aoMapIntensity = t.aoMapIntensity, this.specularMap = t.specularMap, this.alphaMap = t.alphaMap, this.envMap = t.envMap, this.envMapRotation.copy(t.envMapRotation), this.combine = t.combine, this.reflectivity = t.reflectivity, this.refractionRatio = t.refractionRatio, this.wireframe = t.wireframe, this.wireframeLinewidth = t.wireframeLinewidth, this.wireframeLinecap = t.wireframeLinecap, this.wireframeLinejoin = t.wireframeLinejoin, this.fog = t.fog, this; + } +} +const le = /* @__PURE__ */ new N(), Bi = /* @__PURE__ */ new Ct(); +let oc = 0; +class Fe { + /** + * 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(t, e, n = !1) { + if (Array.isArray(t)) + throw new TypeError("THREE.BufferAttribute: array should be a Typed Array."); + this.isBufferAttribute = !0, Object.defineProperty(this, "id", { value: oc++ }), this.name = "", this.array = t, this.itemSize = e, this.count = t !== void 0 ? t.length / e : 0, this.normalized = n, this.usage = da, this.updateRanges = [], this.gpuType = sn, 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(t) { + t === !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(t) { + return this.usage = t, 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(t, e) { + this.updateRanges.push({ start: t, count: e }); + } + /** + * 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(t) { + return this.name = t.name, this.array = new t.array.constructor(t.array), this.itemSize = t.itemSize, this.count = t.count, this.normalized = t.normalized, this.usage = t.usage, this.gpuType = t.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(t, e, n) { + t *= this.itemSize, n *= e.itemSize; + for (let s = 0, r = this.itemSize; s < r; s++) + this.array[t + s] = e.array[n + s]; + 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(t) { + return this.array.set(t), 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(t) { + if (this.itemSize === 2) + for (let e = 0, n = this.count; e < n; e++) + Bi.fromBufferAttribute(this, e), Bi.applyMatrix3(t), this.setXY(e, Bi.x, Bi.y); + else if (this.itemSize === 3) + for (let e = 0, n = this.count; e < n; e++) + le.fromBufferAttribute(this, e), le.applyMatrix3(t), this.setXYZ(e, le.x, le.y, le.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(t) { + for (let e = 0, n = this.count; e < n; e++) + le.fromBufferAttribute(this, e), le.applyMatrix4(t), this.setXYZ(e, le.x, le.y, le.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(t) { + for (let e = 0, n = this.count; e < n; e++) + le.fromBufferAttribute(this, e), le.applyNormalMatrix(t), this.setXYZ(e, le.x, le.y, le.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(t) { + for (let e = 0, n = this.count; e < n; e++) + le.fromBufferAttribute(this, e), le.transformDirection(t), this.setXYZ(e, le.x, le.y, le.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(t, e = 0) { + return this.array.set(t, e), 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(t, e) { + let n = this.array[t * this.itemSize + e]; + return this.normalized && (n = ui(n, this.array)), n; + } + /** + * 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(t, e, n) { + return this.normalized && (n = Ee(n, this.array)), this.array[t * this.itemSize + e] = n, 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(t) { + let e = this.array[t * this.itemSize]; + return this.normalized && (e = ui(e, this.array)), e; + } + /** + * 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(t, e) { + return this.normalized && (e = Ee(e, this.array)), this.array[t * this.itemSize] = e, 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(t) { + let e = this.array[t * this.itemSize + 1]; + return this.normalized && (e = ui(e, this.array)), e; + } + /** + * 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(t, e) { + return this.normalized && (e = Ee(e, this.array)), this.array[t * this.itemSize + 1] = e, 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(t) { + let e = this.array[t * this.itemSize + 2]; + return this.normalized && (e = ui(e, this.array)), e; + } + /** + * 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(t, e) { + return this.normalized && (e = Ee(e, this.array)), this.array[t * this.itemSize + 2] = e, 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(t) { + let e = this.array[t * this.itemSize + 3]; + return this.normalized && (e = ui(e, this.array)), e; + } + /** + * 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(t, e) { + return this.normalized && (e = Ee(e, this.array)), this.array[t * this.itemSize + 3] = e, 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(t, e, n) { + return t *= this.itemSize, this.normalized && (e = Ee(e, this.array), n = Ee(n, this.array)), this.array[t + 0] = e, this.array[t + 1] = n, 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(t, e, n, s) { + return t *= this.itemSize, this.normalized && (e = Ee(e, this.array), n = Ee(n, this.array), s = Ee(s, this.array)), this.array[t + 0] = e, this.array[t + 1] = n, this.array[t + 2] = s, 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(t, e, n, s, r) { + return t *= this.itemSize, this.normalized && (e = Ee(e, this.array), n = Ee(n, this.array), s = Ee(s, this.array), r = Ee(r, this.array)), this.array[t + 0] = e, this.array[t + 1] = n, this.array[t + 2] = s, this.array[t + 3] = r, 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(t) { + return this.onUploadCallback = t, 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 t = { + itemSize: this.itemSize, + type: this.array.constructor.name, + array: Array.from(this.array), + normalized: this.normalized + }; + return this.name !== "" && (t.name = this.name), this.usage !== da && (t.usage = this.usage), t; + } +} +class wo extends Fe { + /** + * Constructs a new buffer attribute. + * + * @param {(Array|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(t, e, n) { + super(new Uint16Array(t), e, n); + } +} +class Co extends Fe { + /** + * Constructs a new buffer attribute. + * + * @param {(Array|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(t, e, n) { + super(new Uint32Array(t), e, n); + } +} +class qe extends Fe { + /** + * Constructs a new buffer attribute. + * + * @param {(Array|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(t, e, n) { + super(new Float32Array(t), e, n); + } +} +let lc = 0; +const Ie = /* @__PURE__ */ new ae(), Us = /* @__PURE__ */ new ge(), Kn = /* @__PURE__ */ new N(), Pe = /* @__PURE__ */ new Ti(), mi = /* @__PURE__ */ new Ti(), fe = /* @__PURE__ */ new N(); +class an extends Fn { + /** + * Constructs a new geometry. + */ + constructor() { + super(), this.isBufferGeometry = !0, Object.defineProperty(this, "id", { value: lc++ }), this.uuid = yi(), 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|BufferAttribute} index - The index to set. + * @return {BufferGeometry} A reference to this instance. + */ + setIndex(t) { + return Array.isArray(t) ? this.index = new (bo(t) ? Co : wo)(t, 1) : this.index = t, 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(t) { + return this.indirect = t, 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(t) { + return this.attributes[t]; + } + /** + * 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(t, e) { + return this.attributes[t] = e, this; + } + /** + * Deletes the attribute for the given name. + * + * @param {string} name - The attribute name to delete. + * @return {BufferGeometry} A reference to this instance. + */ + deleteAttribute(t) { + return delete this.attributes[t], 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(t) { + return this.attributes[t] !== 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(t, e, n = 0) { + this.groups.push({ + start: t, + count: e, + materialIndex: n + }); + } + /** + * 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(t, e) { + this.drawRange.start = t, this.drawRange.count = e; + } + /** + * Applies the given 4x4 transformation matrix to the geometry. + * + * @param {Matrix4} matrix - The matrix to apply. + * @return {BufferGeometry} A reference to this instance. + */ + applyMatrix4(t) { + const e = this.attributes.position; + e !== void 0 && (e.applyMatrix4(t), e.needsUpdate = !0); + const n = this.attributes.normal; + if (n !== void 0) { + const r = new It().getNormalMatrix(t); + n.applyNormalMatrix(r), n.needsUpdate = !0; + } + const s = this.attributes.tangent; + return s !== void 0 && (s.transformDirection(t), s.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(t) { + return Ie.makeRotationFromQuaternion(t), this.applyMatrix4(Ie), 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(t) { + return Ie.makeRotationX(t), this.applyMatrix4(Ie), 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(t) { + return Ie.makeRotationY(t), this.applyMatrix4(Ie), 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(t) { + return Ie.makeRotationZ(t), this.applyMatrix4(Ie), 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(t, e, n) { + return Ie.makeTranslation(t, e, n), this.applyMatrix4(Ie), 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(t, e, n) { + return Ie.makeScale(t, e, n), this.applyMatrix4(Ie), 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(t) { + return Us.lookAt(t), Us.updateMatrix(), this.applyMatrix4(Us.matrix), this; + } + /** + * Center the geometry based on its bounding box. + * + * @return {BufferGeometry} A reference to this instance. + */ + center() { + return this.computeBoundingBox(), this.boundingBox.getCenter(Kn).negate(), this.translate(Kn.x, Kn.y, Kn.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|Array} points - The points. + * @return {BufferGeometry} A reference to this instance. + */ + setFromPoints(t) { + const e = this.getAttribute("position"); + if (e === void 0) { + const n = []; + for (let s = 0, r = t.length; s < r; s++) { + const a = t[s]; + n.push(a.x, a.y, a.z || 0); + } + this.setAttribute("position", new qe(n, 3)); + } else { + const n = Math.min(t.length, e.count); + for (let s = 0; s < n; s++) { + const r = t[s]; + e.setXYZ(s, r.x, r.y, r.z || 0); + } + t.length > e.count && console.warn("THREE.BufferGeometry: Buffer size too small for points data. Use .dispose() and create a new geometry."), e.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 Ti()); + const t = this.attributes.position, e = this.morphAttributes.position; + if (t && t.isGLBufferAttribute) { + console.error("THREE.BufferGeometry.computeBoundingBox(): GLBufferAttribute requires a manual bounding box.", this), this.boundingBox.set( + new N(-1 / 0, -1 / 0, -1 / 0), + new N(1 / 0, 1 / 0, 1 / 0) + ); + return; + } + if (t !== void 0) { + if (this.boundingBox.setFromBufferAttribute(t), e) + for (let n = 0, s = e.length; n < s; n++) { + const r = e[n]; + Pe.setFromBufferAttribute(r), this.morphTargetsRelative ? (fe.addVectors(this.boundingBox.min, Pe.min), this.boundingBox.expandByPoint(fe), fe.addVectors(this.boundingBox.max, Pe.max), this.boundingBox.expandByPoint(fe)) : (this.boundingBox.expandByPoint(Pe.min), this.boundingBox.expandByPoint(Pe.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 qr()); + const t = this.attributes.position, e = this.morphAttributes.position; + if (t && t.isGLBufferAttribute) { + console.error("THREE.BufferGeometry.computeBoundingSphere(): GLBufferAttribute requires a manual bounding sphere.", this), this.boundingSphere.set(new N(), 1 / 0); + return; + } + if (t) { + const n = this.boundingSphere.center; + if (Pe.setFromBufferAttribute(t), e) + for (let r = 0, a = e.length; r < a; r++) { + const o = e[r]; + mi.setFromBufferAttribute(o), this.morphTargetsRelative ? (fe.addVectors(Pe.min, mi.min), Pe.expandByPoint(fe), fe.addVectors(Pe.max, mi.max), Pe.expandByPoint(fe)) : (Pe.expandByPoint(mi.min), Pe.expandByPoint(mi.max)); + } + Pe.getCenter(n); + let s = 0; + for (let r = 0, a = t.count; r < a; r++) + fe.fromBufferAttribute(t, r), s = Math.max(s, n.distanceToSquared(fe)); + if (e) + for (let r = 0, a = e.length; r < a; r++) { + const o = e[r], c = this.morphTargetsRelative; + for (let l = 0, u = o.count; l < u; l++) + fe.fromBufferAttribute(o, l), c && (Kn.fromBufferAttribute(t, l), fe.add(Kn)), s = Math.max(s, n.distanceToSquared(fe)); + } + this.boundingSphere.radius = Math.sqrt(s), 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 t = this.index, e = this.attributes; + if (t === null || e.position === void 0 || e.normal === void 0 || e.uv === void 0) { + console.error("THREE.BufferGeometry: .computeTangents() failed. Missing required attributes (index, position, normal or uv)"); + return; + } + const n = e.position, s = e.normal, r = e.uv; + this.hasAttribute("tangent") === !1 && this.setAttribute("tangent", new Fe(new Float32Array(4 * n.count), 4)); + const a = this.getAttribute("tangent"), o = [], c = []; + for (let F = 0; F < n.count; F++) + o[F] = new N(), c[F] = new N(); + const l = new N(), u = new N(), d = new N(), f = new Ct(), m = new Ct(), v = new Ct(), x = new N(), p = new N(); + function h(F, S, M) { + l.fromBufferAttribute(n, F), u.fromBufferAttribute(n, S), d.fromBufferAttribute(n, M), f.fromBufferAttribute(r, F), m.fromBufferAttribute(r, S), v.fromBufferAttribute(r, M), u.sub(l), d.sub(l), m.sub(f), v.sub(f); + const C = 1 / (m.x * v.y - v.x * m.y); + isFinite(C) && (x.copy(u).multiplyScalar(v.y).addScaledVector(d, -m.y).multiplyScalar(C), p.copy(d).multiplyScalar(m.x).addScaledVector(u, -v.x).multiplyScalar(C), o[F].add(x), o[S].add(x), o[M].add(x), c[F].add(p), c[S].add(p), c[M].add(p)); + } + let A = this.groups; + A.length === 0 && (A = [{ + start: 0, + count: t.count + }]); + for (let F = 0, S = A.length; F < S; ++F) { + const M = A[F], C = M.start, z = M.count; + for (let G = C, K = C + z; G < K; G += 3) + h( + t.getX(G + 0), + t.getX(G + 1), + t.getX(G + 2) + ); + } + const b = new N(), y = new N(), D = new N(), P = new N(); + function w(F) { + D.fromBufferAttribute(s, F), P.copy(D); + const S = o[F]; + b.copy(S), b.sub(D.multiplyScalar(D.dot(S))).normalize(), y.crossVectors(P, S); + const C = y.dot(c[F]) < 0 ? -1 : 1; + a.setXYZW(F, b.x, b.y, b.z, C); + } + for (let F = 0, S = A.length; F < S; ++F) { + const M = A[F], C = M.start, z = M.count; + for (let G = C, K = C + z; G < K; G += 3) + w(t.getX(G + 0)), w(t.getX(G + 1)), w(t.getX(G + 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 t = this.index, e = this.getAttribute("position"); + if (e !== void 0) { + let n = this.getAttribute("normal"); + if (n === void 0) + n = new Fe(new Float32Array(e.count * 3), 3), this.setAttribute("normal", n); + else + for (let f = 0, m = n.count; f < m; f++) + n.setXYZ(f, 0, 0, 0); + const s = new N(), r = new N(), a = new N(), o = new N(), c = new N(), l = new N(), u = new N(), d = new N(); + if (t) + for (let f = 0, m = t.count; f < m; f += 3) { + const v = t.getX(f + 0), x = t.getX(f + 1), p = t.getX(f + 2); + s.fromBufferAttribute(e, v), r.fromBufferAttribute(e, x), a.fromBufferAttribute(e, p), u.subVectors(a, r), d.subVectors(s, r), u.cross(d), o.fromBufferAttribute(n, v), c.fromBufferAttribute(n, x), l.fromBufferAttribute(n, p), o.add(u), c.add(u), l.add(u), n.setXYZ(v, o.x, o.y, o.z), n.setXYZ(x, c.x, c.y, c.z), n.setXYZ(p, l.x, l.y, l.z); + } + else + for (let f = 0, m = e.count; f < m; f += 3) + s.fromBufferAttribute(e, f + 0), r.fromBufferAttribute(e, f + 1), a.fromBufferAttribute(e, f + 2), u.subVectors(a, r), d.subVectors(s, r), u.cross(d), n.setXYZ(f + 0, u.x, u.y, u.z), n.setXYZ(f + 1, u.x, u.y, u.z), n.setXYZ(f + 2, u.x, u.y, u.z); + this.normalizeNormals(), n.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 t = this.attributes.normal; + for (let e = 0, n = t.count; e < n; e++) + fe.fromBufferAttribute(t, e), fe.normalize(), t.setXYZ(e, fe.x, fe.y, fe.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 t(o, c) { + const l = o.array, u = o.itemSize, d = o.normalized, f = new l.constructor(c.length * u); + let m = 0, v = 0; + for (let x = 0, p = c.length; x < p; x++) { + o.isInterleavedBufferAttribute ? m = c[x] * o.data.stride + o.offset : m = c[x] * u; + for (let h = 0; h < u; h++) + f[v++] = l[m++]; + } + return new Fe(f, u, d); + } + if (this.index === null) + return console.warn("THREE.BufferGeometry.toNonIndexed(): BufferGeometry is already non-indexed."), this; + const e = new an(), n = this.index.array, s = this.attributes; + for (const o in s) { + const c = s[o], l = t(c, n); + e.setAttribute(o, l); + } + const r = this.morphAttributes; + for (const o in r) { + const c = [], l = r[o]; + for (let u = 0, d = l.length; u < d; u++) { + const f = l[u], m = t(f, n); + c.push(m); + } + e.morphAttributes[o] = c; + } + e.morphTargetsRelative = this.morphTargetsRelative; + const a = this.groups; + for (let o = 0, c = a.length; o < c; o++) { + const l = a[o]; + e.addGroup(l.start, l.count, l.materialIndex); + } + return e; + } + /** + * Serializes the geometry into JSON. + * + * @return {Object} A JSON object representing the serialized geometry. + */ + toJSON() { + const t = { + metadata: { + version: 4.7, + type: "BufferGeometry", + generator: "BufferGeometry.toJSON" + } + }; + if (t.uuid = this.uuid, t.type = this.type, this.name !== "" && (t.name = this.name), Object.keys(this.userData).length > 0 && (t.userData = this.userData), this.parameters !== void 0) { + const c = this.parameters; + for (const l in c) + c[l] !== void 0 && (t[l] = c[l]); + return t; + } + t.data = { attributes: {} }; + const e = this.index; + e !== null && (t.data.index = { + type: e.array.constructor.name, + array: Array.prototype.slice.call(e.array) + }); + const n = this.attributes; + for (const c in n) { + const l = n[c]; + t.data.attributes[c] = l.toJSON(t.data); + } + const s = {}; + let r = !1; + for (const c in this.morphAttributes) { + const l = this.morphAttributes[c], u = []; + for (let d = 0, f = l.length; d < f; d++) { + const m = l[d]; + u.push(m.toJSON(t.data)); + } + u.length > 0 && (s[c] = u, r = !0); + } + r && (t.data.morphAttributes = s, t.data.morphTargetsRelative = this.morphTargetsRelative); + const a = this.groups; + a.length > 0 && (t.data.groups = JSON.parse(JSON.stringify(a))); + const o = this.boundingSphere; + return o !== null && (t.data.boundingSphere = o.toJSON()), t; + } + /** + * 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(t) { + this.index = null, this.attributes = {}, this.morphAttributes = {}, this.groups = [], this.boundingBox = null, this.boundingSphere = null; + const e = {}; + this.name = t.name; + const n = t.index; + n !== null && this.setIndex(n.clone()); + const s = t.attributes; + for (const l in s) { + const u = s[l]; + this.setAttribute(l, u.clone(e)); + } + const r = t.morphAttributes; + for (const l in r) { + const u = [], d = r[l]; + for (let f = 0, m = d.length; f < m; f++) + u.push(d[f].clone(e)); + this.morphAttributes[l] = u; + } + this.morphTargetsRelative = t.morphTargetsRelative; + const a = t.groups; + for (let l = 0, u = a.length; l < u; l++) { + const d = a[l]; + this.addGroup(d.start, d.count, d.materialIndex); + } + const o = t.boundingBox; + o !== null && (this.boundingBox = o.clone()); + const c = t.boundingSphere; + return c !== null && (this.boundingSphere = c.clone()), this.drawRange.start = t.drawRange.start, this.drawRange.count = t.drawRange.count, this.userData = t.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 Aa = /* @__PURE__ */ new ae(), Tn = /* @__PURE__ */ new Kr(), zi = /* @__PURE__ */ new qr(), Ra = /* @__PURE__ */ new N(), Hi = /* @__PURE__ */ new N(), Vi = /* @__PURE__ */ new N(), Gi = /* @__PURE__ */ new N(), Is = /* @__PURE__ */ new N(), ki = /* @__PURE__ */ new N(), wa = /* @__PURE__ */ new N(), Wi = /* @__PURE__ */ new N(); +class be extends ge { + /** + * Constructs a new mesh. + * + * @param {BufferGeometry} [geometry] - The mesh geometry. + * @param {Material|Array} [material] - The mesh material. + */ + constructor(t = new an(), e = new Zr()) { + super(), this.isMesh = !0, this.type = "Mesh", this.geometry = t, this.material = e, this.morphTargetDictionary = void 0, this.morphTargetInfluences = void 0, this.count = 1, this.updateMorphTargets(); + } + copy(t, e) { + return super.copy(t, e), t.morphTargetInfluences !== void 0 && (this.morphTargetInfluences = t.morphTargetInfluences.slice()), t.morphTargetDictionary !== void 0 && (this.morphTargetDictionary = Object.assign({}, t.morphTargetDictionary)), this.material = Array.isArray(t.material) ? t.material.slice() : t.material, this.geometry = t.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 e = this.geometry.morphAttributes, n = Object.keys(e); + if (n.length > 0) { + const s = e[n[0]]; + if (s !== void 0) { + this.morphTargetInfluences = [], this.morphTargetDictionary = {}; + for (let r = 0, a = s.length; r < a; r++) { + const o = s[r].name || String(r); + this.morphTargetInfluences.push(0), this.morphTargetDictionary[o] = r; + } + } + } + } + /** + * 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(t, e) { + const n = this.geometry, s = n.attributes.position, r = n.morphAttributes.position, a = n.morphTargetsRelative; + e.fromBufferAttribute(s, t); + const o = this.morphTargetInfluences; + if (r && o) { + ki.set(0, 0, 0); + for (let c = 0, l = r.length; c < l; c++) { + const u = o[c], d = r[c]; + u !== 0 && (Is.fromBufferAttribute(d, t), a ? ki.addScaledVector(Is, u) : ki.addScaledVector(Is.sub(e), u)); + } + e.add(ki); + } + return e; + } + /** + * Computes intersection points between a casted ray and this line. + * + * @param {Raycaster} raycaster - The raycaster. + * @param {Array} intersects - The target array that holds the intersection points. + */ + raycast(t, e) { + const n = this.geometry, s = this.material, r = this.matrixWorld; + s !== void 0 && (n.boundingSphere === null && n.computeBoundingSphere(), zi.copy(n.boundingSphere), zi.applyMatrix4(r), Tn.copy(t.ray).recast(t.near), !(zi.containsPoint(Tn.origin) === !1 && (Tn.intersectSphere(zi, Ra) === null || Tn.origin.distanceToSquared(Ra) > (t.far - t.near) ** 2)) && (Aa.copy(r).invert(), Tn.copy(t.ray).applyMatrix4(Aa), !(n.boundingBox !== null && Tn.intersectsBox(n.boundingBox) === !1) && this._computeIntersections(t, e, Tn))); + } + _computeIntersections(t, e, n) { + let s; + const r = this.geometry, a = this.material, o = r.index, c = r.attributes.position, l = r.attributes.uv, u = r.attributes.uv1, d = r.attributes.normal, f = r.groups, m = r.drawRange; + if (o !== null) + if (Array.isArray(a)) + for (let v = 0, x = f.length; v < x; v++) { + const p = f[v], h = a[p.materialIndex], A = Math.max(p.start, m.start), b = Math.min(o.count, Math.min(p.start + p.count, m.start + m.count)); + for (let y = A, D = b; y < D; y += 3) { + const P = o.getX(y), w = o.getX(y + 1), F = o.getX(y + 2); + s = Xi(this, h, t, n, l, u, d, P, w, F), s && (s.faceIndex = Math.floor(y / 3), s.face.materialIndex = p.materialIndex, e.push(s)); + } + } + else { + const v = Math.max(0, m.start), x = Math.min(o.count, m.start + m.count); + for (let p = v, h = x; p < h; p += 3) { + const A = o.getX(p), b = o.getX(p + 1), y = o.getX(p + 2); + s = Xi(this, a, t, n, l, u, d, A, b, y), s && (s.faceIndex = Math.floor(p / 3), e.push(s)); + } + } + else if (c !== void 0) + if (Array.isArray(a)) + for (let v = 0, x = f.length; v < x; v++) { + const p = f[v], h = a[p.materialIndex], A = Math.max(p.start, m.start), b = Math.min(c.count, Math.min(p.start + p.count, m.start + m.count)); + for (let y = A, D = b; y < D; y += 3) { + const P = y, w = y + 1, F = y + 2; + s = Xi(this, h, t, n, l, u, d, P, w, F), s && (s.faceIndex = Math.floor(y / 3), s.face.materialIndex = p.materialIndex, e.push(s)); + } + } + else { + const v = Math.max(0, m.start), x = Math.min(c.count, m.start + m.count); + for (let p = v, h = x; p < h; p += 3) { + const A = p, b = p + 1, y = p + 2; + s = Xi(this, a, t, n, l, u, d, A, b, y), s && (s.faceIndex = Math.floor(p / 3), e.push(s)); + } + } + } +} +function cc(i, t, e, n, s, r, a, o) { + let c; + if (t.side === Ae ? c = n.intersectTriangle(a, r, s, !0, o) : c = n.intersectTriangle(s, r, a, t.side === vn, o), c === null) return null; + Wi.copy(o), Wi.applyMatrix4(i.matrixWorld); + const l = e.ray.origin.distanceTo(Wi); + return l < e.near || l > e.far ? null : { + distance: l, + point: Wi.clone(), + object: i + }; +} +function Xi(i, t, e, n, s, r, a, o, c, l) { + i.getVertexPosition(o, Hi), i.getVertexPosition(c, Vi), i.getVertexPosition(l, Gi); + const u = cc(i, t, e, n, Hi, Vi, Gi, wa); + if (u) { + const d = new N(); + He.getBarycoord(wa, Hi, Vi, Gi, d), s && (u.uv = He.getInterpolatedAttribute(s, o, c, l, d, new Ct())), r && (u.uv1 = He.getInterpolatedAttribute(r, o, c, l, d, new Ct())), a && (u.normal = He.getInterpolatedAttribute(a, o, c, l, d, new N()), u.normal.dot(n.direction) > 0 && u.normal.multiplyScalar(-1)); + const f = { + a: o, + b: c, + c: l, + normal: new N(), + materialIndex: 0 + }; + He.getNormal(Hi, Vi, Gi, f.normal), u.face = f, u.barycoord = d; + } + return u; +} +class Ai extends an { + /** + * 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(t = 1, e = 1, n = 1, s = 1, r = 1, a = 1) { + super(), this.type = "BoxGeometry", this.parameters = { + width: t, + height: e, + depth: n, + widthSegments: s, + heightSegments: r, + depthSegments: a + }; + const o = this; + s = Math.floor(s), r = Math.floor(r), a = Math.floor(a); + const c = [], l = [], u = [], d = []; + let f = 0, m = 0; + v("z", "y", "x", -1, -1, n, e, t, a, r, 0), v("z", "y", "x", 1, -1, n, e, -t, a, r, 1), v("x", "z", "y", 1, 1, t, n, e, s, a, 2), v("x", "z", "y", 1, -1, t, n, -e, s, a, 3), v("x", "y", "z", 1, -1, t, e, n, s, r, 4), v("x", "y", "z", -1, -1, t, e, -n, s, r, 5), this.setIndex(c), this.setAttribute("position", new qe(l, 3)), this.setAttribute("normal", new qe(u, 3)), this.setAttribute("uv", new qe(d, 2)); + function v(x, p, h, A, b, y, D, P, w, F, S) { + const M = y / w, C = D / F, z = y / 2, G = D / 2, K = P / 2, W = w + 1, Y = F + 1; + let Z = 0, H = 0; + const rt = new N(); + for (let ct = 0; ct < Y; ct++) { + const Et = ct * C - G; + for (let Ot = 0; Ot < W; Ot++) { + const Zt = Ot * M - z; + rt[x] = Zt * A, rt[p] = Et * b, rt[h] = K, l.push(rt.x, rt.y, rt.z), rt[x] = 0, rt[p] = 0, rt[h] = P > 0 ? 1 : -1, u.push(rt.x, rt.y, rt.z), d.push(Ot / w), d.push(1 - ct / F), Z += 1; + } + } + for (let ct = 0; ct < F; ct++) + for (let Et = 0; Et < w; Et++) { + const Ot = f + Et + W * ct, Zt = f + Et + W * (ct + 1), Qt = f + (Et + 1) + W * (ct + 1), Wt = f + (Et + 1) + W * ct; + c.push(Ot, Zt, Wt), c.push(Zt, Qt, Wt), H += 6; + } + o.addGroup(m, H, S), m += H, f += Z; + } + } + copy(t) { + return super.copy(t), this.parameters = Object.assign({}, t.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(t) { + return new Ai(t.width, t.height, t.depth, t.widthSegments, t.heightSegments, t.depthSegments); + } +} +function li(i) { + const t = {}; + for (const e in i) { + t[e] = {}; + for (const n in i[e]) { + const s = i[e][n]; + s && (s.isColor || s.isMatrix3 || s.isMatrix4 || s.isVector2 || s.isVector3 || s.isVector4 || s.isTexture || s.isQuaternion) ? s.isRenderTargetTexture ? (console.warn("UniformsUtils: Textures of render targets cannot be cloned via cloneUniforms() or mergeUniforms()."), t[e][n] = null) : t[e][n] = s.clone() : Array.isArray(s) ? t[e][n] = s.slice() : t[e][n] = s; + } + } + return t; +} +function xe(i) { + const t = {}; + for (let e = 0; e < i.length; e++) { + const n = li(i[e]); + for (const s in n) + t[s] = n[s]; + } + return t; +} +function hc(i) { + const t = []; + for (let e = 0; e < i.length; e++) + t.push(i[e].clone()); + return t; +} +function Po(i) { + const t = i.getRenderTarget(); + return t === null ? i.outputColorSpace : t.isXRRenderTarget === !0 ? t.texture.colorSpace : kt.workingColorSpace; +} +const uc = { clone: li, merge: xe }; +var dc = `void main() { + gl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 ); +}`, fc = `void main() { + gl_FragColor = vec4( 1.0, 0.0, 0.0, 1.0 ); +}`; +class xn extends bi { + /** + * 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(t) { + super(), this.isShaderMaterial = !0, this.type = "ShaderMaterial", this.defines = {}, this.uniforms = {}, this.uniformsGroups = [], this.vertexShader = dc, this.fragmentShader = fc, 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, t !== void 0 && this.setValues(t); + } + copy(t) { + return super.copy(t), this.fragmentShader = t.fragmentShader, this.vertexShader = t.vertexShader, this.uniforms = li(t.uniforms), this.uniformsGroups = hc(t.uniformsGroups), this.defines = Object.assign({}, t.defines), this.wireframe = t.wireframe, this.wireframeLinewidth = t.wireframeLinewidth, this.fog = t.fog, this.lights = t.lights, this.clipping = t.clipping, this.extensions = Object.assign({}, t.extensions), this.glslVersion = t.glslVersion, this; + } + toJSON(t) { + const e = super.toJSON(t); + e.glslVersion = this.glslVersion, e.uniforms = {}; + for (const s in this.uniforms) { + const a = this.uniforms[s].value; + a && a.isTexture ? e.uniforms[s] = { + type: "t", + value: a.toJSON(t).uuid + } : a && a.isColor ? e.uniforms[s] = { + type: "c", + value: a.getHex() + } : a && a.isVector2 ? e.uniforms[s] = { + type: "v2", + value: a.toArray() + } : a && a.isVector3 ? e.uniforms[s] = { + type: "v3", + value: a.toArray() + } : a && a.isVector4 ? e.uniforms[s] = { + type: "v4", + value: a.toArray() + } : a && a.isMatrix3 ? e.uniforms[s] = { + type: "m3", + value: a.toArray() + } : a && a.isMatrix4 ? e.uniforms[s] = { + type: "m4", + value: a.toArray() + } : e.uniforms[s] = { + value: a + }; + } + Object.keys(this.defines).length > 0 && (e.defines = this.defines), e.vertexShader = this.vertexShader, e.fragmentShader = this.fragmentShader, e.lights = this.lights, e.clipping = this.clipping; + const n = {}; + for (const s in this.extensions) + this.extensions[s] === !0 && (n[s] = !0); + return Object.keys(n).length > 0 && (e.extensions = n), e; + } +} +class Do extends ge { + /** + * Constructs a new camera. + */ + constructor() { + super(), this.isCamera = !0, this.type = "Camera", this.matrixWorldInverse = new ae(), this.projectionMatrix = new ae(), this.projectionMatrixInverse = new ae(), this.coordinateSystem = Ye, 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(t, e) { + return super.copy(t, e), this.matrixWorldInverse.copy(t.matrixWorldInverse), this.projectionMatrix.copy(t.projectionMatrix), this.projectionMatrixInverse.copy(t.projectionMatrixInverse), this.coordinateSystem = t.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(t) { + return super.getWorldDirection(t).negate(); + } + updateMatrixWorld(t) { + super.updateMatrixWorld(t), this.matrixWorldInverse.copy(this.matrixWorld).invert(); + } + updateWorldMatrix(t, e) { + super.updateWorldMatrix(t, e), this.matrixWorldInverse.copy(this.matrixWorld).invert(); + } + clone() { + return new this.constructor().copy(this); + } +} +const dn = /* @__PURE__ */ new N(), Ca = /* @__PURE__ */ new Ct(), Pa = /* @__PURE__ */ new Ct(); +class Ne extends Do { + /** + * 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(t = 50, e = 1, n = 0.1, s = 2e3) { + super(), this.isPerspectiveCamera = !0, this.type = "PerspectiveCamera", this.fov = t, this.zoom = 1, this.near = n, this.far = s, this.focus = 10, this.aspect = e, this.view = null, this.filmGauge = 35, this.filmOffset = 0, this.updateProjectionMatrix(); + } + copy(t, e) { + return super.copy(t, e), this.fov = t.fov, this.zoom = t.zoom, this.near = t.near, this.far = t.far, this.focus = t.focus, this.aspect = t.aspect, this.view = t.view === null ? null : Object.assign({}, t.view), this.filmGauge = t.filmGauge, this.filmOffset = t.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(t) { + const e = 0.5 * this.getFilmHeight() / t; + this.fov = Nr * 2 * Math.atan(e), this.updateProjectionMatrix(); + } + /** + * Returns the focal length from the current {@link PerspectiveCamera#fov} and + * {@link PerspectiveCamera#filmGauge}. + * + * @return {number} The computed focal length. + */ + getFocalLength() { + const t = Math.tan(is * 0.5 * this.fov); + return 0.5 * this.getFilmHeight() / t; + } + /** + * Returns the current vertical field of view angle in degrees considering {@link PerspectiveCamera#zoom}. + * + * @return {number} The effective FOV. + */ + getEffectiveFOV() { + return Nr * 2 * Math.atan( + Math.tan(is * 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(t, e, n) { + dn.set(-1, -1, 0.5).applyMatrix4(this.projectionMatrixInverse), e.set(dn.x, dn.y).multiplyScalar(-t / dn.z), dn.set(1, 1, 0.5).applyMatrix4(this.projectionMatrixInverse), n.set(dn.x, dn.y).multiplyScalar(-t / dn.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(t, e) { + return this.getViewBounds(t, Ca, Pa), e.subVectors(Pa, Ca); + } + /** + * 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(t, e, n, s, r, a) { + this.aspect = t / e, 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 = t, this.view.fullHeight = e, this.view.offsetX = n, this.view.offsetY = s, this.view.width = r, 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 t = this.near; + let e = t * Math.tan(is * 0.5 * this.fov) / this.zoom, n = 2 * e, s = this.aspect * n, r = -0.5 * s; + const a = this.view; + if (this.view !== null && this.view.enabled) { + const c = a.fullWidth, l = a.fullHeight; + r += a.offsetX * s / c, e -= a.offsetY * n / l, s *= a.width / c, n *= a.height / l; + } + const o = this.filmOffset; + o !== 0 && (r += t * o / this.getFilmWidth()), this.projectionMatrix.makePerspective(r, r + s, e, e - n, t, this.far, this.coordinateSystem, this.reversedDepth), this.projectionMatrixInverse.copy(this.projectionMatrix).invert(); + } + toJSON(t) { + const e = super.toJSON(t); + return e.object.fov = this.fov, e.object.zoom = this.zoom, e.object.near = this.near, e.object.far = this.far, e.object.focus = this.focus, e.object.aspect = this.aspect, this.view !== null && (e.object.view = Object.assign({}, this.view)), e.object.filmGauge = this.filmGauge, e.object.filmOffset = this.filmOffset, e; + } +} +const jn = -90, Zn = 1; +class pc extends ge { + /** + * 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(t, e, n) { + super(), this.type = "CubeCamera", this.renderTarget = n, this.coordinateSystem = null, this.activeMipmapLevel = 0; + const s = new Ne(jn, Zn, t, e); + s.layers = this.layers, this.add(s); + const r = new Ne(jn, Zn, t, e); + r.layers = this.layers, this.add(r); + const a = new Ne(jn, Zn, t, e); + a.layers = this.layers, this.add(a); + const o = new Ne(jn, Zn, t, e); + o.layers = this.layers, this.add(o); + const c = new Ne(jn, Zn, t, e); + c.layers = this.layers, this.add(c); + const l = new Ne(jn, Zn, t, e); + l.layers = this.layers, this.add(l); + } + /** + * Must be called when the coordinate system of the cube camera is changed. + */ + updateCoordinateSystem() { + const t = this.coordinateSystem, e = this.children.concat(), [n, s, r, a, o, c] = e; + for (const l of e) this.remove(l); + if (t === Ye) + n.up.set(0, 1, 0), n.lookAt(1, 0, 0), s.up.set(0, 1, 0), s.lookAt(-1, 0, 0), r.up.set(0, 0, -1), r.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), c.up.set(0, 1, 0), c.lookAt(0, 0, -1); + else if (t === as) + n.up.set(0, -1, 0), n.lookAt(-1, 0, 0), s.up.set(0, -1, 0), s.lookAt(1, 0, 0), r.up.set(0, 0, 1), r.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), c.up.set(0, -1, 0), c.lookAt(0, 0, -1); + else + throw new Error("THREE.CubeCamera.updateCoordinateSystem(): Invalid coordinate system: " + t); + for (const l of e) + this.add(l), l.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(t, e) { + this.parent === null && this.updateMatrixWorld(); + const { renderTarget: n, activeMipmapLevel: s } = this; + this.coordinateSystem !== t.coordinateSystem && (this.coordinateSystem = t.coordinateSystem, this.updateCoordinateSystem()); + const [r, a, o, c, l, u] = this.children, d = t.getRenderTarget(), f = t.getActiveCubeFace(), m = t.getActiveMipmapLevel(), v = t.xr.enabled; + t.xr.enabled = !1; + const x = n.texture.generateMipmaps; + n.texture.generateMipmaps = !1, t.setRenderTarget(n, 0, s), t.render(e, r), t.setRenderTarget(n, 1, s), t.render(e, a), t.setRenderTarget(n, 2, s), t.render(e, o), t.setRenderTarget(n, 3, s), t.render(e, c), t.setRenderTarget(n, 4, s), t.render(e, l), n.texture.generateMipmaps = x, t.setRenderTarget(n, 5, s), t.render(e, u), t.setRenderTarget(d, f, m), t.xr.enabled = v, n.texture.needsPMREMUpdate = !0; + } +} +class Lo extends Me { + /** + * Constructs a new cube texture. + * + * @param {Array} [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(t = [], e = ri, n, s, r, a, o, c, l, u) { + super(t, e, n, s, r, a, o, c, l, u), this.isCubeTexture = !0, this.flipY = !1; + } + /** + * Alias for {@link CubeTexture#image}. + * + * @type {Array} + */ + get images() { + return this.image; + } + set images(t) { + this.image = t; + } +} +class mc 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(t = 1, e = {}) { + super(t, t, e), this.isWebGLCubeRenderTarget = !0; + const n = { width: t, height: t, depth: 1 }, s = [n, n, n, n, n, n]; + this.texture = new Lo(s), this._setTextureOptions(e), 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(t, e) { + this.texture.type = e.type, this.texture.colorSpace = e.colorSpace, this.texture.generateMipmaps = e.generateMipmaps, this.texture.minFilter = e.minFilter, this.texture.magFilter = e.magFilter; + const n = { + 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 + #include + + } + ` + ), + fragmentShader: ( + /* glsl */ + ` + + uniform sampler2D tEquirect; + + varying vec3 vWorldDirection; + + #include + + void main() { + + vec3 direction = normalize( vWorldDirection ); + + vec2 sampleUV = equirectUv( direction ); + + gl_FragColor = texture2D( tEquirect, sampleUV ); + + } + ` + ) + }, s = new Ai(5, 5, 5), r = new xn({ + name: "CubemapFromEquirect", + uniforms: li(n.uniforms), + vertexShader: n.vertexShader, + fragmentShader: n.fragmentShader, + side: Ae, + blending: _n + }); + r.uniforms.tEquirect.value = e; + const a = new be(s, r), o = e.minFilter; + return e.minFilter === Ln && (e.minFilter = Xe), new pc(1, 10, this).update(t, a), e.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(t, e = !0, n = !0, s = !0) { + const r = t.getRenderTarget(); + for (let a = 0; a < 6; a++) + t.setRenderTarget(this, a), t.clear(e, n, s); + t.setRenderTarget(r); + } +} +class Yi extends ge { + constructor() { + super(), this.isGroup = !0, this.type = "Group"; + } +} +const _c = { type: "move" }; +class Ns { + /** + * 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 Yi(), 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 Yi(), this._targetRay.matrixAutoUpdate = !1, this._targetRay.visible = !1, this._targetRay.hasLinearVelocity = !1, this._targetRay.linearVelocity = new N(), this._targetRay.hasAngularVelocity = !1, this._targetRay.angularVelocity = new N()), 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 Yi(), this._grip.matrixAutoUpdate = !1, this._grip.visible = !1, this._grip.hasLinearVelocity = !1, this._grip.linearVelocity = new N(), this._grip.hasAngularVelocity = !1, this._grip.angularVelocity = new N()), 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(t) { + return this._targetRay !== null && this._targetRay.dispatchEvent(t), this._grip !== null && this._grip.dispatchEvent(t), this._hand !== null && this._hand.dispatchEvent(t), this; + } + /** + * Connects the controller with the given XR input source. + * + * @param {XRInputSource} inputSource - The input source. + * @return {WebXRController} A reference to this instance. + */ + connect(t) { + if (t && t.hand) { + const e = this._hand; + if (e) + for (const n of t.hand.values()) + this._getHandJoint(e, n); + } + return this.dispatchEvent({ type: "connected", data: t }), this; + } + /** + * Disconnects the controller from the given XR input source. + * + * @param {XRInputSource} inputSource - The input source. + * @return {WebXRController} A reference to this instance. + */ + disconnect(t) { + return this.dispatchEvent({ type: "disconnected", data: t }), 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(t, e, n) { + let s = null, r = null, a = null; + const o = this._targetRay, c = this._grip, l = this._hand; + if (t && e.session.visibilityState !== "visible-blurred") { + if (l && t.hand) { + a = !0; + for (const x of t.hand.values()) { + const p = e.getJointPose(x, n), h = this._getHandJoint(l, x); + p !== null && (h.matrix.fromArray(p.transform.matrix), h.matrix.decompose(h.position, h.rotation, h.scale), h.matrixWorldNeedsUpdate = !0, h.jointRadius = p.radius), h.visible = p !== null; + } + const u = l.joints["index-finger-tip"], d = l.joints["thumb-tip"], f = u.position.distanceTo(d.position), m = 0.02, v = 5e-3; + l.inputState.pinching && f > m + v ? (l.inputState.pinching = !1, this.dispatchEvent({ + type: "pinchend", + handedness: t.handedness, + target: this + })) : !l.inputState.pinching && f <= m - v && (l.inputState.pinching = !0, this.dispatchEvent({ + type: "pinchstart", + handedness: t.handedness, + target: this + })); + } else + c !== null && t.gripSpace && (r = e.getPose(t.gripSpace, n), r !== null && (c.matrix.fromArray(r.transform.matrix), c.matrix.decompose(c.position, c.rotation, c.scale), c.matrixWorldNeedsUpdate = !0, r.linearVelocity ? (c.hasLinearVelocity = !0, c.linearVelocity.copy(r.linearVelocity)) : c.hasLinearVelocity = !1, r.angularVelocity ? (c.hasAngularVelocity = !0, c.angularVelocity.copy(r.angularVelocity)) : c.hasAngularVelocity = !1)); + o !== null && (s = e.getPose(t.targetRaySpace, n), s === null && r !== null && (s = r), s !== null && (o.matrix.fromArray(s.transform.matrix), o.matrix.decompose(o.position, o.rotation, o.scale), o.matrixWorldNeedsUpdate = !0, s.linearVelocity ? (o.hasLinearVelocity = !0, o.linearVelocity.copy(s.linearVelocity)) : o.hasLinearVelocity = !1, s.angularVelocity ? (o.hasAngularVelocity = !0, o.angularVelocity.copy(s.angularVelocity)) : o.hasAngularVelocity = !1, this.dispatchEvent(_c))); + } + return o !== null && (o.visible = s !== null), c !== null && (c.visible = r !== null), l !== null && (l.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(t, e) { + if (t.joints[e.jointName] === void 0) { + const n = new Yi(); + n.matrixAutoUpdate = !1, n.visible = !1, t.joints[e.jointName] = n, t.add(n); + } + return t.joints[e.jointName]; + } +} +class gc extends ge { + /** + * 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 je(), this.environmentIntensity = 1, this.environmentRotation = new je(), this.overrideMaterial = null, typeof __THREE_DEVTOOLS__ < "u" && __THREE_DEVTOOLS__.dispatchEvent(new CustomEvent("observe", { detail: this })); + } + copy(t, e) { + return super.copy(t, e), t.background !== null && (this.background = t.background.clone()), t.environment !== null && (this.environment = t.environment.clone()), t.fog !== null && (this.fog = t.fog.clone()), this.backgroundBlurriness = t.backgroundBlurriness, this.backgroundIntensity = t.backgroundIntensity, this.backgroundRotation.copy(t.backgroundRotation), this.environmentIntensity = t.environmentIntensity, this.environmentRotation.copy(t.environmentRotation), t.overrideMaterial !== null && (this.overrideMaterial = t.overrideMaterial.clone()), this.matrixAutoUpdate = t.matrixAutoUpdate, this; + } + toJSON(t) { + const e = super.toJSON(t); + return this.fog !== null && (e.object.fog = this.fog.toJSON()), this.backgroundBlurriness > 0 && (e.object.backgroundBlurriness = this.backgroundBlurriness), this.backgroundIntensity !== 1 && (e.object.backgroundIntensity = this.backgroundIntensity), e.object.backgroundRotation = this.backgroundRotation.toArray(), this.environmentIntensity !== 1 && (e.object.environmentIntensity = this.environmentIntensity), e.object.environmentRotation = this.environmentRotation.toArray(), e; + } +} +const Fs = /* @__PURE__ */ new N(), vc = /* @__PURE__ */ new N(), xc = /* @__PURE__ */ new It(); +class pn { + /** + * 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(t = new N(1, 0, 0), e = 0) { + this.isPlane = !0, this.normal = t, this.constant = e; + } + /** + * 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(t, e) { + return this.normal.copy(t), this.constant = e, 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(t, e, n, s) { + return this.normal.set(t, e, n), this.constant = s, 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(t, e) { + return this.normal.copy(t), this.constant = -e.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(t, e, n) { + const s = Fs.subVectors(n, e).cross(vc.subVectors(t, e)).normalize(); + return this.setFromNormalAndCoplanarPoint(s, t), 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(t) { + return this.normal.copy(t.normal), this.constant = t.constant, this; + } + /** + * Normalizes the plane normal and adjusts the constant accordingly. + * + * @return {Plane} A reference to this plane. + */ + normalize() { + const t = 1 / this.normal.length(); + return this.normal.multiplyScalar(t), this.constant *= t, 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(t) { + return this.normal.dot(t) + 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(t) { + return this.distanceToPoint(t.center) - t.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(t, e) { + return e.copy(t).addScaledVector(this.normal, -this.distanceToPoint(t)); + } + /** + * 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(t, e) { + const n = t.delta(Fs), s = this.normal.dot(n); + if (s === 0) + return this.distanceToPoint(t.start) === 0 ? e.copy(t.start) : null; + const r = -(t.start.dot(this.normal) + this.constant) / s; + return r < 0 || r > 1 ? null : e.copy(t.start).addScaledVector(n, r); + } + /** + * 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(t) { + const e = this.distanceToPoint(t.start), n = this.distanceToPoint(t.end); + return e < 0 && n > 0 || n < 0 && e > 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(t) { + return t.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(t) { + return t.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(t) { + return t.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(t, e) { + const n = e || xc.getNormalMatrix(t), s = this.coplanarPoint(Fs).applyMatrix4(t), r = this.normal.applyMatrix3(n).normalize(); + return this.constant = -s.dot(r), 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(t) { + return this.constant -= t.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(t) { + return t.normal.equals(this.normal) && t.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 bn = /* @__PURE__ */ new qr(), Mc = /* @__PURE__ */ new Ct(0.5, 0.5), qi = /* @__PURE__ */ new N(); +class $r { + /** + * 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(t = new pn(), e = new pn(), n = new pn(), s = new pn(), r = new pn(), a = new pn()) { + this.planes = [t, e, n, s, r, 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(t, e, n, s, r, a) { + const o = this.planes; + return o[0].copy(t), o[1].copy(e), o[2].copy(n), o[3].copy(s), o[4].copy(r), 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(t) { + const e = this.planes; + for (let n = 0; n < 6; n++) + e[n].copy(t.planes[n]); + 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(t, e = Ye, n = !1) { + const s = this.planes, r = t.elements, a = r[0], o = r[1], c = r[2], l = r[3], u = r[4], d = r[5], f = r[6], m = r[7], v = r[8], x = r[9], p = r[10], h = r[11], A = r[12], b = r[13], y = r[14], D = r[15]; + if (s[0].setComponents(l - a, m - u, h - v, D - A).normalize(), s[1].setComponents(l + a, m + u, h + v, D + A).normalize(), s[2].setComponents(l + o, m + d, h + x, D + b).normalize(), s[3].setComponents(l - o, m - d, h - x, D - b).normalize(), n) + s[4].setComponents(c, f, p, y).normalize(), s[5].setComponents(l - c, m - f, h - p, D - y).normalize(); + else if (s[4].setComponents(l - c, m - f, h - p, D - y).normalize(), e === Ye) + s[5].setComponents(l + c, m + f, h + p, D + y).normalize(); + else if (e === as) + s[5].setComponents(c, f, p, y).normalize(); + else + throw new Error("THREE.Frustum.setFromProjectionMatrix(): Invalid coordinate system: " + e); + 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(t) { + if (t.boundingSphere !== void 0) + t.boundingSphere === null && t.computeBoundingSphere(), bn.copy(t.boundingSphere).applyMatrix4(t.matrixWorld); + else { + const e = t.geometry; + e.boundingSphere === null && e.computeBoundingSphere(), bn.copy(e.boundingSphere).applyMatrix4(t.matrixWorld); + } + return this.intersectsSphere(bn); + } + /** + * 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(t) { + bn.center.set(0, 0, 0); + const e = Mc.distanceTo(t.center); + return bn.radius = 0.7071067811865476 + e, bn.applyMatrix4(t.matrixWorld), this.intersectsSphere(bn); + } + /** + * 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(t) { + const e = this.planes, n = t.center, s = -t.radius; + for (let r = 0; r < 6; r++) + if (e[r].distanceToPoint(n) < s) + 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(t) { + const e = this.planes; + for (let n = 0; n < 6; n++) { + const s = e[n]; + if (qi.x = s.normal.x > 0 ? t.max.x : t.min.x, qi.y = s.normal.y > 0 ? t.max.y : t.min.y, qi.z = s.normal.z > 0 ? t.max.z : t.min.z, s.distanceToPoint(qi) < 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(t) { + const e = this.planes; + for (let n = 0; n < 6; n++) + if (e[n].distanceToPoint(t) < 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); + } +} +class Sc extends Me { + /** + * 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(t, e, n, s, r, a, o, c, l) { + super(t, e, n, s, r, a, o, c, l), this.isCanvasTexture = !0, this.needsUpdate = !0; + } +} +class Uo extends Me { + /** + * 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(t, e, n = Un, s, r, a, o = Ge, c = Ge, l, u = xi, d = 1) { + if (u !== xi && u !== Mi) + throw new Error("DepthTexture format must be either THREE.DepthFormat or THREE.DepthStencilFormat"); + const f = { width: t, height: e, depth: d }; + super(f, s, r, a, o, c, u, n, l), this.isDepthTexture = !0, this.flipY = !1, this.generateMipmaps = !1, this.compareFunction = null; + } + copy(t) { + return super.copy(t), this.source = new Yr(Object.assign({}, t.image)), this.compareFunction = t.compareFunction, this; + } + toJSON(t) { + const e = super.toJSON(t); + return this.compareFunction !== null && (e.compareFunction = this.compareFunction), e; + } +} +class Io extends Me { + /** + * Creates a new raw texture. + * + * @param {?(WebGLTexture|GPUTexture)} [sourceTexture=null] - The external texture. + */ + constructor(t = null) { + super(), this.sourceTexture = t, this.isExternalTexture = !0; + } + copy(t) { + return super.copy(t), this.sourceTexture = t.sourceTexture, this; + } +} +class Jr extends an { + /** + * 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(t = 1, e = 32, n = 0, s = Math.PI * 2) { + super(), this.type = "CircleGeometry", this.parameters = { + radius: t, + segments: e, + thetaStart: n, + thetaLength: s + }, e = Math.max(3, e); + const r = [], a = [], o = [], c = [], l = new N(), u = new Ct(); + a.push(0, 0, 0), o.push(0, 0, 1), c.push(0.5, 0.5); + for (let d = 0, f = 3; d <= e; d++, f += 3) { + const m = n + d / e * s; + l.x = t * Math.cos(m), l.y = t * Math.sin(m), a.push(l.x, l.y, l.z), o.push(0, 0, 1), u.x = (a[f] / t + 1) / 2, u.y = (a[f + 1] / t + 1) / 2, c.push(u.x, u.y); + } + for (let d = 1; d <= e; d++) + r.push(d, d + 1, 0); + this.setIndex(r), this.setAttribute("position", new qe(a, 3)), this.setAttribute("normal", new qe(o, 3)), this.setAttribute("uv", new qe(c, 2)); + } + copy(t) { + return super.copy(t), this.parameters = Object.assign({}, t.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(t) { + return new Jr(t.radius, t.segments, t.thetaStart, t.thetaLength); + } +} +class cs extends an { + /** + * 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(t = 1, e = 1, n = 1, s = 1) { + super(), this.type = "PlaneGeometry", this.parameters = { + width: t, + height: e, + widthSegments: n, + heightSegments: s + }; + const r = t / 2, a = e / 2, o = Math.floor(n), c = Math.floor(s), l = o + 1, u = c + 1, d = t / o, f = e / c, m = [], v = [], x = [], p = []; + for (let h = 0; h < u; h++) { + const A = h * f - a; + for (let b = 0; b < l; b++) { + const y = b * d - r; + v.push(y, -A, 0), x.push(0, 0, 1), p.push(b / o), p.push(1 - h / c); + } + } + for (let h = 0; h < c; h++) + for (let A = 0; A < o; A++) { + const b = A + l * h, y = A + l * (h + 1), D = A + 1 + l * (h + 1), P = A + 1 + l * h; + m.push(b, y, P), m.push(y, D, P); + } + this.setIndex(m), this.setAttribute("position", new qe(v, 3)), this.setAttribute("normal", new qe(x, 3)), this.setAttribute("uv", new qe(p, 2)); + } + copy(t) { + return super.copy(t), this.parameters = Object.assign({}, t.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(t) { + return new cs(t.width, t.height, t.widthSegments, t.heightSegments); + } +} +class Os extends bi { + /** + * 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(t) { + super(), this.isMeshLambertMaterial = !0, this.type = "MeshLambertMaterial", this.color = new Vt(16777215), this.map = null, this.lightMap = null, this.lightMapIntensity = 1, this.aoMap = null, this.aoMapIntensity = 1, this.emissive = new Vt(0), this.emissiveIntensity = 1, this.emissiveMap = null, this.bumpMap = null, this.bumpScale = 1, this.normalMap = null, this.normalMapType = yo, this.normalScale = new Ct(1, 1), this.displacementMap = null, this.displacementScale = 1, this.displacementBias = 0, this.specularMap = null, this.alphaMap = null, this.envMap = null, this.envMapRotation = new je(), this.combine = zr, 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(t); + } + copy(t) { + return super.copy(t), this.color.copy(t.color), this.map = t.map, this.lightMap = t.lightMap, this.lightMapIntensity = t.lightMapIntensity, this.aoMap = t.aoMap, this.aoMapIntensity = t.aoMapIntensity, this.emissive.copy(t.emissive), this.emissiveMap = t.emissiveMap, this.emissiveIntensity = t.emissiveIntensity, this.bumpMap = t.bumpMap, this.bumpScale = t.bumpScale, this.normalMap = t.normalMap, this.normalMapType = t.normalMapType, this.normalScale.copy(t.normalScale), this.displacementMap = t.displacementMap, this.displacementScale = t.displacementScale, this.displacementBias = t.displacementBias, this.specularMap = t.specularMap, this.alphaMap = t.alphaMap, this.envMap = t.envMap, this.envMapRotation.copy(t.envMapRotation), this.combine = t.combine, this.reflectivity = t.reflectivity, this.refractionRatio = t.refractionRatio, this.wireframe = t.wireframe, this.wireframeLinewidth = t.wireframeLinewidth, this.wireframeLinecap = t.wireframeLinecap, this.wireframeLinejoin = t.wireframeLinejoin, this.flatShading = t.flatShading, this.fog = t.fog, this; + } +} +class Ec extends bi { + /** + * 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(t) { + super(), this.isMeshDepthMaterial = !0, this.type = "MeshDepthMaterial", this.depthPacking = Ul, this.map = null, this.alphaMap = null, this.displacementMap = null, this.displacementScale = 1, this.displacementBias = 0, this.wireframe = !1, this.wireframeLinewidth = 1, this.setValues(t); + } + copy(t) { + return super.copy(t), this.depthPacking = t.depthPacking, this.map = t.map, this.alphaMap = t.alphaMap, this.displacementMap = t.displacementMap, this.displacementScale = t.displacementScale, this.displacementBias = t.displacementBias, this.wireframe = t.wireframe, this.wireframeLinewidth = t.wireframeLinewidth, this; + } +} +class yc extends bi { + /** + * 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(t) { + super(), this.isMeshDistanceMaterial = !0, this.type = "MeshDistanceMaterial", this.map = null, this.alphaMap = null, this.displacementMap = null, this.displacementScale = 1, this.displacementBias = 0, this.setValues(t); + } + copy(t) { + return super.copy(t), this.map = t.map, this.alphaMap = t.alphaMap, this.displacementMap = t.displacementMap, this.displacementScale = t.displacementScale, this.displacementBias = t.displacementBias, this; + } +} +class No extends ge { + /** + * Constructs a new light. + * + * @param {(number|Color|string)} [color=0xffffff] - The light's color. + * @param {number} [intensity=1] - The light's strength/intensity. + */ + constructor(t, e = 1) { + super(), this.isLight = !0, this.type = "Light", this.color = new Vt(t), this.intensity = e; + } + /** + * Frees the GPU-related resources allocated by this instance. Call this + * method whenever this instance is no longer used in your app. + */ + dispose() { + } + copy(t, e) { + return super.copy(t, e), this.color.copy(t.color), this.intensity = t.intensity, this; + } + toJSON(t) { + const e = super.toJSON(t); + return e.object.color = this.color.getHex(), e.object.intensity = this.intensity, this.groundColor !== void 0 && (e.object.groundColor = this.groundColor.getHex()), this.distance !== void 0 && (e.object.distance = this.distance), this.angle !== void 0 && (e.object.angle = this.angle), this.decay !== void 0 && (e.object.decay = this.decay), this.penumbra !== void 0 && (e.object.penumbra = this.penumbra), this.shadow !== void 0 && (e.object.shadow = this.shadow.toJSON()), this.target !== void 0 && (e.object.target = this.target.uuid), e; + } +} +const Bs = /* @__PURE__ */ new ae(), Da = /* @__PURE__ */ new N(), La = /* @__PURE__ */ new N(); +class Tc { + /** + * Constructs a new light shadow. + * + * @param {Camera} camera - The light's view of the world. + */ + constructor(t) { + this.camera = t, this.intensity = 1, this.bias = 0, this.normalBias = 0, this.radius = 1, this.blurSamples = 8, this.mapSize = new Ct(512, 512), this.mapType = Ke, this.map = null, this.mapPass = null, this.matrix = new ae(), this.autoUpdate = !0, this.needsUpdate = !1, this._frustum = new $r(), this._frameExtents = new Ct(1, 1), this._viewportCount = 1, this._viewports = [ + new re(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(t) { + const e = this.camera, n = this.matrix; + Da.setFromMatrixPosition(t.matrixWorld), e.position.copy(Da), La.setFromMatrixPosition(t.target.matrixWorld), e.lookAt(La), e.updateMatrixWorld(), Bs.multiplyMatrices(e.projectionMatrix, e.matrixWorldInverse), this._frustum.setFromProjectionMatrix(Bs, e.coordinateSystem, e.reversedDepth), e.reversedDepth ? n.set( + 0.5, + 0, + 0, + 0.5, + 0, + 0.5, + 0, + 0.5, + 0, + 0, + 1, + 0, + 0, + 0, + 0, + 1 + ) : n.set( + 0.5, + 0, + 0, + 0.5, + 0, + 0.5, + 0, + 0.5, + 0, + 0, + 0.5, + 0.5, + 0, + 0, + 0, + 1 + ), n.multiply(Bs); + } + /** + * Returns a viewport definition for the given viewport index. + * + * @param {number} viewportIndex - The viewport index. + * @return {Vector4} The viewport. + */ + getViewport(t) { + return this._viewports[t]; + } + /** + * 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(t) { + return this.camera = t.camera.clone(), this.intensity = t.intensity, this.bias = t.bias, this.radius = t.radius, this.autoUpdate = t.autoUpdate, this.needsUpdate = t.needsUpdate, this.normalBias = t.normalBias, this.blurSamples = t.blurSamples, this.mapSize.copy(t.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 t = {}; + return this.intensity !== 1 && (t.intensity = this.intensity), this.bias !== 0 && (t.bias = this.bias), this.normalBias !== 0 && (t.normalBias = this.normalBias), this.radius !== 1 && (t.radius = this.radius), (this.mapSize.x !== 512 || this.mapSize.y !== 512) && (t.mapSize = this.mapSize.toArray()), t.camera = this.camera.toJSON(!1).object, delete t.camera.matrix, t; + } +} +class Fo extends Do { + /** + * 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(t = -1, e = 1, n = 1, s = -1, r = 0.1, a = 2e3) { + super(), this.isOrthographicCamera = !0, this.type = "OrthographicCamera", this.zoom = 1, this.view = null, this.left = t, this.right = e, this.top = n, this.bottom = s, this.near = r, this.far = a, this.updateProjectionMatrix(); + } + copy(t, e) { + return super.copy(t, e), this.left = t.left, this.right = t.right, this.top = t.top, this.bottom = t.bottom, this.near = t.near, this.far = t.far, this.zoom = t.zoom, this.view = t.view === null ? null : Object.assign({}, t.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(t, e, n, s, r, 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 = t, this.view.fullHeight = e, this.view.offsetX = n, this.view.offsetY = s, this.view.width = r, 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 t = (this.right - this.left) / (2 * this.zoom), e = (this.top - this.bottom) / (2 * this.zoom), n = (this.right + this.left) / 2, s = (this.top + this.bottom) / 2; + let r = n - t, a = n + t, o = s + e, c = s - e; + if (this.view !== null && this.view.enabled) { + const l = (this.right - this.left) / this.view.fullWidth / this.zoom, u = (this.top - this.bottom) / this.view.fullHeight / this.zoom; + r += l * this.view.offsetX, a = r + l * this.view.width, o -= u * this.view.offsetY, c = o - u * this.view.height; + } + this.projectionMatrix.makeOrthographic(r, a, o, c, this.near, this.far, this.coordinateSystem, this.reversedDepth), this.projectionMatrixInverse.copy(this.projectionMatrix).invert(); + } + toJSON(t) { + const e = super.toJSON(t); + return e.object.zoom = this.zoom, e.object.left = this.left, e.object.right = this.right, e.object.top = this.top, e.object.bottom = this.bottom, e.object.near = this.near, e.object.far = this.far, this.view !== null && (e.object.view = Object.assign({}, this.view)), e; + } +} +class bc extends Tc { + /** + * Constructs a new directional light shadow. + */ + constructor() { + super(new Fo(-5, 5, 5, -5, 0.5, 500)), this.isDirectionalLightShadow = !0; + } +} +class Ac extends No { + /** + * 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(t, e) { + super(t, e), this.isDirectionalLight = !0, this.type = "DirectionalLight", this.position.copy(ge.DEFAULT_UP), this.updateMatrix(), this.target = new ge(), this.shadow = new bc(); + } + dispose() { + this.shadow.dispose(); + } + copy(t) { + return super.copy(t), this.target = t.target.clone(), this.shadow = t.shadow.clone(), this; + } +} +class Rc extends No { + /** + * 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(t, e) { + super(t, e), this.isAmbientLight = !0, this.type = "AmbientLight"; + } +} +class wc extends Ne { + /** + * Constructs a new array camera. + * + * @param {Array} [array=[]] - An array of perspective sub cameras. + */ + constructor(t = []) { + super(), this.isArrayCamera = !0, this.isMultiViewCamera = !1, this.cameras = t; + } +} +const Ua = /* @__PURE__ */ new ae(); +class Cc { + /** + * 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(t, e, n = 0, s = 1 / 0) { + this.ray = new Kr(t, e), this.near = n, this.far = s, this.camera = null, this.layers = new jr(), 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(t, e) { + this.ray.set(t, e); + } + /** + * 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(t, e) { + e.isPerspectiveCamera ? (this.ray.origin.setFromMatrixPosition(e.matrixWorld), this.ray.direction.set(t.x, t.y, 0.5).unproject(e).sub(this.ray.origin).normalize(), this.camera = e) : e.isOrthographicCamera ? (this.ray.origin.set(t.x, t.y, (e.near + e.far) / (e.near - e.far)).unproject(e), this.ray.direction.set(0, 0, -1).transformDirection(e.matrixWorld), this.camera = e) : console.error("THREE.Raycaster: Unsupported camera type: " + e.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(t) { + return Ua.identity().extractRotation(t.matrixWorld), this.ray.origin.setFromMatrixPosition(t.matrixWorld), this.ray.direction.set(0, 0, -1).applyMatrix4(Ua), 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} [intersects=[]] The target array that holds the result of the method. + * @return {Array} An array holding the intersection points. + */ + intersectObject(t, e = !0, n = []) { + return Fr(t, this, n, e), n.sort(Ia), n; + } + /** + * Checks all intersection between the ray and the objects with or without + * the descendants. Intersections are returned sorted by distance, closest first. + * + * @param {Array} 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} [intersects=[]] The target array that holds the result of the method. + * @return {Array} An array holding the intersection points. + */ + intersectObjects(t, e = !0, n = []) { + for (let s = 0, r = t.length; s < r; s++) + Fr(t[s], this, n, e); + return n.sort(Ia), n; + } +} +function Ia(i, t) { + return i.distance - t.distance; +} +function Fr(i, t, e, n) { + let s = !0; + if (i.layers.test(t.layers) && i.raycast(t, e) === !1 && (s = !1), s === !0 && n === !0) { + const r = i.children; + for (let a = 0, o = r.length; a < o; a++) + Fr(r[a], t, e, !0); + } +} +class Na { + /** + * 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(t = 1, e = 0, n = 0) { + this.radius = t, this.phi = e, this.theta = n; + } + /** + * 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(t, e, n) { + return this.radius = t, this.phi = e, this.theta = n, 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(t) { + return this.radius = t.radius, this.phi = t.phi, this.theta = t.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 = Bt(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(t) { + return this.setFromCartesianCoords(t.x, t.y, t.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(t, e, n) { + return this.radius = Math.sqrt(t * t + e * e + n * n), this.radius === 0 ? (this.theta = 0, this.phi = 0) : (this.theta = Math.atan2(t, n), this.phi = Math.acos(Bt(e / 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 Pc extends Fn { + /** + * 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(t, e = null) { + super(), this.object = t, this.domElement = e, 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(t) { + if (t === void 0) { + console.warn("THREE.Controls: connect() now requires an element."); + return; + } + this.domElement !== null && this.disconnect(), this.domElement = t; + } + /** + * 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 Fa(i, t, e, n) { + const s = Dc(n); + switch (e) { + // https://registry.khronos.org/OpenGL-Refpages/es3.0/html/glTexImage2D.xhtml + case xo: + return i * t; + case So: + return i * t / s.components * s.byteLength; + case kr: + return i * t / s.components * s.byteLength; + case Eo: + return i * t * 2 / s.components * s.byteLength; + case Wr: + return i * t * 2 / s.components * s.byteLength; + case Mo: + return i * t * 3 / s.components * s.byteLength; + case Ve: + return i * t * 4 / s.components * s.byteLength; + case Xr: + return i * t * 4 / s.components * s.byteLength; + // https://registry.khronos.org/webgl/extensions/WEBGL_compressed_texture_s3tc_srgb/ + case Qi: + case ts: + return Math.floor((i + 3) / 4) * Math.floor((t + 3) / 4) * 8; + case es: + case ns: + return Math.floor((i + 3) / 4) * Math.floor((t + 3) / 4) * 16; + // https://registry.khronos.org/webgl/extensions/WEBGL_compressed_texture_pvrtc/ + case lr: + case hr: + return Math.max(i, 16) * Math.max(t, 8) / 4; + case or: + case cr: + return Math.max(i, 8) * Math.max(t, 8) / 2; + // https://registry.khronos.org/webgl/extensions/WEBGL_compressed_texture_etc/ + case ur: + case dr: + return Math.floor((i + 3) / 4) * Math.floor((t + 3) / 4) * 8; + case fr: + return Math.floor((i + 3) / 4) * Math.floor((t + 3) / 4) * 16; + // https://registry.khronos.org/webgl/extensions/WEBGL_compressed_texture_astc/ + case pr: + return Math.floor((i + 3) / 4) * Math.floor((t + 3) / 4) * 16; + case mr: + return Math.floor((i + 4) / 5) * Math.floor((t + 3) / 4) * 16; + case _r: + return Math.floor((i + 4) / 5) * Math.floor((t + 4) / 5) * 16; + case gr: + return Math.floor((i + 5) / 6) * Math.floor((t + 4) / 5) * 16; + case vr: + return Math.floor((i + 5) / 6) * Math.floor((t + 5) / 6) * 16; + case xr: + return Math.floor((i + 7) / 8) * Math.floor((t + 4) / 5) * 16; + case Mr: + return Math.floor((i + 7) / 8) * Math.floor((t + 5) / 6) * 16; + case Sr: + return Math.floor((i + 7) / 8) * Math.floor((t + 7) / 8) * 16; + case Er: + return Math.floor((i + 9) / 10) * Math.floor((t + 4) / 5) * 16; + case yr: + return Math.floor((i + 9) / 10) * Math.floor((t + 5) / 6) * 16; + case Tr: + return Math.floor((i + 9) / 10) * Math.floor((t + 7) / 8) * 16; + case br: + return Math.floor((i + 9) / 10) * Math.floor((t + 9) / 10) * 16; + case Ar: + return Math.floor((i + 11) / 12) * Math.floor((t + 9) / 10) * 16; + case Rr: + return Math.floor((i + 11) / 12) * Math.floor((t + 11) / 12) * 16; + // https://registry.khronos.org/webgl/extensions/EXT_texture_compression_bptc/ + case wr: + case Cr: + case Pr: + return Math.ceil(i / 4) * Math.ceil(t / 4) * 16; + // https://registry.khronos.org/webgl/extensions/EXT_texture_compression_rgtc/ + case Dr: + case Lr: + return Math.ceil(i / 4) * Math.ceil(t / 4) * 8; + case Ur: + case Ir: + return Math.ceil(i / 4) * Math.ceil(t / 4) * 16; + } + throw new Error( + `Unable to determine texture byte length for ${e} format.` + ); +} +function Dc(i) { + switch (i) { + case Ke: + case mo: + return { byteLength: 1, components: 1 }; + case gi: + case _o: + case Ei: + return { byteLength: 2, components: 1 }; + case Vr: + case Gr: + return { byteLength: 2, components: 4 }; + case Un: + case Hr: + case sn: + return { byteLength: 4, components: 1 }; + case go: + case vo: + return { byteLength: 4, components: 3 }; + } + throw new Error(`Unknown texture type ${i}.`); +} +typeof __THREE_DEVTOOLS__ < "u" && __THREE_DEVTOOLS__.dispatchEvent(new CustomEvent("register", { detail: { + revision: Br +} })); +typeof window < "u" && (window.__THREE__ ? console.warn("WARNING: Multiple instances of Three.js being imported.") : window.__THREE__ = Br); +/** + * @license + * Copyright 2010-2025 Three.js Authors + * SPDX-License-Identifier: MIT + */ +function Oo() { + let i = null, t = !1, e = null, n = null; + function s(r, a) { + e(r, a), n = i.requestAnimationFrame(s); + } + return { + start: function() { + t !== !0 && e !== null && (n = i.requestAnimationFrame(s), t = !0); + }, + stop: function() { + i.cancelAnimationFrame(n), t = !1; + }, + setAnimationLoop: function(r) { + e = r; + }, + setContext: function(r) { + i = r; + } + }; +} +function Lc(i) { + const t = /* @__PURE__ */ new WeakMap(); + function e(o, c) { + const l = o.array, u = o.usage, d = l.byteLength, f = i.createBuffer(); + i.bindBuffer(c, f), i.bufferData(c, l, u), o.onUploadCallback(); + let m; + if (l instanceof Float32Array) + m = i.FLOAT; + else if (typeof Float16Array < "u" && l instanceof Float16Array) + m = i.HALF_FLOAT; + else if (l instanceof Uint16Array) + o.isFloat16BufferAttribute ? m = i.HALF_FLOAT : m = i.UNSIGNED_SHORT; + else if (l instanceof Int16Array) + m = i.SHORT; + else if (l instanceof Uint32Array) + m = i.UNSIGNED_INT; + else if (l instanceof Int32Array) + m = i.INT; + else if (l instanceof Int8Array) + m = i.BYTE; + else if (l instanceof Uint8Array) + m = i.UNSIGNED_BYTE; + else if (l instanceof Uint8ClampedArray) + m = i.UNSIGNED_BYTE; + else + throw new Error("THREE.WebGLAttributes: Unsupported buffer data format: " + l); + return { + buffer: f, + type: m, + bytesPerElement: l.BYTES_PER_ELEMENT, + version: o.version, + size: d + }; + } + function n(o, c, l) { + const u = c.array, d = c.updateRanges; + if (i.bindBuffer(l, o), d.length === 0) + i.bufferSubData(l, 0, u); + else { + d.sort((m, v) => m.start - v.start); + let f = 0; + for (let m = 1; m < d.length; m++) { + const v = d[f], x = d[m]; + x.start <= v.start + v.count + 1 ? v.count = Math.max( + v.count, + x.start + x.count - v.start + ) : (++f, d[f] = x); + } + d.length = f + 1; + for (let m = 0, v = d.length; m < v; m++) { + const x = d[m]; + i.bufferSubData( + l, + x.start * u.BYTES_PER_ELEMENT, + u, + x.start, + x.count + ); + } + c.clearUpdateRanges(); + } + c.onUploadCallback(); + } + function s(o) { + return o.isInterleavedBufferAttribute && (o = o.data), t.get(o); + } + function r(o) { + o.isInterleavedBufferAttribute && (o = o.data); + const c = t.get(o); + c && (i.deleteBuffer(c.buffer), t.delete(o)); + } + function a(o, c) { + if (o.isInterleavedBufferAttribute && (o = o.data), o.isGLBufferAttribute) { + const u = t.get(o); + (!u || u.version < o.version) && t.set(o, { + buffer: o.buffer, + type: o.type, + bytesPerElement: o.elementSize, + version: o.version + }); + return; + } + const l = t.get(o); + if (l === void 0) + t.set(o, e(o, c)); + else if (l.version < o.version) { + if (l.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."); + n(l.buffer, o, c), l.version = o.version; + } + } + return { + get: s, + remove: r, + update: a + }; +} +var Uc = `#ifdef USE_ALPHAHASH + if ( diffuseColor.a < getAlphaHashThreshold( vPosition ) ) discard; +#endif`, Ic = `#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`, Nc = `#ifdef USE_ALPHAMAP + diffuseColor.a *= texture2D( alphaMap, vAlphaMapUv ).g; +#endif`, Fc = `#ifdef USE_ALPHAMAP + uniform sampler2D alphaMap; +#endif`, Oc = `#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`, Bc = `#ifdef USE_ALPHATEST + uniform float alphaTest; +#endif`, zc = `#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`, Hc = `#ifdef USE_AOMAP + uniform sampler2D aoMap; + uniform float aoMapIntensity; +#endif`, Vc = `#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`, Gc = `#ifdef USE_BATCHING + mat4 batchingMatrix = getBatchingMatrix( getIndirectIndex( gl_DrawID ) ); +#endif`, kc = `vec3 transformed = vec3( position ); +#ifdef USE_ALPHAHASH + vPosition = vec3( position ); +#endif`, Wc = `vec3 objectNormal = vec3( normal ); +#ifdef USE_TANGENT + vec3 objectTangent = vec3( tangent.xyz ); +#endif`, Xc = `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`, Yc = `#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`, qc = `#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`, Kc = `#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`, jc = `#if NUM_CLIPPING_PLANES > 0 + varying vec3 vClipPosition; + uniform vec4 clippingPlanes[ NUM_CLIPPING_PLANES ]; +#endif`, Zc = `#if NUM_CLIPPING_PLANES > 0 + varying vec3 vClipPosition; +#endif`, $c = `#if NUM_CLIPPING_PLANES > 0 + vClipPosition = - mvPosition.xyz; +#endif`, Jc = `#if defined( USE_COLOR_ALPHA ) + diffuseColor *= vColor; +#elif defined( USE_COLOR ) + diffuseColor.rgb *= vColor; +#endif`, Qc = `#if defined( USE_COLOR_ALPHA ) + varying vec4 vColor; +#elif defined( USE_COLOR ) + varying vec3 vColor; +#endif`, th = `#if defined( USE_COLOR_ALPHA ) + varying vec4 vColor; +#elif defined( USE_COLOR ) || defined( USE_INSTANCING_COLOR ) || defined( USE_BATCHING_COLOR ) + varying vec3 vColor; +#endif`, eh = `#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`, nh = `#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`, ih = `#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`, sh = `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`, rh = `#ifdef USE_DISPLACEMENTMAP + uniform sampler2D displacementMap; + uniform float displacementScale; + uniform float displacementBias; +#endif`, ah = `#ifdef USE_DISPLACEMENTMAP + transformed += normalize( objectNormal ) * ( texture2D( displacementMap, vDisplacementMapUv ).x * displacementScale + displacementBias ); +#endif`, oh = `#ifdef USE_EMISSIVEMAP + vec4 emissiveColor = texture2D( emissiveMap, vEmissiveMapUv ); + #ifdef DECODE_VIDEO_TEXTURE_EMISSIVE + emissiveColor = sRGBTransferEOTF( emissiveColor ); + #endif + totalEmissiveRadiance *= emissiveColor.rgb; +#endif`, lh = `#ifdef USE_EMISSIVEMAP + uniform sampler2D emissiveMap; +#endif`, ch = "gl_FragColor = linearToOutputTexel( gl_FragColor );", hh = `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 ); +}`, uh = `#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`, dh = `#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`, fh = `#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`, ph = `#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`, mh = `#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`, _h = `#ifdef USE_FOG + vFogDepth = - mvPosition.z; +#endif`, gh = `#ifdef USE_FOG + varying float vFogDepth; +#endif`, vh = `#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`, xh = `#ifdef USE_FOG + uniform vec3 fogColor; + varying float vFogDepth; + #ifdef FOG_EXP2 + uniform float fogDensity; + #else + uniform float fogNear; + uniform float fogFar; + #endif +#endif`, Mh = `#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 +}`, Sh = `#ifdef USE_LIGHTMAP + uniform sampler2D lightMap; + uniform float lightMapIntensity; +#endif`, Eh = `LambertMaterial material; +material.diffuseColor = diffuseColor.rgb; +material.specularStrength = specularStrength;`, yh = `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`, Th = `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`, bh = `#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`, Ah = `ToonMaterial material; +material.diffuseColor = diffuseColor.rgb;`, Rh = `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`, wh = `BlinnPhongMaterial material; +material.diffuseColor = diffuseColor.rgb; +material.specularColor = specular; +material.specularShininess = shininess; +material.specularStrength = specularStrength;`, Ch = `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`, Ph = `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`, Dh = `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 ); +}`, Lh = ` +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`, Uh = `#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`, Ih = `#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`, Nh = `#if defined( USE_LOGARITHMIC_DEPTH_BUFFER ) + gl_FragDepth = vIsPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5; +#endif`, Fh = `#if defined( USE_LOGARITHMIC_DEPTH_BUFFER ) + uniform float logDepthBufFC; + varying float vFragDepth; + varying float vIsPerspective; +#endif`, Oh = `#ifdef USE_LOGARITHMIC_DEPTH_BUFFER + varying float vFragDepth; + varying float vIsPerspective; +#endif`, Bh = `#ifdef USE_LOGARITHMIC_DEPTH_BUFFER + vFragDepth = 1.0 + gl_Position.w; + vIsPerspective = float( isPerspectiveMatrix( projectionMatrix ) ); +#endif`, zh = `#ifdef USE_MAP + vec4 sampledDiffuseColor = texture2D( map, vMapUv ); + #ifdef DECODE_VIDEO_TEXTURE + sampledDiffuseColor = sRGBTransferEOTF( sampledDiffuseColor ); + #endif + diffuseColor *= sampledDiffuseColor; +#endif`, Hh = `#ifdef USE_MAP + uniform sampler2D map; +#endif`, Vh = `#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`, Gh = `#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`, kh = `float metalnessFactor = metalness; +#ifdef USE_METALNESSMAP + vec4 texelMetalness = texture2D( metalnessMap, vMetalnessMapUv ); + metalnessFactor *= texelMetalness.b; +#endif`, Wh = `#ifdef USE_METALNESSMAP + uniform sampler2D metalnessMap; +#endif`, Xh = `#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`, Yh = `#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`, qh = `#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`, Kh = `#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`, jh = `#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`, Zh = `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;`, $h = `#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`, Jh = `#ifndef FLAT_SHADED + varying vec3 vNormal; + #ifdef USE_TANGENT + varying vec3 vTangent; + varying vec3 vBitangent; + #endif +#endif`, Qh = `#ifndef FLAT_SHADED + varying vec3 vNormal; + #ifdef USE_TANGENT + varying vec3 vTangent; + varying vec3 vBitangent; + #endif +#endif`, tu = `#ifndef FLAT_SHADED + vNormal = normalize( transformedNormal ); + #ifdef USE_TANGENT + vTangent = normalize( transformedTangent ); + vBitangent = normalize( cross( vNormal, vTangent ) * tangent.w ); + #endif +#endif`, eu = `#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`, nu = `#ifdef USE_CLEARCOAT + vec3 clearcoatNormal = nonPerturbedNormal; +#endif`, iu = `#ifdef USE_CLEARCOAT_NORMALMAP + vec3 clearcoatMapN = texture2D( clearcoatNormalMap, vClearcoatNormalMapUv ).xyz * 2.0 - 1.0; + clearcoatMapN.xy *= clearcoatNormalScale; + clearcoatNormal = normalize( tbn2 * clearcoatMapN ); +#endif`, su = `#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`, ru = `#ifdef USE_IRIDESCENCEMAP + uniform sampler2D iridescenceMap; +#endif +#ifdef USE_IRIDESCENCE_THICKNESSMAP + uniform sampler2D iridescenceThicknessMap; +#endif`, au = `#ifdef OPAQUE +diffuseColor.a = 1.0; +#endif +#ifdef USE_TRANSMISSION +diffuseColor.a *= material.transmissionAlpha; +#endif +gl_FragColor = vec4( outgoingLight, diffuseColor.a );`, ou = `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 ); +}`, lu = `#ifdef PREMULTIPLIED_ALPHA + gl_FragColor.rgb *= gl_FragColor.a; +#endif`, cu = `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;`, hu = `#ifdef DITHERING + gl_FragColor.rgb = dithering( gl_FragColor.rgb ); +#endif`, uu = `#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`, du = `float roughnessFactor = roughness; +#ifdef USE_ROUGHNESSMAP + vec4 texelRoughness = texture2D( roughnessMap, vRoughnessMapUv ); + roughnessFactor *= texelRoughness.g; +#endif`, fu = `#ifdef USE_ROUGHNESSMAP + uniform sampler2D roughnessMap; +#endif`, pu = `#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`, mu = `#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`, _u = `#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`, gu = `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; +}`, vu = `#ifdef USE_SKINNING + mat4 boneMatX = getBoneMatrix( skinIndex.x ); + mat4 boneMatY = getBoneMatrix( skinIndex.y ); + mat4 boneMatZ = getBoneMatrix( skinIndex.z ); + mat4 boneMatW = getBoneMatrix( skinIndex.w ); +#endif`, xu = `#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`, Mu = `#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`, Su = `#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`, Eu = `float specularStrength; +#ifdef USE_SPECULARMAP + vec4 texelSpecular = texture2D( specularMap, vSpecularMapUv ); + specularStrength = texelSpecular.r; +#else + specularStrength = 1.0; +#endif`, yu = `#ifdef USE_SPECULARMAP + uniform sampler2D specularMap; +#endif`, Tu = `#if defined( TONE_MAPPING ) + gl_FragColor.rgb = toneMapping( gl_FragColor.rgb ); +#endif`, bu = `#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; }`, Au = `#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`, Ru = `#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`, wu = `#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`, Cu = `#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`, Pu = `#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`, Du = `#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 Lu = `varying vec2 vUv; +uniform mat3 uvTransform; +void main() { + vUv = ( uvTransform * vec3( uv, 1 ) ).xy; + gl_Position = vec4( position.xy, 1.0, 1.0 ); +}`, Uu = `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 + #include +}`, Iu = `varying vec3 vWorldDirection; +#include +void main() { + vWorldDirection = transformDirection( position, modelMatrix ); + #include + #include + gl_Position.z = gl_Position.w; +}`, Nu = `#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 +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 + #include +}`, Fu = `varying vec3 vWorldDirection; +#include +void main() { + vWorldDirection = transformDirection( position, modelMatrix ); + #include + #include + gl_Position.z = gl_Position.w; +}`, Ou = `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 + #include +}`, Bu = `#include +#include +#include +#include +#include +#include +#include +#include +varying vec2 vHighPrecisionZW; +void main() { + #include + #include + #include + #include + #ifdef USE_DISPLACEMENTMAP + #include + #include + #include + #endif + #include + #include + #include + #include + #include + #include + #include + vHighPrecisionZW = gl_Position.zw; +}`, zu = `#if DEPTH_PACKING == 3200 + uniform float opacity; +#endif +#include +#include +#include +#include +#include +#include +#include +#include +#include +varying vec2 vHighPrecisionZW; +void main() { + vec4 diffuseColor = vec4( 1.0 ); + #include + #if DEPTH_PACKING == 3200 + diffuseColor.a = opacity; + #endif + #include + #include + #include + #include + #include + #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 +}`, Hu = `#define DISTANCE +varying vec3 vWorldPosition; +#include +#include +#include +#include +#include +#include +#include +void main() { + #include + #include + #include + #include + #ifdef USE_DISPLACEMENTMAP + #include + #include + #include + #endif + #include + #include + #include + #include + #include + #include + #include + vWorldPosition = worldPosition.xyz; +}`, Vu = `#define DISTANCE +uniform vec3 referencePosition; +uniform float nearDistance; +uniform float farDistance; +varying vec3 vWorldPosition; +#include +#include +#include +#include +#include +#include +#include +#include +void main () { + vec4 diffuseColor = vec4( 1.0 ); + #include + #include + #include + #include + #include + float dist = length( vWorldPosition - referencePosition ); + dist = ( dist - nearDistance ) / ( farDistance - nearDistance ); + dist = saturate( dist ); + gl_FragColor = packDepthToRGBA( dist ); +}`, Gu = `varying vec3 vWorldDirection; +#include +void main() { + vWorldDirection = transformDirection( position, modelMatrix ); + #include + #include +}`, ku = `uniform sampler2D tEquirect; +varying vec3 vWorldDirection; +#include +void main() { + vec3 direction = normalize( vWorldDirection ); + vec2 sampleUV = equirectUv( direction ); + gl_FragColor = texture2D( tEquirect, sampleUV ); + #include + #include +}`, Wu = `uniform float scale; +attribute float lineDistance; +varying float vLineDistance; +#include +#include +#include +#include +#include +#include +#include +void main() { + vLineDistance = scale * lineDistance; + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include +}`, Xu = `uniform vec3 diffuse; +uniform float opacity; +uniform float dashSize; +uniform float totalSize; +varying float vLineDistance; +#include +#include +#include +#include +#include +#include +#include +void main() { + vec4 diffuseColor = vec4( diffuse, opacity ); + #include + if ( mod( vLineDistance, totalSize ) > dashSize ) { + discard; + } + vec3 outgoingLight = vec3( 0.0 ); + #include + #include + #include + outgoingLight = diffuseColor.rgb; + #include + #include + #include + #include + #include +}`, Yu = `#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +void main() { + #include + #include + #include + #include + #include + #if defined ( USE_ENVMAP ) || defined ( USE_SKINNING ) + #include + #include + #include + #include + #include + #endif + #include + #include + #include + #include + #include + #include + #include + #include + #include +}`, qu = `uniform vec3 diffuse; +uniform float opacity; +#ifndef FLAT_SHADED + varying vec3 vNormal; +#endif +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +void main() { + vec4 diffuseColor = vec4( diffuse, opacity ); + #include + #include + #include + #include + #include + #include + #include + #include + 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 + reflectedLight.indirectDiffuse *= diffuseColor.rgb; + vec3 outgoingLight = reflectedLight.indirectDiffuse; + #include + #include + #include + #include + #include + #include + #include +}`, Ku = `#define LAMBERT +varying vec3 vViewPosition; +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +void main() { + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + vViewPosition = - mvPosition.xyz; + #include + #include + #include + #include +}`, ju = `#define LAMBERT +uniform vec3 diffuse; +uniform vec3 emissive; +uniform float opacity; +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +void main() { + vec4 diffuseColor = vec4( diffuse, opacity ); + #include + ReflectedLight reflectedLight = ReflectedLight( vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ) ); + vec3 totalEmissiveRadiance = emissive; + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + vec3 outgoingLight = reflectedLight.directDiffuse + reflectedLight.indirectDiffuse + totalEmissiveRadiance; + #include + #include + #include + #include + #include + #include + #include +}`, Zu = `#define MATCAP +varying vec3 vViewPosition; +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +void main() { + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + vViewPosition = - mvPosition.xyz; +}`, $u = `#define MATCAP +uniform vec3 diffuse; +uniform float opacity; +uniform sampler2D matcap; +varying vec3 vViewPosition; +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +void main() { + vec4 diffuseColor = vec4( diffuse, opacity ); + #include + #include + #include + #include + #include + #include + #include + #include + #include + 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 + #include + #include + #include + #include + #include +}`, Ju = `#define NORMAL +#if defined( FLAT_SHADED ) || defined( USE_BUMPMAP ) || defined( USE_NORMALMAP_TANGENTSPACE ) + varying vec3 vViewPosition; +#endif +#include +#include +#include +#include +#include +#include +#include +#include +#include +void main() { + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include +#if defined( FLAT_SHADED ) || defined( USE_BUMPMAP ) || defined( USE_NORMALMAP_TANGENTSPACE ) + vViewPosition = - mvPosition.xyz; +#endif +}`, Qu = `#define NORMAL +uniform float opacity; +#if defined( FLAT_SHADED ) || defined( USE_BUMPMAP ) || defined( USE_NORMALMAP_TANGENTSPACE ) + varying vec3 vViewPosition; +#endif +#include +#include +#include +#include +#include +#include +#include +void main() { + vec4 diffuseColor = vec4( 0.0, 0.0, 0.0, opacity ); + #include + #include + #include + #include + gl_FragColor = vec4( packNormalToRGB( normal ), diffuseColor.a ); + #ifdef OPAQUE + gl_FragColor.a = 1.0; + #endif +}`, td = `#define PHONG +varying vec3 vViewPosition; +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +void main() { + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + vViewPosition = - mvPosition.xyz; + #include + #include + #include + #include +}`, ed = `#define PHONG +uniform vec3 diffuse; +uniform vec3 emissive; +uniform vec3 specular; +uniform float shininess; +uniform float opacity; +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +void main() { + vec4 diffuseColor = vec4( diffuse, opacity ); + #include + ReflectedLight reflectedLight = ReflectedLight( vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ) ); + vec3 totalEmissiveRadiance = emissive; + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + vec3 outgoingLight = reflectedLight.directDiffuse + reflectedLight.indirectDiffuse + reflectedLight.directSpecular + reflectedLight.indirectSpecular + totalEmissiveRadiance; + #include + #include + #include + #include + #include + #include + #include +}`, nd = `#define STANDARD +varying vec3 vViewPosition; +#ifdef USE_TRANSMISSION + varying vec3 vWorldPosition; +#endif +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +void main() { + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + vViewPosition = - mvPosition.xyz; + #include + #include + #include +#ifdef USE_TRANSMISSION + vWorldPosition = worldPosition.xyz; +#endif +}`, id = `#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 +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +void main() { + vec4 diffuseColor = vec4( diffuse, opacity ); + #include + ReflectedLight reflectedLight = ReflectedLight( vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ) ); + vec3 totalEmissiveRadiance = emissive; + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + vec3 totalDiffuse = reflectedLight.directDiffuse + reflectedLight.indirectDiffuse; + vec3 totalSpecular = reflectedLight.directSpecular + reflectedLight.indirectSpecular; + #include + 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 + #include + #include + #include + #include + #include +}`, sd = `#define TOON +varying vec3 vViewPosition; +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +void main() { + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + vViewPosition = - mvPosition.xyz; + #include + #include + #include +}`, rd = `#define TOON +uniform vec3 diffuse; +uniform vec3 emissive; +uniform float opacity; +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +void main() { + vec4 diffuseColor = vec4( diffuse, opacity ); + #include + ReflectedLight reflectedLight = ReflectedLight( vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ) ); + vec3 totalEmissiveRadiance = emissive; + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + vec3 outgoingLight = reflectedLight.directDiffuse + reflectedLight.indirectDiffuse + totalEmissiveRadiance; + #include + #include + #include + #include + #include + #include +}`, ad = `uniform float size; +uniform float scale; +#include +#include +#include +#include +#include +#include +#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 + #include + #include + #include + #include + #include + gl_PointSize = size; + #ifdef USE_SIZEATTENUATION + bool isPerspective = isPerspectiveMatrix( projectionMatrix ); + if ( isPerspective ) gl_PointSize *= ( scale / - mvPosition.z ); + #endif + #include + #include + #include + #include +}`, od = `uniform vec3 diffuse; +uniform float opacity; +#include +#include +#include +#include +#include +#include +#include +#include +void main() { + vec4 diffuseColor = vec4( diffuse, opacity ); + #include + vec3 outgoingLight = vec3( 0.0 ); + #include + #include + #include + #include + #include + outgoingLight = diffuseColor.rgb; + #include + #include + #include + #include + #include +}`, ld = `#include +#include +#include +#include +#include +#include +#include +void main() { + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include +}`, cd = `uniform vec3 color; +uniform float opacity; +#include +#include +#include +#include +#include +#include +#include +#include +void main() { + #include + gl_FragColor = vec4( color, opacity * ( 1.0 - getShadowMask() ) ); + #include + #include + #include +}`, hd = `uniform float rotation; +uniform vec2 center; +#include +#include +#include +#include +#include +void main() { + #include + 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 + #include + #include +}`, ud = `uniform vec3 diffuse; +uniform float opacity; +#include +#include +#include +#include +#include +#include +#include +#include +#include +void main() { + vec4 diffuseColor = vec4( diffuse, opacity ); + #include + vec3 outgoingLight = vec3( 0.0 ); + #include + #include + #include + #include + #include + outgoingLight = diffuseColor.rgb; + #include + #include + #include + #include +}`, Ft = { + alphahash_fragment: Uc, + alphahash_pars_fragment: Ic, + alphamap_fragment: Nc, + alphamap_pars_fragment: Fc, + alphatest_fragment: Oc, + alphatest_pars_fragment: Bc, + aomap_fragment: zc, + aomap_pars_fragment: Hc, + batching_pars_vertex: Vc, + batching_vertex: Gc, + begin_vertex: kc, + beginnormal_vertex: Wc, + bsdfs: Xc, + iridescence_fragment: Yc, + bumpmap_pars_fragment: qc, + clipping_planes_fragment: Kc, + clipping_planes_pars_fragment: jc, + clipping_planes_pars_vertex: Zc, + clipping_planes_vertex: $c, + color_fragment: Jc, + color_pars_fragment: Qc, + color_pars_vertex: th, + color_vertex: eh, + common: nh, + cube_uv_reflection_fragment: ih, + defaultnormal_vertex: sh, + displacementmap_pars_vertex: rh, + displacementmap_vertex: ah, + emissivemap_fragment: oh, + emissivemap_pars_fragment: lh, + colorspace_fragment: ch, + colorspace_pars_fragment: hh, + envmap_fragment: uh, + envmap_common_pars_fragment: dh, + envmap_pars_fragment: fh, + envmap_pars_vertex: ph, + envmap_physical_pars_fragment: bh, + envmap_vertex: mh, + fog_vertex: _h, + fog_pars_vertex: gh, + fog_fragment: vh, + fog_pars_fragment: xh, + gradientmap_pars_fragment: Mh, + lightmap_pars_fragment: Sh, + lights_lambert_fragment: Eh, + lights_lambert_pars_fragment: yh, + lights_pars_begin: Th, + lights_toon_fragment: Ah, + lights_toon_pars_fragment: Rh, + lights_phong_fragment: wh, + lights_phong_pars_fragment: Ch, + lights_physical_fragment: Ph, + lights_physical_pars_fragment: Dh, + lights_fragment_begin: Lh, + lights_fragment_maps: Uh, + lights_fragment_end: Ih, + logdepthbuf_fragment: Nh, + logdepthbuf_pars_fragment: Fh, + logdepthbuf_pars_vertex: Oh, + logdepthbuf_vertex: Bh, + map_fragment: zh, + map_pars_fragment: Hh, + map_particle_fragment: Vh, + map_particle_pars_fragment: Gh, + metalnessmap_fragment: kh, + metalnessmap_pars_fragment: Wh, + morphinstance_vertex: Xh, + morphcolor_vertex: Yh, + morphnormal_vertex: qh, + morphtarget_pars_vertex: Kh, + morphtarget_vertex: jh, + normal_fragment_begin: Zh, + normal_fragment_maps: $h, + normal_pars_fragment: Jh, + normal_pars_vertex: Qh, + normal_vertex: tu, + normalmap_pars_fragment: eu, + clearcoat_normal_fragment_begin: nu, + clearcoat_normal_fragment_maps: iu, + clearcoat_pars_fragment: su, + iridescence_pars_fragment: ru, + opaque_fragment: au, + packing: ou, + premultiplied_alpha_fragment: lu, + project_vertex: cu, + dithering_fragment: hu, + dithering_pars_fragment: uu, + roughnessmap_fragment: du, + roughnessmap_pars_fragment: fu, + shadowmap_pars_fragment: pu, + shadowmap_pars_vertex: mu, + shadowmap_vertex: _u, + shadowmask_pars_fragment: gu, + skinbase_vertex: vu, + skinning_pars_vertex: xu, + skinning_vertex: Mu, + skinnormal_vertex: Su, + specularmap_fragment: Eu, + specularmap_pars_fragment: yu, + tonemapping_fragment: Tu, + tonemapping_pars_fragment: bu, + transmission_fragment: Au, + transmission_pars_fragment: Ru, + uv_pars_fragment: wu, + uv_pars_vertex: Cu, + uv_vertex: Pu, + worldpos_vertex: Du, + background_vert: Lu, + background_frag: Uu, + backgroundCube_vert: Iu, + backgroundCube_frag: Nu, + cube_vert: Fu, + cube_frag: Ou, + depth_vert: Bu, + depth_frag: zu, + distanceRGBA_vert: Hu, + distanceRGBA_frag: Vu, + equirect_vert: Gu, + equirect_frag: ku, + linedashed_vert: Wu, + linedashed_frag: Xu, + meshbasic_vert: Yu, + meshbasic_frag: qu, + meshlambert_vert: Ku, + meshlambert_frag: ju, + meshmatcap_vert: Zu, + meshmatcap_frag: $u, + meshnormal_vert: Ju, + meshnormal_frag: Qu, + meshphong_vert: td, + meshphong_frag: ed, + meshphysical_vert: nd, + meshphysical_frag: id, + meshtoon_vert: sd, + meshtoon_frag: rd, + points_vert: ad, + points_frag: od, + shadow_vert: ld, + shadow_frag: cd, + sprite_vert: hd, + sprite_frag: ud +}, st = { + common: { + diffuse: { value: /* @__PURE__ */ new Vt(16777215) }, + opacity: { value: 1 }, + map: { value: null }, + mapTransform: { value: /* @__PURE__ */ new It() }, + alphaMap: { value: null }, + alphaMapTransform: { value: /* @__PURE__ */ new It() }, + alphaTest: { value: 0 } + }, + specularmap: { + specularMap: { value: null }, + specularMapTransform: { value: /* @__PURE__ */ new It() } + }, + envmap: { + envMap: { value: null }, + envMapRotation: { value: /* @__PURE__ */ new It() }, + 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 It() } + }, + lightmap: { + lightMap: { value: null }, + lightMapIntensity: { value: 1 }, + lightMapTransform: { value: /* @__PURE__ */ new It() } + }, + bumpmap: { + bumpMap: { value: null }, + bumpMapTransform: { value: /* @__PURE__ */ new It() }, + bumpScale: { value: 1 } + }, + normalmap: { + normalMap: { value: null }, + normalMapTransform: { value: /* @__PURE__ */ new It() }, + normalScale: { value: /* @__PURE__ */ new Ct(1, 1) } + }, + displacementmap: { + displacementMap: { value: null }, + displacementMapTransform: { value: /* @__PURE__ */ new It() }, + displacementScale: { value: 1 }, + displacementBias: { value: 0 } + }, + emissivemap: { + emissiveMap: { value: null }, + emissiveMapTransform: { value: /* @__PURE__ */ new It() } + }, + metalnessmap: { + metalnessMap: { value: null }, + metalnessMapTransform: { value: /* @__PURE__ */ new It() } + }, + roughnessmap: { + roughnessMap: { value: null }, + roughnessMapTransform: { value: /* @__PURE__ */ new It() } + }, + gradientmap: { + gradientMap: { value: null } + }, + fog: { + fogDensity: { value: 25e-5 }, + fogNear: { value: 1 }, + fogFar: { value: 2e3 }, + fogColor: { value: /* @__PURE__ */ new Vt(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 Vt(16777215) }, + opacity: { value: 1 }, + size: { value: 1 }, + scale: { value: 1 }, + map: { value: null }, + alphaMap: { value: null }, + alphaMapTransform: { value: /* @__PURE__ */ new It() }, + alphaTest: { value: 0 }, + uvTransform: { value: /* @__PURE__ */ new It() } + }, + sprite: { + diffuse: { value: /* @__PURE__ */ new Vt(16777215) }, + opacity: { value: 1 }, + center: { value: /* @__PURE__ */ new Ct(0.5, 0.5) }, + rotation: { value: 0 }, + map: { value: null }, + mapTransform: { value: /* @__PURE__ */ new It() }, + alphaMap: { value: null }, + alphaMapTransform: { value: /* @__PURE__ */ new It() }, + alphaTest: { value: 0 } + } +}, We = { + basic: { + uniforms: /* @__PURE__ */ xe([ + st.common, + st.specularmap, + st.envmap, + st.aomap, + st.lightmap, + st.fog + ]), + vertexShader: Ft.meshbasic_vert, + fragmentShader: Ft.meshbasic_frag + }, + lambert: { + uniforms: /* @__PURE__ */ xe([ + st.common, + st.specularmap, + st.envmap, + st.aomap, + st.lightmap, + st.emissivemap, + st.bumpmap, + st.normalmap, + st.displacementmap, + st.fog, + st.lights, + { + emissive: { value: /* @__PURE__ */ new Vt(0) } + } + ]), + vertexShader: Ft.meshlambert_vert, + fragmentShader: Ft.meshlambert_frag + }, + phong: { + uniforms: /* @__PURE__ */ xe([ + st.common, + st.specularmap, + st.envmap, + st.aomap, + st.lightmap, + st.emissivemap, + st.bumpmap, + st.normalmap, + st.displacementmap, + st.fog, + st.lights, + { + emissive: { value: /* @__PURE__ */ new Vt(0) }, + specular: { value: /* @__PURE__ */ new Vt(1118481) }, + shininess: { value: 30 } + } + ]), + vertexShader: Ft.meshphong_vert, + fragmentShader: Ft.meshphong_frag + }, + standard: { + uniforms: /* @__PURE__ */ xe([ + st.common, + st.envmap, + st.aomap, + st.lightmap, + st.emissivemap, + st.bumpmap, + st.normalmap, + st.displacementmap, + st.roughnessmap, + st.metalnessmap, + st.fog, + st.lights, + { + emissive: { value: /* @__PURE__ */ new Vt(0) }, + roughness: { value: 1 }, + metalness: { value: 0 }, + envMapIntensity: { value: 1 } + } + ]), + vertexShader: Ft.meshphysical_vert, + fragmentShader: Ft.meshphysical_frag + }, + toon: { + uniforms: /* @__PURE__ */ xe([ + st.common, + st.aomap, + st.lightmap, + st.emissivemap, + st.bumpmap, + st.normalmap, + st.displacementmap, + st.gradientmap, + st.fog, + st.lights, + { + emissive: { value: /* @__PURE__ */ new Vt(0) } + } + ]), + vertexShader: Ft.meshtoon_vert, + fragmentShader: Ft.meshtoon_frag + }, + matcap: { + uniforms: /* @__PURE__ */ xe([ + st.common, + st.bumpmap, + st.normalmap, + st.displacementmap, + st.fog, + { + matcap: { value: null } + } + ]), + vertexShader: Ft.meshmatcap_vert, + fragmentShader: Ft.meshmatcap_frag + }, + points: { + uniforms: /* @__PURE__ */ xe([ + st.points, + st.fog + ]), + vertexShader: Ft.points_vert, + fragmentShader: Ft.points_frag + }, + dashed: { + uniforms: /* @__PURE__ */ xe([ + st.common, + st.fog, + { + scale: { value: 1 }, + dashSize: { value: 1 }, + totalSize: { value: 2 } + } + ]), + vertexShader: Ft.linedashed_vert, + fragmentShader: Ft.linedashed_frag + }, + depth: { + uniforms: /* @__PURE__ */ xe([ + st.common, + st.displacementmap + ]), + vertexShader: Ft.depth_vert, + fragmentShader: Ft.depth_frag + }, + normal: { + uniforms: /* @__PURE__ */ xe([ + st.common, + st.bumpmap, + st.normalmap, + st.displacementmap, + { + opacity: { value: 1 } + } + ]), + vertexShader: Ft.meshnormal_vert, + fragmentShader: Ft.meshnormal_frag + }, + sprite: { + uniforms: /* @__PURE__ */ xe([ + st.sprite, + st.fog + ]), + vertexShader: Ft.sprite_vert, + fragmentShader: Ft.sprite_frag + }, + background: { + uniforms: { + uvTransform: { value: /* @__PURE__ */ new It() }, + t2D: { value: null }, + backgroundIntensity: { value: 1 } + }, + vertexShader: Ft.background_vert, + fragmentShader: Ft.background_frag + }, + backgroundCube: { + uniforms: { + envMap: { value: null }, + flipEnvMap: { value: -1 }, + backgroundBlurriness: { value: 0 }, + backgroundIntensity: { value: 1 }, + backgroundRotation: { value: /* @__PURE__ */ new It() } + }, + vertexShader: Ft.backgroundCube_vert, + fragmentShader: Ft.backgroundCube_frag + }, + cube: { + uniforms: { + tCube: { value: null }, + tFlip: { value: -1 }, + opacity: { value: 1 } + }, + vertexShader: Ft.cube_vert, + fragmentShader: Ft.cube_frag + }, + equirect: { + uniforms: { + tEquirect: { value: null } + }, + vertexShader: Ft.equirect_vert, + fragmentShader: Ft.equirect_frag + }, + distanceRGBA: { + uniforms: /* @__PURE__ */ xe([ + st.common, + st.displacementmap, + { + referencePosition: { value: /* @__PURE__ */ new N() }, + nearDistance: { value: 1 }, + farDistance: { value: 1e3 } + } + ]), + vertexShader: Ft.distanceRGBA_vert, + fragmentShader: Ft.distanceRGBA_frag + }, + shadow: { + uniforms: /* @__PURE__ */ xe([ + st.lights, + st.fog, + { + color: { value: /* @__PURE__ */ new Vt(0) }, + opacity: { value: 1 } + } + ]), + vertexShader: Ft.shadow_vert, + fragmentShader: Ft.shadow_frag + } +}; +We.physical = { + uniforms: /* @__PURE__ */ xe([ + We.standard.uniforms, + { + clearcoat: { value: 0 }, + clearcoatMap: { value: null }, + clearcoatMapTransform: { value: /* @__PURE__ */ new It() }, + clearcoatNormalMap: { value: null }, + clearcoatNormalMapTransform: { value: /* @__PURE__ */ new It() }, + clearcoatNormalScale: { value: /* @__PURE__ */ new Ct(1, 1) }, + clearcoatRoughness: { value: 0 }, + clearcoatRoughnessMap: { value: null }, + clearcoatRoughnessMapTransform: { value: /* @__PURE__ */ new It() }, + dispersion: { value: 0 }, + iridescence: { value: 0 }, + iridescenceMap: { value: null }, + iridescenceMapTransform: { value: /* @__PURE__ */ new It() }, + iridescenceIOR: { value: 1.3 }, + iridescenceThicknessMinimum: { value: 100 }, + iridescenceThicknessMaximum: { value: 400 }, + iridescenceThicknessMap: { value: null }, + iridescenceThicknessMapTransform: { value: /* @__PURE__ */ new It() }, + sheen: { value: 0 }, + sheenColor: { value: /* @__PURE__ */ new Vt(0) }, + sheenColorMap: { value: null }, + sheenColorMapTransform: { value: /* @__PURE__ */ new It() }, + sheenRoughness: { value: 1 }, + sheenRoughnessMap: { value: null }, + sheenRoughnessMapTransform: { value: /* @__PURE__ */ new It() }, + transmission: { value: 0 }, + transmissionMap: { value: null }, + transmissionMapTransform: { value: /* @__PURE__ */ new It() }, + transmissionSamplerSize: { value: /* @__PURE__ */ new Ct() }, + transmissionSamplerMap: { value: null }, + thickness: { value: 0 }, + thicknessMap: { value: null }, + thicknessMapTransform: { value: /* @__PURE__ */ new It() }, + attenuationDistance: { value: 0 }, + attenuationColor: { value: /* @__PURE__ */ new Vt(0) }, + specularColor: { value: /* @__PURE__ */ new Vt(1, 1, 1) }, + specularColorMap: { value: null }, + specularColorMapTransform: { value: /* @__PURE__ */ new It() }, + specularIntensity: { value: 1 }, + specularIntensityMap: { value: null }, + specularIntensityMapTransform: { value: /* @__PURE__ */ new It() }, + anisotropyVector: { value: /* @__PURE__ */ new Ct() }, + anisotropyMap: { value: null }, + anisotropyMapTransform: { value: /* @__PURE__ */ new It() } + } + ]), + vertexShader: Ft.meshphysical_vert, + fragmentShader: Ft.meshphysical_frag +}; +const Ki = { r: 0, b: 0, g: 0 }, An = /* @__PURE__ */ new je(), dd = /* @__PURE__ */ new ae(); +function fd(i, t, e, n, s, r, a) { + const o = new Vt(0); + let c = r === !0 ? 0 : 1, l, u, d = null, f = 0, m = null; + function v(b) { + let y = b.isScene === !0 ? b.background : null; + return y && y.isTexture && (y = (b.backgroundBlurriness > 0 ? e : t).get(y)), y; + } + function x(b) { + let y = !1; + const D = v(b); + D === null ? h(o, c) : D && D.isColor && (h(D, 1), y = !0); + const P = i.xr.getEnvironmentBlendMode(); + P === "additive" ? n.buffers.color.setClear(0, 0, 0, 1, a) : P === "alpha-blend" && n.buffers.color.setClear(0, 0, 0, 0, a), (i.autoClear || y) && (n.buffers.depth.setTest(!0), n.buffers.depth.setMask(!0), n.buffers.color.setMask(!0), i.clear(i.autoClearColor, i.autoClearDepth, i.autoClearStencil)); + } + function p(b, y) { + const D = v(y); + D && (D.isCubeTexture || D.mapping === ls) ? (u === void 0 && (u = new be( + new Ai(1, 1, 1), + new xn({ + name: "BackgroundCubeMaterial", + uniforms: li(We.backgroundCube.uniforms), + vertexShader: We.backgroundCube.vertexShader, + fragmentShader: We.backgroundCube.fragmentShader, + side: Ae, + depthTest: !1, + depthWrite: !1, + fog: !1, + allowOverride: !1 + }) + ), u.geometry.deleteAttribute("normal"), u.geometry.deleteAttribute("uv"), u.onBeforeRender = function(P, w, F) { + this.matrixWorld.copyPosition(F.matrixWorld); + }, Object.defineProperty(u.material, "envMap", { + get: function() { + return this.uniforms.envMap.value; + } + }), s.update(u)), An.copy(y.backgroundRotation), An.x *= -1, An.y *= -1, An.z *= -1, D.isCubeTexture && D.isRenderTargetTexture === !1 && (An.y *= -1, An.z *= -1), u.material.uniforms.envMap.value = D, u.material.uniforms.flipEnvMap.value = D.isCubeTexture && D.isRenderTargetTexture === !1 ? -1 : 1, u.material.uniforms.backgroundBlurriness.value = y.backgroundBlurriness, u.material.uniforms.backgroundIntensity.value = y.backgroundIntensity, u.material.uniforms.backgroundRotation.value.setFromMatrix4(dd.makeRotationFromEuler(An)), u.material.toneMapped = kt.getTransfer(D.colorSpace) !== qt, (d !== D || f !== D.version || m !== i.toneMapping) && (u.material.needsUpdate = !0, d = D, f = D.version, m = i.toneMapping), u.layers.enableAll(), b.unshift(u, u.geometry, u.material, 0, 0, null)) : D && D.isTexture && (l === void 0 && (l = new be( + new cs(2, 2), + new xn({ + name: "BackgroundMaterial", + uniforms: li(We.background.uniforms), + vertexShader: We.background.vertexShader, + fragmentShader: We.background.fragmentShader, + side: vn, + depthTest: !1, + depthWrite: !1, + fog: !1, + allowOverride: !1 + }) + ), l.geometry.deleteAttribute("normal"), Object.defineProperty(l.material, "map", { + get: function() { + return this.uniforms.t2D.value; + } + }), s.update(l)), l.material.uniforms.t2D.value = D, l.material.uniforms.backgroundIntensity.value = y.backgroundIntensity, l.material.toneMapped = kt.getTransfer(D.colorSpace) !== qt, D.matrixAutoUpdate === !0 && D.updateMatrix(), l.material.uniforms.uvTransform.value.copy(D.matrix), (d !== D || f !== D.version || m !== i.toneMapping) && (l.material.needsUpdate = !0, d = D, f = D.version, m = i.toneMapping), l.layers.enableAll(), b.unshift(l, l.geometry, l.material, 0, 0, null)); + } + function h(b, y) { + b.getRGB(Ki, Po(i)), n.buffers.color.setClear(Ki.r, Ki.g, Ki.b, y, a); + } + function A() { + u !== void 0 && (u.geometry.dispose(), u.material.dispose(), u = void 0), l !== void 0 && (l.geometry.dispose(), l.material.dispose(), l = void 0); + } + return { + getClearColor: function() { + return o; + }, + setClearColor: function(b, y = 1) { + o.set(b), c = y, h(o, c); + }, + getClearAlpha: function() { + return c; + }, + setClearAlpha: function(b) { + c = b, h(o, c); + }, + render: x, + addToRenderList: p, + dispose: A + }; +} +function pd(i, t) { + const e = i.getParameter(i.MAX_VERTEX_ATTRIBS), n = {}, s = f(null); + let r = s, a = !1; + function o(M, C, z, G, K) { + let W = !1; + const Y = d(G, z, C); + r !== Y && (r = Y, l(r.object)), W = m(M, G, z, K), W && v(M, G, z, K), K !== null && t.update(K, i.ELEMENT_ARRAY_BUFFER), (W || a) && (a = !1, y(M, C, z, G), K !== null && i.bindBuffer(i.ELEMENT_ARRAY_BUFFER, t.get(K).buffer)); + } + function c() { + return i.createVertexArray(); + } + function l(M) { + return i.bindVertexArray(M); + } + function u(M) { + return i.deleteVertexArray(M); + } + function d(M, C, z) { + const G = z.wireframe === !0; + let K = n[M.id]; + K === void 0 && (K = {}, n[M.id] = K); + let W = K[C.id]; + W === void 0 && (W = {}, K[C.id] = W); + let Y = W[G]; + return Y === void 0 && (Y = f(c()), W[G] = Y), Y; + } + function f(M) { + const C = [], z = [], G = []; + for (let K = 0; K < e; K++) + C[K] = 0, z[K] = 0, G[K] = 0; + return { + // for backward compatibility on non-VAO support browser + geometry: null, + program: null, + wireframe: !1, + newAttributes: C, + enabledAttributes: z, + attributeDivisors: G, + object: M, + attributes: {}, + index: null + }; + } + function m(M, C, z, G) { + const K = r.attributes, W = C.attributes; + let Y = 0; + const Z = z.getAttributes(); + for (const H in Z) + if (Z[H].location >= 0) { + const ct = K[H]; + let Et = W[H]; + if (Et === void 0 && (H === "instanceMatrix" && M.instanceMatrix && (Et = M.instanceMatrix), H === "instanceColor" && M.instanceColor && (Et = M.instanceColor)), ct === void 0 || ct.attribute !== Et || Et && ct.data !== Et.data) return !0; + Y++; + } + return r.attributesNum !== Y || r.index !== G; + } + function v(M, C, z, G) { + const K = {}, W = C.attributes; + let Y = 0; + const Z = z.getAttributes(); + for (const H in Z) + if (Z[H].location >= 0) { + let ct = W[H]; + ct === void 0 && (H === "instanceMatrix" && M.instanceMatrix && (ct = M.instanceMatrix), H === "instanceColor" && M.instanceColor && (ct = M.instanceColor)); + const Et = {}; + Et.attribute = ct, ct && ct.data && (Et.data = ct.data), K[H] = Et, Y++; + } + r.attributes = K, r.attributesNum = Y, r.index = G; + } + function x() { + const M = r.newAttributes; + for (let C = 0, z = M.length; C < z; C++) + M[C] = 0; + } + function p(M) { + h(M, 0); + } + function h(M, C) { + const z = r.newAttributes, G = r.enabledAttributes, K = r.attributeDivisors; + z[M] = 1, G[M] === 0 && (i.enableVertexAttribArray(M), G[M] = 1), K[M] !== C && (i.vertexAttribDivisor(M, C), K[M] = C); + } + function A() { + const M = r.newAttributes, C = r.enabledAttributes; + for (let z = 0, G = C.length; z < G; z++) + C[z] !== M[z] && (i.disableVertexAttribArray(z), C[z] = 0); + } + function b(M, C, z, G, K, W, Y) { + Y === !0 ? i.vertexAttribIPointer(M, C, z, K, W) : i.vertexAttribPointer(M, C, z, G, K, W); + } + function y(M, C, z, G) { + x(); + const K = G.attributes, W = z.getAttributes(), Y = C.defaultAttributeValues; + for (const Z in W) { + const H = W[Z]; + if (H.location >= 0) { + let rt = K[Z]; + if (rt === void 0 && (Z === "instanceMatrix" && M.instanceMatrix && (rt = M.instanceMatrix), Z === "instanceColor" && M.instanceColor && (rt = M.instanceColor)), rt !== void 0) { + const ct = rt.normalized, Et = rt.itemSize, Ot = t.get(rt); + if (Ot === void 0) continue; + const Zt = Ot.buffer, Qt = Ot.type, Wt = Ot.bytesPerElement, X = Qt === i.INT || Qt === i.UNSIGNED_INT || rt.gpuType === Hr; + if (rt.isInterleavedBufferAttribute) { + const $ = rt.data, dt = $.stride, Pt = rt.offset; + if ($.isInstancedInterleavedBuffer) { + for (let St = 0; St < H.locationSize; St++) + h(H.location + St, $.meshPerAttribute); + M.isInstancedMesh !== !0 && G._maxInstanceCount === void 0 && (G._maxInstanceCount = $.meshPerAttribute * $.count); + } else + for (let St = 0; St < H.locationSize; St++) + p(H.location + St); + i.bindBuffer(i.ARRAY_BUFFER, Zt); + for (let St = 0; St < H.locationSize; St++) + b( + H.location + St, + Et / H.locationSize, + Qt, + ct, + dt * Wt, + (Pt + Et / H.locationSize * St) * Wt, + X + ); + } else { + if (rt.isInstancedBufferAttribute) { + for (let $ = 0; $ < H.locationSize; $++) + h(H.location + $, rt.meshPerAttribute); + M.isInstancedMesh !== !0 && G._maxInstanceCount === void 0 && (G._maxInstanceCount = rt.meshPerAttribute * rt.count); + } else + for (let $ = 0; $ < H.locationSize; $++) + p(H.location + $); + i.bindBuffer(i.ARRAY_BUFFER, Zt); + for (let $ = 0; $ < H.locationSize; $++) + b( + H.location + $, + Et / H.locationSize, + Qt, + ct, + Et * Wt, + Et / H.locationSize * $ * Wt, + X + ); + } + } else if (Y !== void 0) { + const ct = Y[Z]; + if (ct !== void 0) + switch (ct.length) { + case 2: + i.vertexAttrib2fv(H.location, ct); + break; + case 3: + i.vertexAttrib3fv(H.location, ct); + break; + case 4: + i.vertexAttrib4fv(H.location, ct); + break; + default: + i.vertexAttrib1fv(H.location, ct); + } + } + } + } + A(); + } + function D() { + F(); + for (const M in n) { + const C = n[M]; + for (const z in C) { + const G = C[z]; + for (const K in G) + u(G[K].object), delete G[K]; + delete C[z]; + } + delete n[M]; + } + } + function P(M) { + if (n[M.id] === void 0) return; + const C = n[M.id]; + for (const z in C) { + const G = C[z]; + for (const K in G) + u(G[K].object), delete G[K]; + delete C[z]; + } + delete n[M.id]; + } + function w(M) { + for (const C in n) { + const z = n[C]; + if (z[M.id] === void 0) continue; + const G = z[M.id]; + for (const K in G) + u(G[K].object), delete G[K]; + delete z[M.id]; + } + } + function F() { + S(), a = !0, r !== s && (r = s, l(r.object)); + } + function S() { + s.geometry = null, s.program = null, s.wireframe = !1; + } + return { + setup: o, + reset: F, + resetDefaultState: S, + dispose: D, + releaseStatesOfGeometry: P, + releaseStatesOfProgram: w, + initAttributes: x, + enableAttribute: p, + disableUnusedAttributes: A + }; +} +function md(i, t, e) { + let n; + function s(l) { + n = l; + } + function r(l, u) { + i.drawArrays(n, l, u), e.update(u, n, 1); + } + function a(l, u, d) { + d !== 0 && (i.drawArraysInstanced(n, l, u, d), e.update(u, n, d)); + } + function o(l, u, d) { + if (d === 0) return; + t.get("WEBGL_multi_draw").multiDrawArraysWEBGL(n, l, 0, u, 0, d); + let m = 0; + for (let v = 0; v < d; v++) + m += u[v]; + e.update(m, n, 1); + } + function c(l, u, d, f) { + if (d === 0) return; + const m = t.get("WEBGL_multi_draw"); + if (m === null) + for (let v = 0; v < l.length; v++) + a(l[v], u[v], f[v]); + else { + m.multiDrawArraysInstancedWEBGL(n, l, 0, u, 0, f, 0, d); + let v = 0; + for (let x = 0; x < d; x++) + v += u[x] * f[x]; + e.update(v, n, 1); + } + } + this.setMode = s, this.render = r, this.renderInstances = a, this.renderMultiDraw = o, this.renderMultiDrawInstances = c; +} +function _d(i, t, e, n) { + let s; + function r() { + if (s !== void 0) return s; + if (t.has("EXT_texture_filter_anisotropic") === !0) { + const w = t.get("EXT_texture_filter_anisotropic"); + s = i.getParameter(w.MAX_TEXTURE_MAX_ANISOTROPY_EXT); + } else + s = 0; + return s; + } + function a(w) { + return !(w !== Ve && n.convert(w) !== i.getParameter(i.IMPLEMENTATION_COLOR_READ_FORMAT)); + } + function o(w) { + const F = w === Ei && (t.has("EXT_color_buffer_half_float") || t.has("EXT_color_buffer_float")); + return !(w !== Ke && n.convert(w) !== i.getParameter(i.IMPLEMENTATION_COLOR_READ_TYPE) && // Edge and Chrome Mac < 52 (#9513) + w !== sn && !F); + } + function c(w) { + if (w === "highp") { + if (i.getShaderPrecisionFormat(i.VERTEX_SHADER, i.HIGH_FLOAT).precision > 0 && i.getShaderPrecisionFormat(i.FRAGMENT_SHADER, i.HIGH_FLOAT).precision > 0) + return "highp"; + w = "mediump"; + } + return w === "mediump" && i.getShaderPrecisionFormat(i.VERTEX_SHADER, i.MEDIUM_FLOAT).precision > 0 && i.getShaderPrecisionFormat(i.FRAGMENT_SHADER, i.MEDIUM_FLOAT).precision > 0 ? "mediump" : "lowp"; + } + let l = e.precision !== void 0 ? e.precision : "highp"; + const u = c(l); + u !== l && (console.warn("THREE.WebGLRenderer:", l, "not supported, using", u, "instead."), l = u); + const d = e.logarithmicDepthBuffer === !0, f = e.reversedDepthBuffer === !0 && t.has("EXT_clip_control"), m = i.getParameter(i.MAX_TEXTURE_IMAGE_UNITS), v = i.getParameter(i.MAX_VERTEX_TEXTURE_IMAGE_UNITS), x = i.getParameter(i.MAX_TEXTURE_SIZE), p = i.getParameter(i.MAX_CUBE_MAP_TEXTURE_SIZE), h = i.getParameter(i.MAX_VERTEX_ATTRIBS), A = i.getParameter(i.MAX_VERTEX_UNIFORM_VECTORS), b = i.getParameter(i.MAX_VARYING_VECTORS), y = i.getParameter(i.MAX_FRAGMENT_UNIFORM_VECTORS), D = v > 0, P = i.getParameter(i.MAX_SAMPLES); + return { + isWebGL2: !0, + // keeping this for backwards compatibility + getMaxAnisotropy: r, + getMaxPrecision: c, + textureFormatReadable: a, + textureTypeReadable: o, + precision: l, + logarithmicDepthBuffer: d, + reversedDepthBuffer: f, + maxTextures: m, + maxVertexTextures: v, + maxTextureSize: x, + maxCubemapSize: p, + maxAttributes: h, + maxVertexUniforms: A, + maxVaryings: b, + maxFragmentUniforms: y, + vertexTextures: D, + maxSamples: P + }; +} +function gd(i) { + const t = this; + let e = null, n = 0, s = !1, r = !1; + const a = new pn(), o = new It(), c = { value: null, needsUpdate: !1 }; + this.uniform = c, this.numPlanes = 0, this.numIntersection = 0, this.init = function(d, f) { + const m = d.length !== 0 || f || // enable state of previous frame - the clipping code has to + // run another frame in order to reset the state: + n !== 0 || s; + return s = f, n = d.length, m; + }, this.beginShadows = function() { + r = !0, u(null); + }, this.endShadows = function() { + r = !1; + }, this.setGlobalState = function(d, f) { + e = u(d, f, 0); + }, this.setState = function(d, f, m) { + const v = d.clippingPlanes, x = d.clipIntersection, p = d.clipShadows, h = i.get(d); + if (!s || v === null || v.length === 0 || r && !p) + r ? u(null) : l(); + else { + const A = r ? 0 : n, b = A * 4; + let y = h.clippingState || null; + c.value = y, y = u(v, f, b, m); + for (let D = 0; D !== b; ++D) + y[D] = e[D]; + h.clippingState = y, this.numIntersection = x ? this.numPlanes : 0, this.numPlanes += A; + } + }; + function l() { + c.value !== e && (c.value = e, c.needsUpdate = n > 0), t.numPlanes = n, t.numIntersection = 0; + } + function u(d, f, m, v) { + const x = d !== null ? d.length : 0; + let p = null; + if (x !== 0) { + if (p = c.value, v !== !0 || p === null) { + const h = m + x * 4, A = f.matrixWorldInverse; + o.getNormalMatrix(A), (p === null || p.length < h) && (p = new Float32Array(h)); + for (let b = 0, y = m; b !== x; ++b, y += 4) + a.copy(d[b]).applyMatrix4(A, o), a.normal.toArray(p, y), p[y + 3] = a.constant; + } + c.value = p, c.needsUpdate = !0; + } + return t.numPlanes = x, t.numIntersection = 0, p; + } +} +function vd(i) { + let t = /* @__PURE__ */ new WeakMap(); + function e(a, o) { + return o === ir ? a.mapping = ri : o === sr && (a.mapping = ai), a; + } + function n(a) { + if (a && a.isTexture) { + const o = a.mapping; + if (o === ir || o === sr) + if (t.has(a)) { + const c = t.get(a).texture; + return e(c, a.mapping); + } else { + const c = a.image; + if (c && c.height > 0) { + const l = new mc(c.height); + return l.fromEquirectangularTexture(i, a), t.set(a, l), a.addEventListener("dispose", s), e(l.texture, a.mapping); + } else + return null; + } + } + return a; + } + function s(a) { + const o = a.target; + o.removeEventListener("dispose", s); + const c = t.get(o); + c !== void 0 && (t.delete(o), c.dispose()); + } + function r() { + t = /* @__PURE__ */ new WeakMap(); + } + return { + get: n, + dispose: r + }; +} +const ti = 4, Oa = [0.125, 0.215, 0.35, 0.446, 0.526, 0.582], Pn = 20, zs = /* @__PURE__ */ new Fo(), Ba = /* @__PURE__ */ new Vt(); +let Hs = null, Vs = 0, Gs = 0, ks = !1; +const wn = (1 + Math.sqrt(5)) / 2, $n = 1 / wn, za = [ + /* @__PURE__ */ new N(-wn, $n, 0), + /* @__PURE__ */ new N(wn, $n, 0), + /* @__PURE__ */ new N(-$n, 0, wn), + /* @__PURE__ */ new N($n, 0, wn), + /* @__PURE__ */ new N(0, wn, -$n), + /* @__PURE__ */ new N(0, wn, $n), + /* @__PURE__ */ new N(-1, 1, -1), + /* @__PURE__ */ new N(1, 1, -1), + /* @__PURE__ */ new N(-1, 1, 1), + /* @__PURE__ */ new N(1, 1, 1) +], xd = /* @__PURE__ */ new N(); +class Ha { + /** + * Constructs a new PMREM generator. + * + * @param {WebGLRenderer} renderer - The renderer. + */ + constructor(t) { + this._renderer = t, 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(t, e = 0, n = 0.1, s = 100, r = {}) { + const { + size: a = 256, + position: o = xd + } = r; + Hs = this._renderer.getRenderTarget(), Vs = this._renderer.getActiveCubeFace(), Gs = this._renderer.getActiveMipmapLevel(), ks = this._renderer.xr.enabled, this._renderer.xr.enabled = !1, this._setSize(a); + const c = this._allocateTargets(); + return c.depthBuffer = !0, this._sceneToCubeUV(t, n, s, c, o), e > 0 && this._blur(c, 0, 0, e), this._applyPMREM(c), this._cleanup(c), c; + } + /** + * 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(t, e = null) { + return this._fromTexture(t, e); + } + /** + * 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(t, e = null) { + return this._fromTexture(t, e); + } + /** + * 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 = ka(), 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 = Ga(), 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(t) { + this._lodMax = Math.floor(Math.log2(t)), this._cubeSize = Math.pow(2, this._lodMax); + } + _dispose() { + this._blurMaterial !== null && this._blurMaterial.dispose(), this._pingPongRenderTarget !== null && this._pingPongRenderTarget.dispose(); + for (let t = 0; t < this._lodPlanes.length; t++) + this._lodPlanes[t].dispose(); + } + _cleanup(t) { + this._renderer.setRenderTarget(Hs, Vs, Gs), this._renderer.xr.enabled = ks, t.scissorTest = !1, ji(t, 0, 0, t.width, t.height); + } + _fromTexture(t, e) { + t.mapping === ri || t.mapping === ai ? this._setSize(t.image.length === 0 ? 16 : t.image[0].width || t.image[0].image.width) : this._setSize(t.image.width / 4), Hs = this._renderer.getRenderTarget(), Vs = this._renderer.getActiveCubeFace(), Gs = this._renderer.getActiveMipmapLevel(), ks = this._renderer.xr.enabled, this._renderer.xr.enabled = !1; + const n = e || this._allocateTargets(); + return this._textureToCubeUV(t, n), this._applyPMREM(n), this._cleanup(n), n; + } + _allocateTargets() { + const t = 3 * Math.max(this._cubeSize, 112), e = 4 * this._cubeSize, n = { + magFilter: Xe, + minFilter: Xe, + generateMipmaps: !1, + type: Ei, + format: Ve, + colorSpace: oi, + depthBuffer: !1 + }, s = Va(t, e, n); + if (this._pingPongRenderTarget === null || this._pingPongRenderTarget.width !== t || this._pingPongRenderTarget.height !== e) { + this._pingPongRenderTarget !== null && this._dispose(), this._pingPongRenderTarget = Va(t, e, n); + const { _lodMax: r } = this; + ({ sizeLods: this._sizeLods, lodPlanes: this._lodPlanes, sigmas: this._sigmas } = Md(r)), this._blurMaterial = Sd(r, t, e); + } + return s; + } + _compileMaterial(t) { + const e = new be(this._lodPlanes[0], t); + this._renderer.compile(e, zs); + } + _sceneToCubeUV(t, e, n, s, r) { + const c = new Ne(90, 1, e, n), l = [1, -1, 1, 1, 1, 1], u = [1, 1, 1, -1, -1, -1], d = this._renderer, f = d.autoClear, m = d.toneMapping; + d.getClearColor(Ba), d.toneMapping = gn, d.autoClear = !1, d.state.buffers.depth.getReversed() && (d.setRenderTarget(s), d.clearDepth(), d.setRenderTarget(null)); + const x = new Zr({ + name: "PMREM.Background", + side: Ae, + depthWrite: !1, + depthTest: !1 + }), p = new be(new Ai(), x); + let h = !1; + const A = t.background; + A ? A.isColor && (x.color.copy(A), t.background = null, h = !0) : (x.color.copy(Ba), h = !0); + for (let b = 0; b < 6; b++) { + const y = b % 3; + y === 0 ? (c.up.set(0, l[b], 0), c.position.set(r.x, r.y, r.z), c.lookAt(r.x + u[b], r.y, r.z)) : y === 1 ? (c.up.set(0, 0, l[b]), c.position.set(r.x, r.y, r.z), c.lookAt(r.x, r.y + u[b], r.z)) : (c.up.set(0, l[b], 0), c.position.set(r.x, r.y, r.z), c.lookAt(r.x, r.y, r.z + u[b])); + const D = this._cubeSize; + ji(s, y * D, b > 2 ? D : 0, D, D), d.setRenderTarget(s), h && d.render(p, c), d.render(t, c); + } + p.geometry.dispose(), p.material.dispose(), d.toneMapping = m, d.autoClear = f, t.background = A; + } + _textureToCubeUV(t, e) { + const n = this._renderer, s = t.mapping === ri || t.mapping === ai; + s ? (this._cubemapMaterial === null && (this._cubemapMaterial = ka()), this._cubemapMaterial.uniforms.flipEnvMap.value = t.isRenderTargetTexture === !1 ? -1 : 1) : this._equirectMaterial === null && (this._equirectMaterial = Ga()); + const r = s ? this._cubemapMaterial : this._equirectMaterial, a = new be(this._lodPlanes[0], r), o = r.uniforms; + o.envMap.value = t; + const c = this._cubeSize; + ji(e, 0, 0, 3 * c, 2 * c), n.setRenderTarget(e), n.render(a, zs); + } + _applyPMREM(t) { + const e = this._renderer, n = e.autoClear; + e.autoClear = !1; + const s = this._lodPlanes.length; + for (let r = 1; r < s; r++) { + const a = Math.sqrt(this._sigmas[r] * this._sigmas[r] - this._sigmas[r - 1] * this._sigmas[r - 1]), o = za[(s - r - 1) % za.length]; + this._blur(t, r - 1, r, a, o); + } + e.autoClear = n; + } + /** + * 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(t, e, n, s, r) { + const a = this._pingPongRenderTarget; + this._halfBlur( + t, + a, + e, + n, + s, + "latitudinal", + r + ), this._halfBlur( + a, + t, + n, + n, + s, + "longitudinal", + r + ); + } + _halfBlur(t, e, n, s, r, a, o) { + const c = this._renderer, l = this._blurMaterial; + a !== "latitudinal" && a !== "longitudinal" && console.error( + "blur direction must be either latitudinal or longitudinal!" + ); + const u = 3, d = new be(this._lodPlanes[s], l), f = l.uniforms, m = this._sizeLods[n] - 1, v = isFinite(r) ? Math.PI / (2 * m) : 2 * Math.PI / (2 * Pn - 1), x = r / v, p = isFinite(r) ? 1 + Math.floor(u * x) : Pn; + p > Pn && console.warn(`sigmaRadians, ${r}, is too large and will clip, as it requested ${p} samples when the maximum is set to ${Pn}`); + const h = []; + let A = 0; + for (let w = 0; w < Pn; ++w) { + const F = w / x, S = Math.exp(-F * F / 2); + h.push(S), w === 0 ? A += S : w < p && (A += 2 * S); + } + for (let w = 0; w < h.length; w++) + h[w] = h[w] / A; + f.envMap.value = t.texture, f.samples.value = p, f.weights.value = h, f.latitudinal.value = a === "latitudinal", o && (f.poleAxis.value = o); + const { _lodMax: b } = this; + f.dTheta.value = v, f.mipInt.value = b - n; + const y = this._sizeLods[s], D = 3 * y * (s > b - ti ? s - b + ti : 0), P = 4 * (this._cubeSize - y); + ji(e, D, P, 3 * y, 2 * y), c.setRenderTarget(e), c.render(d, zs); + } +} +function Md(i) { + const t = [], e = [], n = []; + let s = i; + const r = i - ti + 1 + Oa.length; + for (let a = 0; a < r; a++) { + const o = Math.pow(2, s); + e.push(o); + let c = 1 / o; + a > i - ti ? c = Oa[a - i + ti - 1] : a === 0 && (c = 0), n.push(c); + const l = 1 / (o - 2), u = -l, d = 1 + l, f = [u, u, d, u, d, d, u, u, d, d, u, d], m = 6, v = 6, x = 3, p = 2, h = 1, A = new Float32Array(x * v * m), b = new Float32Array(p * v * m), y = new Float32Array(h * v * m); + for (let P = 0; P < m; P++) { + const w = P % 3 * 2 / 3 - 1, F = P > 2 ? 0 : -1, S = [ + w, + F, + 0, + w + 2 / 3, + F, + 0, + w + 2 / 3, + F + 1, + 0, + w, + F, + 0, + w + 2 / 3, + F + 1, + 0, + w, + F + 1, + 0 + ]; + A.set(S, x * v * P), b.set(f, p * v * P); + const M = [P, P, P, P, P, P]; + y.set(M, h * v * P); + } + const D = new an(); + D.setAttribute("position", new Fe(A, x)), D.setAttribute("uv", new Fe(b, p)), D.setAttribute("faceIndex", new Fe(y, h)), t.push(D), s > ti && s--; + } + return { lodPlanes: t, sizeLods: e, sigmas: n }; +} +function Va(i, t, e) { + const n = new Nn(i, t, e); + return n.texture.mapping = ls, n.texture.name = "PMREM.cubeUv", n.scissorTest = !0, n; +} +function ji(i, t, e, n, s) { + i.viewport.set(t, e, n, s), i.scissor.set(t, e, n, s); +} +function Sd(i, t, e) { + const n = new Float32Array(Pn), s = new N(0, 1, 0); + return new xn({ + name: "SphericalGaussianBlur", + defines: { + n: Pn, + CUBEUV_TEXEL_WIDTH: 1 / t, + CUBEUV_TEXEL_HEIGHT: 1 / e, + CUBEUV_MAX_MIP: `${i}.0` + }, + uniforms: { + envMap: { value: null }, + samples: { value: 1 }, + weights: { value: n }, + latitudinal: { value: !1 }, + dTheta: { value: 0 }, + mipInt: { value: 0 }, + poleAxis: { value: s } + }, + vertexShader: Qr(), + 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 + + 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: _n, + depthTest: !1, + depthWrite: !1 + }); +} +function Ga() { + return new xn({ + name: "EquirectangularToCubeUV", + uniforms: { + envMap: { value: null } + }, + vertexShader: Qr(), + fragmentShader: ( + /* glsl */ + ` + + precision mediump float; + precision mediump int; + + varying vec3 vOutputDirection; + + uniform sampler2D envMap; + + #include + + void main() { + + vec3 outputDirection = normalize( vOutputDirection ); + vec2 uv = equirectUv( outputDirection ); + + gl_FragColor = vec4( texture2D ( envMap, uv ).rgb, 1.0 ); + + } + ` + ), + blending: _n, + depthTest: !1, + depthWrite: !1 + }); +} +function ka() { + return new xn({ + name: "CubemapToCubeUV", + uniforms: { + envMap: { value: null }, + flipEnvMap: { value: -1 } + }, + vertexShader: Qr(), + 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: _n, + depthTest: !1, + depthWrite: !1 + }); +} +function Qr() { + 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 Ed(i) { + let t = /* @__PURE__ */ new WeakMap(), e = null; + function n(o) { + if (o && o.isTexture) { + const c = o.mapping, l = c === ir || c === sr, u = c === ri || c === ai; + if (l || u) { + let d = t.get(o); + const f = d !== void 0 ? d.texture.pmremVersion : 0; + if (o.isRenderTargetTexture && o.pmremVersion !== f) + return e === null && (e = new Ha(i)), d = l ? e.fromEquirectangular(o, d) : e.fromCubemap(o, d), d.texture.pmremVersion = o.pmremVersion, t.set(o, d), d.texture; + if (d !== void 0) + return d.texture; + { + const m = o.image; + return l && m && m.height > 0 || u && m && s(m) ? (e === null && (e = new Ha(i)), d = l ? e.fromEquirectangular(o) : e.fromCubemap(o), d.texture.pmremVersion = o.pmremVersion, t.set(o, d), o.addEventListener("dispose", r), d.texture) : null; + } + } + } + return o; + } + function s(o) { + let c = 0; + const l = 6; + for (let u = 0; u < l; u++) + o[u] !== void 0 && c++; + return c === l; + } + function r(o) { + const c = o.target; + c.removeEventListener("dispose", r); + const l = t.get(c); + l !== void 0 && (t.delete(c), l.dispose()); + } + function a() { + t = /* @__PURE__ */ new WeakMap(), e !== null && (e.dispose(), e = null); + } + return { + get: n, + dispose: a + }; +} +function yd(i) { + const t = {}; + function e(n) { + if (t[n] !== void 0) + return t[n]; + let s; + switch (n) { + case "WEBGL_depth_texture": + s = i.getExtension("WEBGL_depth_texture") || i.getExtension("MOZ_WEBGL_depth_texture") || i.getExtension("WEBKIT_WEBGL_depth_texture"); + break; + case "EXT_texture_filter_anisotropic": + s = i.getExtension("EXT_texture_filter_anisotropic") || i.getExtension("MOZ_EXT_texture_filter_anisotropic") || i.getExtension("WEBKIT_EXT_texture_filter_anisotropic"); + break; + case "WEBGL_compressed_texture_s3tc": + s = i.getExtension("WEBGL_compressed_texture_s3tc") || i.getExtension("MOZ_WEBGL_compressed_texture_s3tc") || i.getExtension("WEBKIT_WEBGL_compressed_texture_s3tc"); + break; + case "WEBGL_compressed_texture_pvrtc": + s = i.getExtension("WEBGL_compressed_texture_pvrtc") || i.getExtension("WEBKIT_WEBGL_compressed_texture_pvrtc"); + break; + default: + s = i.getExtension(n); + } + return t[n] = s, s; + } + return { + has: function(n) { + return e(n) !== null; + }, + init: function() { + e("EXT_color_buffer_float"), e("WEBGL_clip_cull_distance"), e("OES_texture_float_linear"), e("EXT_color_buffer_half_float"), e("WEBGL_multisampled_render_to_texture"), e("WEBGL_render_shared_exponent"); + }, + get: function(n) { + const s = e(n); + return s === null && Si("THREE.WebGLRenderer: " + n + " extension not supported."), s; + } + }; +} +function Td(i, t, e, n) { + const s = {}, r = /* @__PURE__ */ new WeakMap(); + function a(d) { + const f = d.target; + f.index !== null && t.remove(f.index); + for (const v in f.attributes) + t.remove(f.attributes[v]); + f.removeEventListener("dispose", a), delete s[f.id]; + const m = r.get(f); + m && (t.remove(m), r.delete(f)), n.releaseStatesOfGeometry(f), f.isInstancedBufferGeometry === !0 && delete f._maxInstanceCount, e.memory.geometries--; + } + function o(d, f) { + return s[f.id] === !0 || (f.addEventListener("dispose", a), s[f.id] = !0, e.memory.geometries++), f; + } + function c(d) { + const f = d.attributes; + for (const m in f) + t.update(f[m], i.ARRAY_BUFFER); + } + function l(d) { + const f = [], m = d.index, v = d.attributes.position; + let x = 0; + if (m !== null) { + const A = m.array; + x = m.version; + for (let b = 0, y = A.length; b < y; b += 3) { + const D = A[b + 0], P = A[b + 1], w = A[b + 2]; + f.push(D, P, P, w, w, D); + } + } else if (v !== void 0) { + const A = v.array; + x = v.version; + for (let b = 0, y = A.length / 3 - 1; b < y; b += 3) { + const D = b + 0, P = b + 1, w = b + 2; + f.push(D, P, P, w, w, D); + } + } else + return; + const p = new (bo(f) ? Co : wo)(f, 1); + p.version = x; + const h = r.get(d); + h && t.remove(h), r.set(d, p); + } + function u(d) { + const f = r.get(d); + if (f) { + const m = d.index; + m !== null && f.version < m.version && l(d); + } else + l(d); + return r.get(d); + } + return { + get: o, + update: c, + getWireframeAttribute: u + }; +} +function bd(i, t, e) { + let n; + function s(f) { + n = f; + } + let r, a; + function o(f) { + r = f.type, a = f.bytesPerElement; + } + function c(f, m) { + i.drawElements(n, m, r, f * a), e.update(m, n, 1); + } + function l(f, m, v) { + v !== 0 && (i.drawElementsInstanced(n, m, r, f * a, v), e.update(m, n, v)); + } + function u(f, m, v) { + if (v === 0) return; + t.get("WEBGL_multi_draw").multiDrawElementsWEBGL(n, m, 0, r, f, 0, v); + let p = 0; + for (let h = 0; h < v; h++) + p += m[h]; + e.update(p, n, 1); + } + function d(f, m, v, x) { + if (v === 0) return; + const p = t.get("WEBGL_multi_draw"); + if (p === null) + for (let h = 0; h < f.length; h++) + l(f[h] / a, m[h], x[h]); + else { + p.multiDrawElementsInstancedWEBGL(n, m, 0, r, f, 0, x, 0, v); + let h = 0; + for (let A = 0; A < v; A++) + h += m[A] * x[A]; + e.update(h, n, 1); + } + } + this.setMode = s, this.setIndex = o, this.render = c, this.renderInstances = l, this.renderMultiDraw = u, this.renderMultiDrawInstances = d; +} +function Ad(i) { + const t = { + geometries: 0, + textures: 0 + }, e = { + frame: 0, + calls: 0, + triangles: 0, + points: 0, + lines: 0 + }; + function n(r, a, o) { + switch (e.calls++, a) { + case i.TRIANGLES: + e.triangles += o * (r / 3); + break; + case i.LINES: + e.lines += o * (r / 2); + break; + case i.LINE_STRIP: + e.lines += o * (r - 1); + break; + case i.LINE_LOOP: + e.lines += o * r; + break; + case i.POINTS: + e.points += o * r; + break; + default: + console.error("THREE.WebGLInfo: Unknown draw mode:", a); + break; + } + } + function s() { + e.calls = 0, e.triangles = 0, e.points = 0, e.lines = 0; + } + return { + memory: t, + render: e, + programs: null, + autoReset: !0, + reset: s, + update: n + }; +} +function Rd(i, t, e) { + const n = /* @__PURE__ */ new WeakMap(), s = new re(); + function r(a, o, c) { + const l = a.morphTargetInfluences, u = o.morphAttributes.position || o.morphAttributes.normal || o.morphAttributes.color, d = u !== void 0 ? u.length : 0; + let f = n.get(o); + if (f === void 0 || f.count !== d) { + let M = function() { + F.dispose(), n.delete(o), o.removeEventListener("dispose", M); + }; + var m = M; + f !== void 0 && f.texture.dispose(); + const v = o.morphAttributes.position !== void 0, x = o.morphAttributes.normal !== void 0, p = o.morphAttributes.color !== void 0, h = o.morphAttributes.position || [], A = o.morphAttributes.normal || [], b = o.morphAttributes.color || []; + let y = 0; + v === !0 && (y = 1), x === !0 && (y = 2), p === !0 && (y = 3); + let D = o.attributes.position.count * y, P = 1; + D > t.maxTextureSize && (P = Math.ceil(D / t.maxTextureSize), D = t.maxTextureSize); + const w = new Float32Array(D * P * 4 * d), F = new Ao(w, D, P, d); + F.type = sn, F.needsUpdate = !0; + const S = y * 4; + for (let C = 0; C < d; C++) { + const z = h[C], G = A[C], K = b[C], W = D * P * 4 * C; + for (let Y = 0; Y < z.count; Y++) { + const Z = Y * S; + v === !0 && (s.fromBufferAttribute(z, Y), w[W + Z + 0] = s.x, w[W + Z + 1] = s.y, w[W + Z + 2] = s.z, w[W + Z + 3] = 0), x === !0 && (s.fromBufferAttribute(G, Y), w[W + Z + 4] = s.x, w[W + Z + 5] = s.y, w[W + Z + 6] = s.z, w[W + Z + 7] = 0), p === !0 && (s.fromBufferAttribute(K, Y), w[W + Z + 8] = s.x, w[W + Z + 9] = s.y, w[W + Z + 10] = s.z, w[W + Z + 11] = K.itemSize === 4 ? s.w : 1); + } + } + f = { + count: d, + texture: F, + size: new Ct(D, P) + }, n.set(o, f), o.addEventListener("dispose", M); + } + if (a.isInstancedMesh === !0 && a.morphTexture !== null) + c.getUniforms().setValue(i, "morphTexture", a.morphTexture, e); + else { + let v = 0; + for (let p = 0; p < l.length; p++) + v += l[p]; + const x = o.morphTargetsRelative ? 1 : 1 - v; + c.getUniforms().setValue(i, "morphTargetBaseInfluence", x), c.getUniforms().setValue(i, "morphTargetInfluences", l); + } + c.getUniforms().setValue(i, "morphTargetsTexture", f.texture, e), c.getUniforms().setValue(i, "morphTargetsTextureSize", f.size); + } + return { + update: r + }; +} +function wd(i, t, e, n) { + let s = /* @__PURE__ */ new WeakMap(); + function r(c) { + const l = n.render.frame, u = c.geometry, d = t.get(c, u); + if (s.get(d) !== l && (t.update(d), s.set(d, l)), c.isInstancedMesh && (c.hasEventListener("dispose", o) === !1 && c.addEventListener("dispose", o), s.get(c) !== l && (e.update(c.instanceMatrix, i.ARRAY_BUFFER), c.instanceColor !== null && e.update(c.instanceColor, i.ARRAY_BUFFER), s.set(c, l))), c.isSkinnedMesh) { + const f = c.skeleton; + s.get(f) !== l && (f.update(), s.set(f, l)); + } + return d; + } + function a() { + s = /* @__PURE__ */ new WeakMap(); + } + function o(c) { + const l = c.target; + l.removeEventListener("dispose", o), e.remove(l.instanceMatrix), l.instanceColor !== null && e.remove(l.instanceColor); + } + return { + update: r, + dispose: a + }; +} +const Bo = /* @__PURE__ */ new Me(), Wa = /* @__PURE__ */ new Uo(1, 1), zo = /* @__PURE__ */ new Ao(), Ho = /* @__PURE__ */ new Jl(), Vo = /* @__PURE__ */ new Lo(), Xa = [], Ya = [], qa = new Float32Array(16), Ka = new Float32Array(9), ja = new Float32Array(4); +function ci(i, t, e) { + const n = i[0]; + if (n <= 0 || n > 0) return i; + const s = t * e; + let r = Xa[s]; + if (r === void 0 && (r = new Float32Array(s), Xa[s] = r), t !== 0) { + n.toArray(r, 0); + for (let a = 1, o = 0; a !== t; ++a) + o += e, i[a].toArray(r, o); + } + return r; +} +function he(i, t) { + if (i.length !== t.length) return !1; + for (let e = 0, n = i.length; e < n; e++) + if (i[e] !== t[e]) return !1; + return !0; +} +function ue(i, t) { + for (let e = 0, n = t.length; e < n; e++) + i[e] = t[e]; +} +function hs(i, t) { + let e = Ya[t]; + e === void 0 && (e = new Int32Array(t), Ya[t] = e); + for (let n = 0; n !== t; ++n) + e[n] = i.allocateTextureUnit(); + return e; +} +function Cd(i, t) { + const e = this.cache; + e[0] !== t && (i.uniform1f(this.addr, t), e[0] = t); +} +function Pd(i, t) { + const e = this.cache; + if (t.x !== void 0) + (e[0] !== t.x || e[1] !== t.y) && (i.uniform2f(this.addr, t.x, t.y), e[0] = t.x, e[1] = t.y); + else { + if (he(e, t)) return; + i.uniform2fv(this.addr, t), ue(e, t); + } +} +function Dd(i, t) { + const e = this.cache; + if (t.x !== void 0) + (e[0] !== t.x || e[1] !== t.y || e[2] !== t.z) && (i.uniform3f(this.addr, t.x, t.y, t.z), e[0] = t.x, e[1] = t.y, e[2] = t.z); + else if (t.r !== void 0) + (e[0] !== t.r || e[1] !== t.g || e[2] !== t.b) && (i.uniform3f(this.addr, t.r, t.g, t.b), e[0] = t.r, e[1] = t.g, e[2] = t.b); + else { + if (he(e, t)) return; + i.uniform3fv(this.addr, t), ue(e, t); + } +} +function Ld(i, t) { + const e = this.cache; + if (t.x !== void 0) + (e[0] !== t.x || e[1] !== t.y || e[2] !== t.z || e[3] !== t.w) && (i.uniform4f(this.addr, t.x, t.y, t.z, t.w), e[0] = t.x, e[1] = t.y, e[2] = t.z, e[3] = t.w); + else { + if (he(e, t)) return; + i.uniform4fv(this.addr, t), ue(e, t); + } +} +function Ud(i, t) { + const e = this.cache, n = t.elements; + if (n === void 0) { + if (he(e, t)) return; + i.uniformMatrix2fv(this.addr, !1, t), ue(e, t); + } else { + if (he(e, n)) return; + ja.set(n), i.uniformMatrix2fv(this.addr, !1, ja), ue(e, n); + } +} +function Id(i, t) { + const e = this.cache, n = t.elements; + if (n === void 0) { + if (he(e, t)) return; + i.uniformMatrix3fv(this.addr, !1, t), ue(e, t); + } else { + if (he(e, n)) return; + Ka.set(n), i.uniformMatrix3fv(this.addr, !1, Ka), ue(e, n); + } +} +function Nd(i, t) { + const e = this.cache, n = t.elements; + if (n === void 0) { + if (he(e, t)) return; + i.uniformMatrix4fv(this.addr, !1, t), ue(e, t); + } else { + if (he(e, n)) return; + qa.set(n), i.uniformMatrix4fv(this.addr, !1, qa), ue(e, n); + } +} +function Fd(i, t) { + const e = this.cache; + e[0] !== t && (i.uniform1i(this.addr, t), e[0] = t); +} +function Od(i, t) { + const e = this.cache; + if (t.x !== void 0) + (e[0] !== t.x || e[1] !== t.y) && (i.uniform2i(this.addr, t.x, t.y), e[0] = t.x, e[1] = t.y); + else { + if (he(e, t)) return; + i.uniform2iv(this.addr, t), ue(e, t); + } +} +function Bd(i, t) { + const e = this.cache; + if (t.x !== void 0) + (e[0] !== t.x || e[1] !== t.y || e[2] !== t.z) && (i.uniform3i(this.addr, t.x, t.y, t.z), e[0] = t.x, e[1] = t.y, e[2] = t.z); + else { + if (he(e, t)) return; + i.uniform3iv(this.addr, t), ue(e, t); + } +} +function zd(i, t) { + const e = this.cache; + if (t.x !== void 0) + (e[0] !== t.x || e[1] !== t.y || e[2] !== t.z || e[3] !== t.w) && (i.uniform4i(this.addr, t.x, t.y, t.z, t.w), e[0] = t.x, e[1] = t.y, e[2] = t.z, e[3] = t.w); + else { + if (he(e, t)) return; + i.uniform4iv(this.addr, t), ue(e, t); + } +} +function Hd(i, t) { + const e = this.cache; + e[0] !== t && (i.uniform1ui(this.addr, t), e[0] = t); +} +function Vd(i, t) { + const e = this.cache; + if (t.x !== void 0) + (e[0] !== t.x || e[1] !== t.y) && (i.uniform2ui(this.addr, t.x, t.y), e[0] = t.x, e[1] = t.y); + else { + if (he(e, t)) return; + i.uniform2uiv(this.addr, t), ue(e, t); + } +} +function Gd(i, t) { + const e = this.cache; + if (t.x !== void 0) + (e[0] !== t.x || e[1] !== t.y || e[2] !== t.z) && (i.uniform3ui(this.addr, t.x, t.y, t.z), e[0] = t.x, e[1] = t.y, e[2] = t.z); + else { + if (he(e, t)) return; + i.uniform3uiv(this.addr, t), ue(e, t); + } +} +function kd(i, t) { + const e = this.cache; + if (t.x !== void 0) + (e[0] !== t.x || e[1] !== t.y || e[2] !== t.z || e[3] !== t.w) && (i.uniform4ui(this.addr, t.x, t.y, t.z, t.w), e[0] = t.x, e[1] = t.y, e[2] = t.z, e[3] = t.w); + else { + if (he(e, t)) return; + i.uniform4uiv(this.addr, t), ue(e, t); + } +} +function Wd(i, t, e) { + const n = this.cache, s = e.allocateTextureUnit(); + n[0] !== s && (i.uniform1i(this.addr, s), n[0] = s); + let r; + this.type === i.SAMPLER_2D_SHADOW ? (Wa.compareFunction = To, r = Wa) : r = Bo, e.setTexture2D(t || r, s); +} +function Xd(i, t, e) { + const n = this.cache, s = e.allocateTextureUnit(); + n[0] !== s && (i.uniform1i(this.addr, s), n[0] = s), e.setTexture3D(t || Ho, s); +} +function Yd(i, t, e) { + const n = this.cache, s = e.allocateTextureUnit(); + n[0] !== s && (i.uniform1i(this.addr, s), n[0] = s), e.setTextureCube(t || Vo, s); +} +function qd(i, t, e) { + const n = this.cache, s = e.allocateTextureUnit(); + n[0] !== s && (i.uniform1i(this.addr, s), n[0] = s), e.setTexture2DArray(t || zo, s); +} +function Kd(i) { + switch (i) { + case 5126: + return Cd; + // FLOAT + case 35664: + return Pd; + // _VEC2 + case 35665: + return Dd; + // _VEC3 + case 35666: + return Ld; + // _VEC4 + case 35674: + return Ud; + // _MAT2 + case 35675: + return Id; + // _MAT3 + case 35676: + return Nd; + // _MAT4 + case 5124: + case 35670: + return Fd; + // INT, BOOL + case 35667: + case 35671: + return Od; + // _VEC2 + case 35668: + case 35672: + return Bd; + // _VEC3 + case 35669: + case 35673: + return zd; + // _VEC4 + case 5125: + return Hd; + // UINT + case 36294: + return Vd; + // _VEC2 + case 36295: + return Gd; + // _VEC3 + case 36296: + return kd; + // _VEC4 + case 35678: + // SAMPLER_2D + case 36198: + // SAMPLER_EXTERNAL_OES + case 36298: + // INT_SAMPLER_2D + case 36306: + // UNSIGNED_INT_SAMPLER_2D + case 35682: + return Wd; + case 35679: + // SAMPLER_3D + case 36299: + // INT_SAMPLER_3D + case 36307: + return Xd; + case 35680: + // SAMPLER_CUBE + case 36300: + // INT_SAMPLER_CUBE + case 36308: + // UNSIGNED_INT_SAMPLER_CUBE + case 36293: + return Yd; + case 36289: + // SAMPLER_2D_ARRAY + case 36303: + // INT_SAMPLER_2D_ARRAY + case 36311: + // UNSIGNED_INT_SAMPLER_2D_ARRAY + case 36292: + return qd; + } +} +function jd(i, t) { + i.uniform1fv(this.addr, t); +} +function Zd(i, t) { + const e = ci(t, this.size, 2); + i.uniform2fv(this.addr, e); +} +function $d(i, t) { + const e = ci(t, this.size, 3); + i.uniform3fv(this.addr, e); +} +function Jd(i, t) { + const e = ci(t, this.size, 4); + i.uniform4fv(this.addr, e); +} +function Qd(i, t) { + const e = ci(t, this.size, 4); + i.uniformMatrix2fv(this.addr, !1, e); +} +function tf(i, t) { + const e = ci(t, this.size, 9); + i.uniformMatrix3fv(this.addr, !1, e); +} +function ef(i, t) { + const e = ci(t, this.size, 16); + i.uniformMatrix4fv(this.addr, !1, e); +} +function nf(i, t) { + i.uniform1iv(this.addr, t); +} +function sf(i, t) { + i.uniform2iv(this.addr, t); +} +function rf(i, t) { + i.uniform3iv(this.addr, t); +} +function af(i, t) { + i.uniform4iv(this.addr, t); +} +function of(i, t) { + i.uniform1uiv(this.addr, t); +} +function lf(i, t) { + i.uniform2uiv(this.addr, t); +} +function cf(i, t) { + i.uniform3uiv(this.addr, t); +} +function hf(i, t) { + i.uniform4uiv(this.addr, t); +} +function uf(i, t, e) { + const n = this.cache, s = t.length, r = hs(e, s); + he(n, r) || (i.uniform1iv(this.addr, r), ue(n, r)); + for (let a = 0; a !== s; ++a) + e.setTexture2D(t[a] || Bo, r[a]); +} +function df(i, t, e) { + const n = this.cache, s = t.length, r = hs(e, s); + he(n, r) || (i.uniform1iv(this.addr, r), ue(n, r)); + for (let a = 0; a !== s; ++a) + e.setTexture3D(t[a] || Ho, r[a]); +} +function ff(i, t, e) { + const n = this.cache, s = t.length, r = hs(e, s); + he(n, r) || (i.uniform1iv(this.addr, r), ue(n, r)); + for (let a = 0; a !== s; ++a) + e.setTextureCube(t[a] || Vo, r[a]); +} +function pf(i, t, e) { + const n = this.cache, s = t.length, r = hs(e, s); + he(n, r) || (i.uniform1iv(this.addr, r), ue(n, r)); + for (let a = 0; a !== s; ++a) + e.setTexture2DArray(t[a] || zo, r[a]); +} +function mf(i) { + switch (i) { + case 5126: + return jd; + // FLOAT + case 35664: + return Zd; + // _VEC2 + case 35665: + return $d; + // _VEC3 + case 35666: + return Jd; + // _VEC4 + case 35674: + return Qd; + // _MAT2 + case 35675: + return tf; + // _MAT3 + case 35676: + return ef; + // _MAT4 + case 5124: + case 35670: + return nf; + // INT, BOOL + case 35667: + case 35671: + return sf; + // _VEC2 + case 35668: + case 35672: + return rf; + // _VEC3 + case 35669: + case 35673: + return af; + // _VEC4 + case 5125: + return of; + // UINT + case 36294: + return lf; + // _VEC2 + case 36295: + return cf; + // _VEC3 + case 36296: + return hf; + // _VEC4 + case 35678: + // SAMPLER_2D + case 36198: + // SAMPLER_EXTERNAL_OES + case 36298: + // INT_SAMPLER_2D + case 36306: + // UNSIGNED_INT_SAMPLER_2D + case 35682: + return uf; + case 35679: + // SAMPLER_3D + case 36299: + // INT_SAMPLER_3D + case 36307: + return df; + case 35680: + // SAMPLER_CUBE + case 36300: + // INT_SAMPLER_CUBE + case 36308: + // UNSIGNED_INT_SAMPLER_CUBE + case 36293: + return ff; + case 36289: + // SAMPLER_2D_ARRAY + case 36303: + // INT_SAMPLER_2D_ARRAY + case 36311: + // UNSIGNED_INT_SAMPLER_2D_ARRAY + case 36292: + return pf; + } +} +class _f { + constructor(t, e, n) { + this.id = t, this.addr = n, this.cache = [], this.type = e.type, this.setValue = Kd(e.type); + } +} +class gf { + constructor(t, e, n) { + this.id = t, this.addr = n, this.cache = [], this.type = e.type, this.size = e.size, this.setValue = mf(e.type); + } +} +class vf { + constructor(t) { + this.id = t, this.seq = [], this.map = {}; + } + setValue(t, e, n) { + const s = this.seq; + for (let r = 0, a = s.length; r !== a; ++r) { + const o = s[r]; + o.setValue(t, e[o.id], n); + } + } +} +const Ws = /(\w+)(\])?(\[|\.)?/g; +function Za(i, t) { + i.seq.push(t), i.map[t.id] = t; +} +function xf(i, t, e) { + const n = i.name, s = n.length; + for (Ws.lastIndex = 0; ; ) { + const r = Ws.exec(n), a = Ws.lastIndex; + let o = r[1]; + const c = r[2] === "]", l = r[3]; + if (c && (o = o | 0), l === void 0 || l === "[" && a + 2 === s) { + Za(e, l === void 0 ? new _f(o, i, t) : new gf(o, i, t)); + break; + } else { + let d = e.map[o]; + d === void 0 && (d = new vf(o), Za(e, d)), e = d; + } + } +} +class ss { + constructor(t, e) { + this.seq = [], this.map = {}; + const n = t.getProgramParameter(e, t.ACTIVE_UNIFORMS); + for (let s = 0; s < n; ++s) { + const r = t.getActiveUniform(e, s), a = t.getUniformLocation(e, r.name); + xf(r, a, this); + } + } + setValue(t, e, n, s) { + const r = this.map[e]; + r !== void 0 && r.setValue(t, n, s); + } + setOptional(t, e, n) { + const s = e[n]; + s !== void 0 && this.setValue(t, n, s); + } + static upload(t, e, n, s) { + for (let r = 0, a = e.length; r !== a; ++r) { + const o = e[r], c = n[o.id]; + c.needsUpdate !== !1 && o.setValue(t, c.value, s); + } + } + static seqWithValue(t, e) { + const n = []; + for (let s = 0, r = t.length; s !== r; ++s) { + const a = t[s]; + a.id in e && n.push(a); + } + return n; + } +} +function $a(i, t, e) { + const n = i.createShader(t); + return i.shaderSource(n, e), i.compileShader(n), n; +} +const Mf = 37297; +let Sf = 0; +function Ef(i, t) { + const e = i.split(` +`), n = [], s = Math.max(t - 6, 0), r = Math.min(t + 6, e.length); + for (let a = s; a < r; a++) { + const o = a + 1; + n.push(`${o === t ? ">" : " "} ${o}: ${e[a]}`); + } + return n.join(` +`); +} +const Ja = /* @__PURE__ */ new It(); +function yf(i) { + kt._getMatrix(Ja, kt.workingColorSpace, i); + const t = `mat3( ${Ja.elements.map((e) => e.toFixed(4))} )`; + switch (kt.getTransfer(i)) { + case rs: + return [t, "LinearTransferOETF"]; + case qt: + return [t, "sRGBTransferOETF"]; + default: + return console.warn("THREE.WebGLProgram: Unsupported color space: ", i), [t, "LinearTransferOETF"]; + } +} +function Qa(i, t, e) { + const n = i.getShaderParameter(t, i.COMPILE_STATUS), r = (i.getShaderInfoLog(t) || "").trim(); + if (n && r === "") return ""; + const a = /ERROR: 0:(\d+)/.exec(r); + if (a) { + const o = parseInt(a[1]); + return e.toUpperCase() + ` + +` + r + ` + +` + Ef(i.getShaderSource(t), o); + } else + return r; +} +function Tf(i, t) { + const e = yf(t); + return [ + `vec4 ${i}( vec4 value ) {`, + ` return ${e[1]}( vec4( value.rgb * ${e[0]}, value.a ) );`, + "}" + ].join(` +`); +} +function bf(i, t) { + let e; + switch (t) { + case bl: + e = "Linear"; + break; + case Al: + e = "Reinhard"; + break; + case Rl: + e = "Cineon"; + break; + case wl: + e = "ACESFilmic"; + break; + case Pl: + e = "AgX"; + break; + case Dl: + e = "Neutral"; + break; + case Cl: + e = "Custom"; + break; + default: + console.warn("THREE.WebGLProgram: Unsupported toneMapping:", t), e = "Linear"; + } + return "vec3 " + i + "( vec3 color ) { return " + e + "ToneMapping( color ); }"; +} +const Zi = /* @__PURE__ */ new N(); +function Af() { + kt.getLuminanceCoefficients(Zi); + const i = Zi.x.toFixed(4), t = Zi.y.toFixed(4), e = Zi.z.toFixed(4); + return [ + "float luminance( const in vec3 rgb ) {", + ` const vec3 weights = vec3( ${i}, ${t}, ${e} );`, + " return dot( weights, rgb );", + "}" + ].join(` +`); +} +function Rf(i) { + return [ + i.extensionClipCullDistance ? "#extension GL_ANGLE_clip_cull_distance : require" : "", + i.extensionMultiDraw ? "#extension GL_ANGLE_multi_draw : require" : "" + ].filter(_i).join(` +`); +} +function wf(i) { + const t = []; + for (const e in i) { + const n = i[e]; + n !== !1 && t.push("#define " + e + " " + n); + } + return t.join(` +`); +} +function Cf(i, t) { + const e = {}, n = i.getProgramParameter(t, i.ACTIVE_ATTRIBUTES); + for (let s = 0; s < n; s++) { + const r = i.getActiveAttrib(t, s), a = r.name; + let o = 1; + r.type === i.FLOAT_MAT2 && (o = 2), r.type === i.FLOAT_MAT3 && (o = 3), r.type === i.FLOAT_MAT4 && (o = 4), e[a] = { + type: r.type, + location: i.getAttribLocation(t, a), + locationSize: o + }; + } + return e; +} +function _i(i) { + return i !== ""; +} +function to(i, t) { + const e = t.numSpotLightShadows + t.numSpotLightMaps - t.numSpotLightShadowsWithMaps; + return i.replace(/NUM_DIR_LIGHTS/g, t.numDirLights).replace(/NUM_SPOT_LIGHTS/g, t.numSpotLights).replace(/NUM_SPOT_LIGHT_MAPS/g, t.numSpotLightMaps).replace(/NUM_SPOT_LIGHT_COORDS/g, e).replace(/NUM_RECT_AREA_LIGHTS/g, t.numRectAreaLights).replace(/NUM_POINT_LIGHTS/g, t.numPointLights).replace(/NUM_HEMI_LIGHTS/g, t.numHemiLights).replace(/NUM_DIR_LIGHT_SHADOWS/g, t.numDirLightShadows).replace(/NUM_SPOT_LIGHT_SHADOWS_WITH_MAPS/g, t.numSpotLightShadowsWithMaps).replace(/NUM_SPOT_LIGHT_SHADOWS/g, t.numSpotLightShadows).replace(/NUM_POINT_LIGHT_SHADOWS/g, t.numPointLightShadows); +} +function eo(i, t) { + return i.replace(/NUM_CLIPPING_PLANES/g, t.numClippingPlanes).replace(/UNION_CLIPPING_PLANES/g, t.numClippingPlanes - t.numClipIntersection); +} +const Pf = /^[ \t]*#include +<([\w\d./]+)>/gm; +function Or(i) { + return i.replace(Pf, Lf); +} +const Df = /* @__PURE__ */ new Map(); +function Lf(i, t) { + let e = Ft[t]; + if (e === void 0) { + const n = Df.get(t); + if (n !== void 0) + e = Ft[n], console.warn('THREE.WebGLRenderer: Shader chunk "%s" has been deprecated. Use "%s" instead.', t, n); + else + throw new Error("Can not resolve #include <" + t + ">"); + } + return Or(e); +} +const Uf = /#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 no(i) { + return i.replace(Uf, If); +} +function If(i, t, e, n) { + let s = ""; + for (let r = parseInt(t); r < parseInt(e); r++) + s += n.replace(/\[\s*i\s*\]/g, "[ " + r + " ]").replace(/UNROLLED_LOOP_INDEX/g, r); + return s; +} +function io(i) { + let t = `precision ${i.precision} float; + precision ${i.precision} int; + precision ${i.precision} sampler2D; + precision ${i.precision} samplerCube; + precision ${i.precision} sampler3D; + precision ${i.precision} sampler2DArray; + precision ${i.precision} sampler2DShadow; + precision ${i.precision} samplerCubeShadow; + precision ${i.precision} sampler2DArrayShadow; + precision ${i.precision} isampler2D; + precision ${i.precision} isampler3D; + precision ${i.precision} isamplerCube; + precision ${i.precision} isampler2DArray; + precision ${i.precision} usampler2D; + precision ${i.precision} usampler3D; + precision ${i.precision} usamplerCube; + precision ${i.precision} usampler2DArray; + `; + return i.precision === "highp" ? t += ` +#define HIGH_PRECISION` : i.precision === "mediump" ? t += ` +#define MEDIUM_PRECISION` : i.precision === "lowp" && (t += ` +#define LOW_PRECISION`), t; +} +function Nf(i) { + let t = "SHADOWMAP_TYPE_BASIC"; + return i.shadowMapType === fo ? t = "SHADOWMAP_TYPE_PCF" : i.shadowMapType === sl ? t = "SHADOWMAP_TYPE_PCF_SOFT" : i.shadowMapType === nn && (t = "SHADOWMAP_TYPE_VSM"), t; +} +function Ff(i) { + let t = "ENVMAP_TYPE_CUBE"; + if (i.envMap) + switch (i.envMapMode) { + case ri: + case ai: + t = "ENVMAP_TYPE_CUBE"; + break; + case ls: + t = "ENVMAP_TYPE_CUBE_UV"; + break; + } + return t; +} +function Of(i) { + let t = "ENVMAP_MODE_REFLECTION"; + if (i.envMap) + switch (i.envMapMode) { + case ai: + t = "ENVMAP_MODE_REFRACTION"; + break; + } + return t; +} +function Bf(i) { + let t = "ENVMAP_BLENDING_NONE"; + if (i.envMap) + switch (i.combine) { + case zr: + t = "ENVMAP_BLENDING_MULTIPLY"; + break; + case yl: + t = "ENVMAP_BLENDING_MIX"; + break; + case Tl: + t = "ENVMAP_BLENDING_ADD"; + break; + } + return t; +} +function zf(i) { + const t = i.envMapCubeUVHeight; + if (t === null) return null; + const e = Math.log2(t) - 2, n = 1 / t; + return { texelWidth: 1 / (3 * Math.max(Math.pow(2, e), 112)), texelHeight: n, maxMip: e }; +} +function Hf(i, t, e, n) { + const s = i.getContext(), r = e.defines; + let a = e.vertexShader, o = e.fragmentShader; + const c = Nf(e), l = Ff(e), u = Of(e), d = Bf(e), f = zf(e), m = Rf(e), v = wf(r), x = s.createProgram(); + let p, h, A = e.glslVersion ? "#version " + e.glslVersion + ` +` : ""; + e.isRawShaderMaterial ? (p = [ + "#define SHADER_TYPE " + e.shaderType, + "#define SHADER_NAME " + e.shaderName, + v + ].filter(_i).join(` +`), p.length > 0 && (p += ` +`), h = [ + "#define SHADER_TYPE " + e.shaderType, + "#define SHADER_NAME " + e.shaderName, + v + ].filter(_i).join(` +`), h.length > 0 && (h += ` +`)) : (p = [ + io(e), + "#define SHADER_TYPE " + e.shaderType, + "#define SHADER_NAME " + e.shaderName, + v, + e.extensionClipCullDistance ? "#define USE_CLIP_DISTANCE" : "", + e.batching ? "#define USE_BATCHING" : "", + e.batchingColor ? "#define USE_BATCHING_COLOR" : "", + e.instancing ? "#define USE_INSTANCING" : "", + e.instancingColor ? "#define USE_INSTANCING_COLOR" : "", + e.instancingMorph ? "#define USE_INSTANCING_MORPH" : "", + e.useFog && e.fog ? "#define USE_FOG" : "", + e.useFog && e.fogExp2 ? "#define FOG_EXP2" : "", + e.map ? "#define USE_MAP" : "", + e.envMap ? "#define USE_ENVMAP" : "", + e.envMap ? "#define " + u : "", + e.lightMap ? "#define USE_LIGHTMAP" : "", + e.aoMap ? "#define USE_AOMAP" : "", + e.bumpMap ? "#define USE_BUMPMAP" : "", + e.normalMap ? "#define USE_NORMALMAP" : "", + e.normalMapObjectSpace ? "#define USE_NORMALMAP_OBJECTSPACE" : "", + e.normalMapTangentSpace ? "#define USE_NORMALMAP_TANGENTSPACE" : "", + e.displacementMap ? "#define USE_DISPLACEMENTMAP" : "", + e.emissiveMap ? "#define USE_EMISSIVEMAP" : "", + e.anisotropy ? "#define USE_ANISOTROPY" : "", + e.anisotropyMap ? "#define USE_ANISOTROPYMAP" : "", + e.clearcoatMap ? "#define USE_CLEARCOATMAP" : "", + e.clearcoatRoughnessMap ? "#define USE_CLEARCOAT_ROUGHNESSMAP" : "", + e.clearcoatNormalMap ? "#define USE_CLEARCOAT_NORMALMAP" : "", + e.iridescenceMap ? "#define USE_IRIDESCENCEMAP" : "", + e.iridescenceThicknessMap ? "#define USE_IRIDESCENCE_THICKNESSMAP" : "", + e.specularMap ? "#define USE_SPECULARMAP" : "", + e.specularColorMap ? "#define USE_SPECULAR_COLORMAP" : "", + e.specularIntensityMap ? "#define USE_SPECULAR_INTENSITYMAP" : "", + e.roughnessMap ? "#define USE_ROUGHNESSMAP" : "", + e.metalnessMap ? "#define USE_METALNESSMAP" : "", + e.alphaMap ? "#define USE_ALPHAMAP" : "", + e.alphaHash ? "#define USE_ALPHAHASH" : "", + e.transmission ? "#define USE_TRANSMISSION" : "", + e.transmissionMap ? "#define USE_TRANSMISSIONMAP" : "", + e.thicknessMap ? "#define USE_THICKNESSMAP" : "", + e.sheenColorMap ? "#define USE_SHEEN_COLORMAP" : "", + e.sheenRoughnessMap ? "#define USE_SHEEN_ROUGHNESSMAP" : "", + // + e.mapUv ? "#define MAP_UV " + e.mapUv : "", + e.alphaMapUv ? "#define ALPHAMAP_UV " + e.alphaMapUv : "", + e.lightMapUv ? "#define LIGHTMAP_UV " + e.lightMapUv : "", + e.aoMapUv ? "#define AOMAP_UV " + e.aoMapUv : "", + e.emissiveMapUv ? "#define EMISSIVEMAP_UV " + e.emissiveMapUv : "", + e.bumpMapUv ? "#define BUMPMAP_UV " + e.bumpMapUv : "", + e.normalMapUv ? "#define NORMALMAP_UV " + e.normalMapUv : "", + e.displacementMapUv ? "#define DISPLACEMENTMAP_UV " + e.displacementMapUv : "", + e.metalnessMapUv ? "#define METALNESSMAP_UV " + e.metalnessMapUv : "", + e.roughnessMapUv ? "#define ROUGHNESSMAP_UV " + e.roughnessMapUv : "", + e.anisotropyMapUv ? "#define ANISOTROPYMAP_UV " + e.anisotropyMapUv : "", + e.clearcoatMapUv ? "#define CLEARCOATMAP_UV " + e.clearcoatMapUv : "", + e.clearcoatNormalMapUv ? "#define CLEARCOAT_NORMALMAP_UV " + e.clearcoatNormalMapUv : "", + e.clearcoatRoughnessMapUv ? "#define CLEARCOAT_ROUGHNESSMAP_UV " + e.clearcoatRoughnessMapUv : "", + e.iridescenceMapUv ? "#define IRIDESCENCEMAP_UV " + e.iridescenceMapUv : "", + e.iridescenceThicknessMapUv ? "#define IRIDESCENCE_THICKNESSMAP_UV " + e.iridescenceThicknessMapUv : "", + e.sheenColorMapUv ? "#define SHEEN_COLORMAP_UV " + e.sheenColorMapUv : "", + e.sheenRoughnessMapUv ? "#define SHEEN_ROUGHNESSMAP_UV " + e.sheenRoughnessMapUv : "", + e.specularMapUv ? "#define SPECULARMAP_UV " + e.specularMapUv : "", + e.specularColorMapUv ? "#define SPECULAR_COLORMAP_UV " + e.specularColorMapUv : "", + e.specularIntensityMapUv ? "#define SPECULAR_INTENSITYMAP_UV " + e.specularIntensityMapUv : "", + e.transmissionMapUv ? "#define TRANSMISSIONMAP_UV " + e.transmissionMapUv : "", + e.thicknessMapUv ? "#define THICKNESSMAP_UV " + e.thicknessMapUv : "", + // + e.vertexTangents && e.flatShading === !1 ? "#define USE_TANGENT" : "", + e.vertexColors ? "#define USE_COLOR" : "", + e.vertexAlphas ? "#define USE_COLOR_ALPHA" : "", + e.vertexUv1s ? "#define USE_UV1" : "", + e.vertexUv2s ? "#define USE_UV2" : "", + e.vertexUv3s ? "#define USE_UV3" : "", + e.pointsUvs ? "#define USE_POINTS_UV" : "", + e.flatShading ? "#define FLAT_SHADED" : "", + e.skinning ? "#define USE_SKINNING" : "", + e.morphTargets ? "#define USE_MORPHTARGETS" : "", + e.morphNormals && e.flatShading === !1 ? "#define USE_MORPHNORMALS" : "", + e.morphColors ? "#define USE_MORPHCOLORS" : "", + e.morphTargetsCount > 0 ? "#define MORPHTARGETS_TEXTURE_STRIDE " + e.morphTextureStride : "", + e.morphTargetsCount > 0 ? "#define MORPHTARGETS_COUNT " + e.morphTargetsCount : "", + e.doubleSided ? "#define DOUBLE_SIDED" : "", + e.flipSided ? "#define FLIP_SIDED" : "", + e.shadowMapEnabled ? "#define USE_SHADOWMAP" : "", + e.shadowMapEnabled ? "#define " + c : "", + e.sizeAttenuation ? "#define USE_SIZEATTENUATION" : "", + e.numLightProbes > 0 ? "#define USE_LIGHT_PROBES" : "", + e.logarithmicDepthBuffer ? "#define USE_LOGARITHMIC_DEPTH_BUFFER" : "", + e.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(_i).join(` +`), h = [ + io(e), + "#define SHADER_TYPE " + e.shaderType, + "#define SHADER_NAME " + e.shaderName, + v, + e.useFog && e.fog ? "#define USE_FOG" : "", + e.useFog && e.fogExp2 ? "#define FOG_EXP2" : "", + e.alphaToCoverage ? "#define ALPHA_TO_COVERAGE" : "", + e.map ? "#define USE_MAP" : "", + e.matcap ? "#define USE_MATCAP" : "", + e.envMap ? "#define USE_ENVMAP" : "", + e.envMap ? "#define " + l : "", + e.envMap ? "#define " + u : "", + e.envMap ? "#define " + d : "", + f ? "#define CUBEUV_TEXEL_WIDTH " + f.texelWidth : "", + f ? "#define CUBEUV_TEXEL_HEIGHT " + f.texelHeight : "", + f ? "#define CUBEUV_MAX_MIP " + f.maxMip + ".0" : "", + e.lightMap ? "#define USE_LIGHTMAP" : "", + e.aoMap ? "#define USE_AOMAP" : "", + e.bumpMap ? "#define USE_BUMPMAP" : "", + e.normalMap ? "#define USE_NORMALMAP" : "", + e.normalMapObjectSpace ? "#define USE_NORMALMAP_OBJECTSPACE" : "", + e.normalMapTangentSpace ? "#define USE_NORMALMAP_TANGENTSPACE" : "", + e.emissiveMap ? "#define USE_EMISSIVEMAP" : "", + e.anisotropy ? "#define USE_ANISOTROPY" : "", + e.anisotropyMap ? "#define USE_ANISOTROPYMAP" : "", + e.clearcoat ? "#define USE_CLEARCOAT" : "", + e.clearcoatMap ? "#define USE_CLEARCOATMAP" : "", + e.clearcoatRoughnessMap ? "#define USE_CLEARCOAT_ROUGHNESSMAP" : "", + e.clearcoatNormalMap ? "#define USE_CLEARCOAT_NORMALMAP" : "", + e.dispersion ? "#define USE_DISPERSION" : "", + e.iridescence ? "#define USE_IRIDESCENCE" : "", + e.iridescenceMap ? "#define USE_IRIDESCENCEMAP" : "", + e.iridescenceThicknessMap ? "#define USE_IRIDESCENCE_THICKNESSMAP" : "", + e.specularMap ? "#define USE_SPECULARMAP" : "", + e.specularColorMap ? "#define USE_SPECULAR_COLORMAP" : "", + e.specularIntensityMap ? "#define USE_SPECULAR_INTENSITYMAP" : "", + e.roughnessMap ? "#define USE_ROUGHNESSMAP" : "", + e.metalnessMap ? "#define USE_METALNESSMAP" : "", + e.alphaMap ? "#define USE_ALPHAMAP" : "", + e.alphaTest ? "#define USE_ALPHATEST" : "", + e.alphaHash ? "#define USE_ALPHAHASH" : "", + e.sheen ? "#define USE_SHEEN" : "", + e.sheenColorMap ? "#define USE_SHEEN_COLORMAP" : "", + e.sheenRoughnessMap ? "#define USE_SHEEN_ROUGHNESSMAP" : "", + e.transmission ? "#define USE_TRANSMISSION" : "", + e.transmissionMap ? "#define USE_TRANSMISSIONMAP" : "", + e.thicknessMap ? "#define USE_THICKNESSMAP" : "", + e.vertexTangents && e.flatShading === !1 ? "#define USE_TANGENT" : "", + e.vertexColors || e.instancingColor || e.batchingColor ? "#define USE_COLOR" : "", + e.vertexAlphas ? "#define USE_COLOR_ALPHA" : "", + e.vertexUv1s ? "#define USE_UV1" : "", + e.vertexUv2s ? "#define USE_UV2" : "", + e.vertexUv3s ? "#define USE_UV3" : "", + e.pointsUvs ? "#define USE_POINTS_UV" : "", + e.gradientMap ? "#define USE_GRADIENTMAP" : "", + e.flatShading ? "#define FLAT_SHADED" : "", + e.doubleSided ? "#define DOUBLE_SIDED" : "", + e.flipSided ? "#define FLIP_SIDED" : "", + e.shadowMapEnabled ? "#define USE_SHADOWMAP" : "", + e.shadowMapEnabled ? "#define " + c : "", + e.premultipliedAlpha ? "#define PREMULTIPLIED_ALPHA" : "", + e.numLightProbes > 0 ? "#define USE_LIGHT_PROBES" : "", + e.decodeVideoTexture ? "#define DECODE_VIDEO_TEXTURE" : "", + e.decodeVideoTextureEmissive ? "#define DECODE_VIDEO_TEXTURE_EMISSIVE" : "", + e.logarithmicDepthBuffer ? "#define USE_LOGARITHMIC_DEPTH_BUFFER" : "", + e.reversedDepthBuffer ? "#define USE_REVERSED_DEPTH_BUFFER" : "", + "uniform mat4 viewMatrix;", + "uniform vec3 cameraPosition;", + "uniform bool isOrthographic;", + e.toneMapping !== gn ? "#define TONE_MAPPING" : "", + e.toneMapping !== gn ? Ft.tonemapping_pars_fragment : "", + // this code is required here because it is used by the toneMapping() function defined below + e.toneMapping !== gn ? bf("toneMapping", e.toneMapping) : "", + e.dithering ? "#define DITHERING" : "", + e.opaque ? "#define OPAQUE" : "", + Ft.colorspace_pars_fragment, + // this code is required here because it is used by the various encoding/decoding function defined below + Tf("linearToOutputTexel", e.outputColorSpace), + Af(), + e.useDepthPacking ? "#define DEPTH_PACKING " + e.depthPacking : "", + ` +` + ].filter(_i).join(` +`)), a = Or(a), a = to(a, e), a = eo(a, e), o = Or(o), o = to(o, e), o = eo(o, e), a = no(a), o = no(o), e.isRawShaderMaterial !== !0 && (A = `#version 300 es +`, p = [ + m, + "#define attribute in", + "#define varying out", + "#define texture2D texture" + ].join(` +`) + ` +` + p, h = [ + "#define varying in", + e.glslVersion === fa ? "" : "layout(location = 0) out highp vec4 pc_fragColor;", + e.glslVersion === fa ? "" : "#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(` +`) + ` +` + h); + const b = A + p + a, y = A + h + o, D = $a(s, s.VERTEX_SHADER, b), P = $a(s, s.FRAGMENT_SHADER, y); + s.attachShader(x, D), s.attachShader(x, P), e.index0AttributeName !== void 0 ? s.bindAttribLocation(x, 0, e.index0AttributeName) : e.morphTargets === !0 && s.bindAttribLocation(x, 0, "position"), s.linkProgram(x); + function w(C) { + if (i.debug.checkShaderErrors) { + const z = s.getProgramInfoLog(x) || "", G = s.getShaderInfoLog(D) || "", K = s.getShaderInfoLog(P) || "", W = z.trim(), Y = G.trim(), Z = K.trim(); + let H = !0, rt = !0; + if (s.getProgramParameter(x, s.LINK_STATUS) === !1) + if (H = !1, typeof i.debug.onShaderError == "function") + i.debug.onShaderError(s, x, D, P); + else { + const ct = Qa(s, D, "vertex"), Et = Qa(s, P, "fragment"); + console.error( + "THREE.WebGLProgram: Shader Error " + s.getError() + " - VALIDATE_STATUS " + s.getProgramParameter(x, s.VALIDATE_STATUS) + ` + +Material Name: ` + C.name + ` +Material Type: ` + C.type + ` + +Program Info Log: ` + W + ` +` + ct + ` +` + Et + ); + } + else W !== "" ? console.warn("THREE.WebGLProgram: Program Info Log:", W) : (Y === "" || Z === "") && (rt = !1); + rt && (C.diagnostics = { + runnable: H, + programLog: W, + vertexShader: { + log: Y, + prefix: p + }, + fragmentShader: { + log: Z, + prefix: h + } + }); + } + s.deleteShader(D), s.deleteShader(P), F = new ss(s, x), S = Cf(s, x); + } + let F; + this.getUniforms = function() { + return F === void 0 && w(this), F; + }; + let S; + this.getAttributes = function() { + return S === void 0 && w(this), S; + }; + let M = e.rendererExtensionParallelShaderCompile === !1; + return this.isReady = function() { + return M === !1 && (M = s.getProgramParameter(x, Mf)), M; + }, this.destroy = function() { + n.releaseStatesOfProgram(this), s.deleteProgram(x), this.program = void 0; + }, this.type = e.shaderType, this.name = e.shaderName, this.id = Sf++, this.cacheKey = t, this.usedTimes = 1, this.program = x, this.vertexShader = D, this.fragmentShader = P, this; +} +let Vf = 0; +class Gf { + constructor() { + this.shaderCache = /* @__PURE__ */ new Map(), this.materialCache = /* @__PURE__ */ new Map(); + } + update(t) { + const e = t.vertexShader, n = t.fragmentShader, s = this._getShaderStage(e), r = this._getShaderStage(n), a = this._getShaderCacheForMaterial(t); + return a.has(s) === !1 && (a.add(s), s.usedTimes++), a.has(r) === !1 && (a.add(r), r.usedTimes++), this; + } + remove(t) { + const e = this.materialCache.get(t); + for (const n of e) + n.usedTimes--, n.usedTimes === 0 && this.shaderCache.delete(n.code); + return this.materialCache.delete(t), this; + } + getVertexShaderID(t) { + return this._getShaderStage(t.vertexShader).id; + } + getFragmentShaderID(t) { + return this._getShaderStage(t.fragmentShader).id; + } + dispose() { + this.shaderCache.clear(), this.materialCache.clear(); + } + _getShaderCacheForMaterial(t) { + const e = this.materialCache; + let n = e.get(t); + return n === void 0 && (n = /* @__PURE__ */ new Set(), e.set(t, n)), n; + } + _getShaderStage(t) { + const e = this.shaderCache; + let n = e.get(t); + return n === void 0 && (n = new kf(t), e.set(t, n)), n; + } +} +class kf { + constructor(t) { + this.id = Vf++, this.code = t, this.usedTimes = 0; + } +} +function Wf(i, t, e, n, s, r, a) { + const o = new jr(), c = new Gf(), l = /* @__PURE__ */ new Set(), u = [], d = s.logarithmicDepthBuffer, f = s.vertexTextures; + let m = s.precision; + const v = { + 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 x(S) { + return l.add(S), S === 0 ? "uv" : `uv${S}`; + } + function p(S, M, C, z, G) { + const K = z.fog, W = G.geometry, Y = S.isMeshStandardMaterial ? z.environment : null, Z = (S.isMeshStandardMaterial ? e : t).get(S.envMap || Y), H = Z && Z.mapping === ls ? Z.image.height : null, rt = v[S.type]; + S.precision !== null && (m = s.getMaxPrecision(S.precision), m !== S.precision && console.warn("THREE.WebGLProgram.getParameters:", S.precision, "not supported, using", m, "instead.")); + const ct = W.morphAttributes.position || W.morphAttributes.normal || W.morphAttributes.color, Et = ct !== void 0 ? ct.length : 0; + let Ot = 0; + W.morphAttributes.position !== void 0 && (Ot = 1), W.morphAttributes.normal !== void 0 && (Ot = 2), W.morphAttributes.color !== void 0 && (Ot = 3); + let Zt, Qt, Wt, X; + if (rt) { + const Xt = We[rt]; + Zt = Xt.vertexShader, Qt = Xt.fragmentShader; + } else + Zt = S.vertexShader, Qt = S.fragmentShader, c.update(S), Wt = c.getVertexShaderID(S), X = c.getFragmentShaderID(S); + const $ = i.getRenderTarget(), dt = i.state.buffers.depth.getReversed(), Pt = G.isInstancedMesh === !0, St = G.isBatchedMesh === !0, Ht = !!S.map, pe = !!S.matcap, T = !!Z, te = !!S.aoMap, Lt = !!S.lightMap, Rt = !!S.bumpMap, mt = !!S.normalMap, ee = !!S.displacementMap, _t = !!S.emissiveMap, Nt = !!S.metalnessMap, de = !!S.roughnessMap, oe = S.anisotropy > 0, E = S.clearcoat > 0, _ = S.dispersion > 0, I = S.iridescence > 0, k = S.sheen > 0, j = S.transmission > 0, V = oe && !!S.anisotropyMap, Mt = E && !!S.clearcoatMap, nt = E && !!S.clearcoatNormalMap, gt = E && !!S.clearcoatRoughnessMap, vt = I && !!S.iridescenceMap, tt = I && !!S.iridescenceThicknessMap, lt = k && !!S.sheenColorMap, At = k && !!S.sheenRoughnessMap, xt = !!S.specularMap, at = !!S.specularColorMap, Ut = !!S.specularIntensityMap, R = j && !!S.transmissionMap, et = j && !!S.thicknessMap, it = !!S.gradientMap, ut = !!S.alphaMap, J = S.alphaTest > 0, q = !!S.alphaHash, pt = !!S.extensions; + let Dt = gn; + S.toneMapped && ($ === null || $.isXRRenderTarget === !0) && (Dt = i.toneMapping); + const $t = { + shaderID: rt, + shaderType: S.type, + shaderName: S.name, + vertexShader: Zt, + fragmentShader: Qt, + defines: S.defines, + customVertexShaderID: Wt, + customFragmentShaderID: X, + isRawShaderMaterial: S.isRawShaderMaterial === !0, + glslVersion: S.glslVersion, + precision: m, + batching: St, + batchingColor: St && G._colorsTexture !== null, + instancing: Pt, + instancingColor: Pt && G.instanceColor !== null, + instancingMorph: Pt && G.morphTexture !== null, + supportsVertexTextures: f, + outputColorSpace: $ === null ? i.outputColorSpace : $.isXRRenderTarget === !0 ? $.texture.colorSpace : oi, + alphaToCoverage: !!S.alphaToCoverage, + map: Ht, + matcap: pe, + envMap: T, + envMapMode: T && Z.mapping, + envMapCubeUVHeight: H, + aoMap: te, + lightMap: Lt, + bumpMap: Rt, + normalMap: mt, + displacementMap: f && ee, + emissiveMap: _t, + normalMapObjectSpace: mt && S.normalMapType === Nl, + normalMapTangentSpace: mt && S.normalMapType === yo, + metalnessMap: Nt, + roughnessMap: de, + anisotropy: oe, + anisotropyMap: V, + clearcoat: E, + clearcoatMap: Mt, + clearcoatNormalMap: nt, + clearcoatRoughnessMap: gt, + dispersion: _, + iridescence: I, + iridescenceMap: vt, + iridescenceThicknessMap: tt, + sheen: k, + sheenColorMap: lt, + sheenRoughnessMap: At, + specularMap: xt, + specularColorMap: at, + specularIntensityMap: Ut, + transmission: j, + transmissionMap: R, + thicknessMap: et, + gradientMap: it, + opaque: S.transparent === !1 && S.blending === ni && S.alphaToCoverage === !1, + alphaMap: ut, + alphaTest: J, + alphaHash: q, + combine: S.combine, + // + mapUv: Ht && x(S.map.channel), + aoMapUv: te && x(S.aoMap.channel), + lightMapUv: Lt && x(S.lightMap.channel), + bumpMapUv: Rt && x(S.bumpMap.channel), + normalMapUv: mt && x(S.normalMap.channel), + displacementMapUv: ee && x(S.displacementMap.channel), + emissiveMapUv: _t && x(S.emissiveMap.channel), + metalnessMapUv: Nt && x(S.metalnessMap.channel), + roughnessMapUv: de && x(S.roughnessMap.channel), + anisotropyMapUv: V && x(S.anisotropyMap.channel), + clearcoatMapUv: Mt && x(S.clearcoatMap.channel), + clearcoatNormalMapUv: nt && x(S.clearcoatNormalMap.channel), + clearcoatRoughnessMapUv: gt && x(S.clearcoatRoughnessMap.channel), + iridescenceMapUv: vt && x(S.iridescenceMap.channel), + iridescenceThicknessMapUv: tt && x(S.iridescenceThicknessMap.channel), + sheenColorMapUv: lt && x(S.sheenColorMap.channel), + sheenRoughnessMapUv: At && x(S.sheenRoughnessMap.channel), + specularMapUv: xt && x(S.specularMap.channel), + specularColorMapUv: at && x(S.specularColorMap.channel), + specularIntensityMapUv: Ut && x(S.specularIntensityMap.channel), + transmissionMapUv: R && x(S.transmissionMap.channel), + thicknessMapUv: et && x(S.thicknessMap.channel), + alphaMapUv: ut && x(S.alphaMap.channel), + // + vertexTangents: !!W.attributes.tangent && (mt || oe), + vertexColors: S.vertexColors, + vertexAlphas: S.vertexColors === !0 && !!W.attributes.color && W.attributes.color.itemSize === 4, + pointsUvs: G.isPoints === !0 && !!W.attributes.uv && (Ht || ut), + fog: !!K, + useFog: S.fog === !0, + fogExp2: !!K && K.isFogExp2, + flatShading: S.flatShading === !0 && S.wireframe === !1, + sizeAttenuation: S.sizeAttenuation === !0, + logarithmicDepthBuffer: d, + reversedDepthBuffer: dt, + skinning: G.isSkinnedMesh === !0, + morphTargets: W.morphAttributes.position !== void 0, + morphNormals: W.morphAttributes.normal !== void 0, + morphColors: W.morphAttributes.color !== void 0, + morphTargetsCount: Et, + morphTextureStride: Ot, + numDirLights: M.directional.length, + numPointLights: M.point.length, + numSpotLights: M.spot.length, + numSpotLightMaps: M.spotLightMap.length, + numRectAreaLights: M.rectArea.length, + numHemiLights: M.hemi.length, + numDirLightShadows: M.directionalShadowMap.length, + numPointLightShadows: M.pointShadowMap.length, + numSpotLightShadows: M.spotShadowMap.length, + numSpotLightShadowsWithMaps: M.numSpotLightShadowsWithMaps, + numLightProbes: M.numLightProbes, + numClippingPlanes: a.numPlanes, + numClipIntersection: a.numIntersection, + dithering: S.dithering, + shadowMapEnabled: i.shadowMap.enabled && C.length > 0, + shadowMapType: i.shadowMap.type, + toneMapping: Dt, + decodeVideoTexture: Ht && S.map.isVideoTexture === !0 && kt.getTransfer(S.map.colorSpace) === qt, + decodeVideoTextureEmissive: _t && S.emissiveMap.isVideoTexture === !0 && kt.getTransfer(S.emissiveMap.colorSpace) === qt, + premultipliedAlpha: S.premultipliedAlpha, + doubleSided: S.side === De, + flipSided: S.side === Ae, + useDepthPacking: S.depthPacking >= 0, + depthPacking: S.depthPacking || 0, + index0AttributeName: S.index0AttributeName, + extensionClipCullDistance: pt && S.extensions.clipCullDistance === !0 && n.has("WEBGL_clip_cull_distance"), + extensionMultiDraw: (pt && S.extensions.multiDraw === !0 || St) && n.has("WEBGL_multi_draw"), + rendererExtensionParallelShaderCompile: n.has("KHR_parallel_shader_compile"), + customProgramCacheKey: S.customProgramCacheKey() + }; + return $t.vertexUv1s = l.has(1), $t.vertexUv2s = l.has(2), $t.vertexUv3s = l.has(3), l.clear(), $t; + } + function h(S) { + const M = []; + if (S.shaderID ? M.push(S.shaderID) : (M.push(S.customVertexShaderID), M.push(S.customFragmentShaderID)), S.defines !== void 0) + for (const C in S.defines) + M.push(C), M.push(S.defines[C]); + return S.isRawShaderMaterial === !1 && (A(M, S), b(M, S), M.push(i.outputColorSpace)), M.push(S.customProgramCacheKey), M.join(); + } + function A(S, M) { + S.push(M.precision), S.push(M.outputColorSpace), S.push(M.envMapMode), S.push(M.envMapCubeUVHeight), S.push(M.mapUv), S.push(M.alphaMapUv), S.push(M.lightMapUv), S.push(M.aoMapUv), S.push(M.bumpMapUv), S.push(M.normalMapUv), S.push(M.displacementMapUv), S.push(M.emissiveMapUv), S.push(M.metalnessMapUv), S.push(M.roughnessMapUv), S.push(M.anisotropyMapUv), S.push(M.clearcoatMapUv), S.push(M.clearcoatNormalMapUv), S.push(M.clearcoatRoughnessMapUv), S.push(M.iridescenceMapUv), S.push(M.iridescenceThicknessMapUv), S.push(M.sheenColorMapUv), S.push(M.sheenRoughnessMapUv), S.push(M.specularMapUv), S.push(M.specularColorMapUv), S.push(M.specularIntensityMapUv), S.push(M.transmissionMapUv), S.push(M.thicknessMapUv), S.push(M.combine), S.push(M.fogExp2), S.push(M.sizeAttenuation), S.push(M.morphTargetsCount), S.push(M.morphAttributeCount), S.push(M.numDirLights), S.push(M.numPointLights), S.push(M.numSpotLights), S.push(M.numSpotLightMaps), S.push(M.numHemiLights), S.push(M.numRectAreaLights), S.push(M.numDirLightShadows), S.push(M.numPointLightShadows), S.push(M.numSpotLightShadows), S.push(M.numSpotLightShadowsWithMaps), S.push(M.numLightProbes), S.push(M.shadowMapType), S.push(M.toneMapping), S.push(M.numClippingPlanes), S.push(M.numClipIntersection), S.push(M.depthPacking); + } + function b(S, M) { + o.disableAll(), M.supportsVertexTextures && o.enable(0), M.instancing && o.enable(1), M.instancingColor && o.enable(2), M.instancingMorph && o.enable(3), M.matcap && o.enable(4), M.envMap && o.enable(5), M.normalMapObjectSpace && o.enable(6), M.normalMapTangentSpace && o.enable(7), M.clearcoat && o.enable(8), M.iridescence && o.enable(9), M.alphaTest && o.enable(10), M.vertexColors && o.enable(11), M.vertexAlphas && o.enable(12), M.vertexUv1s && o.enable(13), M.vertexUv2s && o.enable(14), M.vertexUv3s && o.enable(15), M.vertexTangents && o.enable(16), M.anisotropy && o.enable(17), M.alphaHash && o.enable(18), M.batching && o.enable(19), M.dispersion && o.enable(20), M.batchingColor && o.enable(21), M.gradientMap && o.enable(22), S.push(o.mask), o.disableAll(), M.fog && o.enable(0), M.useFog && o.enable(1), M.flatShading && o.enable(2), M.logarithmicDepthBuffer && o.enable(3), M.reversedDepthBuffer && o.enable(4), M.skinning && o.enable(5), M.morphTargets && o.enable(6), M.morphNormals && o.enable(7), M.morphColors && o.enable(8), M.premultipliedAlpha && o.enable(9), M.shadowMapEnabled && o.enable(10), M.doubleSided && o.enable(11), M.flipSided && o.enable(12), M.useDepthPacking && o.enable(13), M.dithering && o.enable(14), M.transmission && o.enable(15), M.sheen && o.enable(16), M.opaque && o.enable(17), M.pointsUvs && o.enable(18), M.decodeVideoTexture && o.enable(19), M.decodeVideoTextureEmissive && o.enable(20), M.alphaToCoverage && o.enable(21), S.push(o.mask); + } + function y(S) { + const M = v[S.type]; + let C; + if (M) { + const z = We[M]; + C = uc.clone(z.uniforms); + } else + C = S.uniforms; + return C; + } + function D(S, M) { + let C; + for (let z = 0, G = u.length; z < G; z++) { + const K = u[z]; + if (K.cacheKey === M) { + C = K, ++C.usedTimes; + break; + } + } + return C === void 0 && (C = new Hf(i, M, S, r), u.push(C)), C; + } + function P(S) { + if (--S.usedTimes === 0) { + const M = u.indexOf(S); + u[M] = u[u.length - 1], u.pop(), S.destroy(); + } + } + function w(S) { + c.remove(S); + } + function F() { + c.dispose(); + } + return { + getParameters: p, + getProgramCacheKey: h, + getUniforms: y, + acquireProgram: D, + releaseProgram: P, + releaseShaderCache: w, + // Exposed for resource monitoring & error feedback via renderer.info: + programs: u, + dispose: F + }; +} +function Xf() { + let i = /* @__PURE__ */ new WeakMap(); + function t(a) { + return i.has(a); + } + function e(a) { + let o = i.get(a); + return o === void 0 && (o = {}, i.set(a, o)), o; + } + function n(a) { + i.delete(a); + } + function s(a, o, c) { + i.get(a)[o] = c; + } + function r() { + i = /* @__PURE__ */ new WeakMap(); + } + return { + has: t, + get: e, + remove: n, + update: s, + dispose: r + }; +} +function Yf(i, t) { + return i.groupOrder !== t.groupOrder ? i.groupOrder - t.groupOrder : i.renderOrder !== t.renderOrder ? i.renderOrder - t.renderOrder : i.material.id !== t.material.id ? i.material.id - t.material.id : i.z !== t.z ? i.z - t.z : i.id - t.id; +} +function so(i, t) { + return i.groupOrder !== t.groupOrder ? i.groupOrder - t.groupOrder : i.renderOrder !== t.renderOrder ? i.renderOrder - t.renderOrder : i.z !== t.z ? t.z - i.z : i.id - t.id; +} +function ro() { + const i = []; + let t = 0; + const e = [], n = [], s = []; + function r() { + t = 0, e.length = 0, n.length = 0, s.length = 0; + } + function a(d, f, m, v, x, p) { + let h = i[t]; + return h === void 0 ? (h = { + id: d.id, + object: d, + geometry: f, + material: m, + groupOrder: v, + renderOrder: d.renderOrder, + z: x, + group: p + }, i[t] = h) : (h.id = d.id, h.object = d, h.geometry = f, h.material = m, h.groupOrder = v, h.renderOrder = d.renderOrder, h.z = x, h.group = p), t++, h; + } + function o(d, f, m, v, x, p) { + const h = a(d, f, m, v, x, p); + m.transmission > 0 ? n.push(h) : m.transparent === !0 ? s.push(h) : e.push(h); + } + function c(d, f, m, v, x, p) { + const h = a(d, f, m, v, x, p); + m.transmission > 0 ? n.unshift(h) : m.transparent === !0 ? s.unshift(h) : e.unshift(h); + } + function l(d, f) { + e.length > 1 && e.sort(d || Yf), n.length > 1 && n.sort(f || so), s.length > 1 && s.sort(f || so); + } + function u() { + for (let d = t, f = i.length; d < f; d++) { + const m = i[d]; + if (m.id === null) break; + m.id = null, m.object = null, m.geometry = null, m.material = null, m.group = null; + } + } + return { + opaque: e, + transmissive: n, + transparent: s, + init: r, + push: o, + unshift: c, + finish: u, + sort: l + }; +} +function qf() { + let i = /* @__PURE__ */ new WeakMap(); + function t(n, s) { + const r = i.get(n); + let a; + return r === void 0 ? (a = new ro(), i.set(n, [a])) : s >= r.length ? (a = new ro(), r.push(a)) : a = r[s], a; + } + function e() { + i = /* @__PURE__ */ new WeakMap(); + } + return { + get: t, + dispose: e + }; +} +function Kf() { + const i = {}; + return { + get: function(t) { + if (i[t.id] !== void 0) + return i[t.id]; + let e; + switch (t.type) { + case "DirectionalLight": + e = { + direction: new N(), + color: new Vt() + }; + break; + case "SpotLight": + e = { + position: new N(), + direction: new N(), + color: new Vt(), + distance: 0, + coneCos: 0, + penumbraCos: 0, + decay: 0 + }; + break; + case "PointLight": + e = { + position: new N(), + color: new Vt(), + distance: 0, + decay: 0 + }; + break; + case "HemisphereLight": + e = { + direction: new N(), + skyColor: new Vt(), + groundColor: new Vt() + }; + break; + case "RectAreaLight": + e = { + color: new Vt(), + position: new N(), + halfWidth: new N(), + halfHeight: new N() + }; + break; + } + return i[t.id] = e, e; + } + }; +} +function jf() { + const i = {}; + return { + get: function(t) { + if (i[t.id] !== void 0) + return i[t.id]; + let e; + switch (t.type) { + case "DirectionalLight": + e = { + shadowIntensity: 1, + shadowBias: 0, + shadowNormalBias: 0, + shadowRadius: 1, + shadowMapSize: new Ct() + }; + break; + case "SpotLight": + e = { + shadowIntensity: 1, + shadowBias: 0, + shadowNormalBias: 0, + shadowRadius: 1, + shadowMapSize: new Ct() + }; + break; + case "PointLight": + e = { + shadowIntensity: 1, + shadowBias: 0, + shadowNormalBias: 0, + shadowRadius: 1, + shadowMapSize: new Ct(), + shadowCameraNear: 1, + shadowCameraFar: 1e3 + }; + break; + } + return i[t.id] = e, e; + } + }; +} +let Zf = 0; +function $f(i, t) { + return (t.castShadow ? 2 : 0) - (i.castShadow ? 2 : 0) + (t.map ? 1 : 0) - (i.map ? 1 : 0); +} +function Jf(i) { + const t = new Kf(), e = jf(), n = { + 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 l = 0; l < 9; l++) n.probe.push(new N()); + const s = new N(), r = new ae(), a = new ae(); + function o(l) { + let u = 0, d = 0, f = 0; + for (let S = 0; S < 9; S++) n.probe[S].set(0, 0, 0); + let m = 0, v = 0, x = 0, p = 0, h = 0, A = 0, b = 0, y = 0, D = 0, P = 0, w = 0; + l.sort($f); + for (let S = 0, M = l.length; S < M; S++) { + const C = l[S], z = C.color, G = C.intensity, K = C.distance, W = C.shadow && C.shadow.map ? C.shadow.map.texture : null; + if (C.isAmbientLight) + u += z.r * G, d += z.g * G, f += z.b * G; + else if (C.isLightProbe) { + for (let Y = 0; Y < 9; Y++) + n.probe[Y].addScaledVector(C.sh.coefficients[Y], G); + w++; + } else if (C.isDirectionalLight) { + const Y = t.get(C); + if (Y.color.copy(C.color).multiplyScalar(C.intensity), C.castShadow) { + const Z = C.shadow, H = e.get(C); + H.shadowIntensity = Z.intensity, H.shadowBias = Z.bias, H.shadowNormalBias = Z.normalBias, H.shadowRadius = Z.radius, H.shadowMapSize = Z.mapSize, n.directionalShadow[m] = H, n.directionalShadowMap[m] = W, n.directionalShadowMatrix[m] = C.shadow.matrix, A++; + } + n.directional[m] = Y, m++; + } else if (C.isSpotLight) { + const Y = t.get(C); + Y.position.setFromMatrixPosition(C.matrixWorld), Y.color.copy(z).multiplyScalar(G), Y.distance = K, Y.coneCos = Math.cos(C.angle), Y.penumbraCos = Math.cos(C.angle * (1 - C.penumbra)), Y.decay = C.decay, n.spot[x] = Y; + const Z = C.shadow; + if (C.map && (n.spotLightMap[D] = C.map, D++, Z.updateMatrices(C), C.castShadow && P++), n.spotLightMatrix[x] = Z.matrix, C.castShadow) { + const H = e.get(C); + H.shadowIntensity = Z.intensity, H.shadowBias = Z.bias, H.shadowNormalBias = Z.normalBias, H.shadowRadius = Z.radius, H.shadowMapSize = Z.mapSize, n.spotShadow[x] = H, n.spotShadowMap[x] = W, y++; + } + x++; + } else if (C.isRectAreaLight) { + const Y = t.get(C); + Y.color.copy(z).multiplyScalar(G), Y.halfWidth.set(C.width * 0.5, 0, 0), Y.halfHeight.set(0, C.height * 0.5, 0), n.rectArea[p] = Y, p++; + } else if (C.isPointLight) { + const Y = t.get(C); + if (Y.color.copy(C.color).multiplyScalar(C.intensity), Y.distance = C.distance, Y.decay = C.decay, C.castShadow) { + const Z = C.shadow, H = e.get(C); + H.shadowIntensity = Z.intensity, H.shadowBias = Z.bias, H.shadowNormalBias = Z.normalBias, H.shadowRadius = Z.radius, H.shadowMapSize = Z.mapSize, H.shadowCameraNear = Z.camera.near, H.shadowCameraFar = Z.camera.far, n.pointShadow[v] = H, n.pointShadowMap[v] = W, n.pointShadowMatrix[v] = C.shadow.matrix, b++; + } + n.point[v] = Y, v++; + } else if (C.isHemisphereLight) { + const Y = t.get(C); + Y.skyColor.copy(C.color).multiplyScalar(G), Y.groundColor.copy(C.groundColor).multiplyScalar(G), n.hemi[h] = Y, h++; + } + } + p > 0 && (i.has("OES_texture_float_linear") === !0 ? (n.rectAreaLTC1 = st.LTC_FLOAT_1, n.rectAreaLTC2 = st.LTC_FLOAT_2) : (n.rectAreaLTC1 = st.LTC_HALF_1, n.rectAreaLTC2 = st.LTC_HALF_2)), n.ambient[0] = u, n.ambient[1] = d, n.ambient[2] = f; + const F = n.hash; + (F.directionalLength !== m || F.pointLength !== v || F.spotLength !== x || F.rectAreaLength !== p || F.hemiLength !== h || F.numDirectionalShadows !== A || F.numPointShadows !== b || F.numSpotShadows !== y || F.numSpotMaps !== D || F.numLightProbes !== w) && (n.directional.length = m, n.spot.length = x, n.rectArea.length = p, n.point.length = v, n.hemi.length = h, n.directionalShadow.length = A, n.directionalShadowMap.length = A, n.pointShadow.length = b, n.pointShadowMap.length = b, n.spotShadow.length = y, n.spotShadowMap.length = y, n.directionalShadowMatrix.length = A, n.pointShadowMatrix.length = b, n.spotLightMatrix.length = y + D - P, n.spotLightMap.length = D, n.numSpotLightShadowsWithMaps = P, n.numLightProbes = w, F.directionalLength = m, F.pointLength = v, F.spotLength = x, F.rectAreaLength = p, F.hemiLength = h, F.numDirectionalShadows = A, F.numPointShadows = b, F.numSpotShadows = y, F.numSpotMaps = D, F.numLightProbes = w, n.version = Zf++); + } + function c(l, u) { + let d = 0, f = 0, m = 0, v = 0, x = 0; + const p = u.matrixWorldInverse; + for (let h = 0, A = l.length; h < A; h++) { + const b = l[h]; + if (b.isDirectionalLight) { + const y = n.directional[d]; + y.direction.setFromMatrixPosition(b.matrixWorld), s.setFromMatrixPosition(b.target.matrixWorld), y.direction.sub(s), y.direction.transformDirection(p), d++; + } else if (b.isSpotLight) { + const y = n.spot[m]; + y.position.setFromMatrixPosition(b.matrixWorld), y.position.applyMatrix4(p), y.direction.setFromMatrixPosition(b.matrixWorld), s.setFromMatrixPosition(b.target.matrixWorld), y.direction.sub(s), y.direction.transformDirection(p), m++; + } else if (b.isRectAreaLight) { + const y = n.rectArea[v]; + y.position.setFromMatrixPosition(b.matrixWorld), y.position.applyMatrix4(p), a.identity(), r.copy(b.matrixWorld), r.premultiply(p), a.extractRotation(r), y.halfWidth.set(b.width * 0.5, 0, 0), y.halfHeight.set(0, b.height * 0.5, 0), y.halfWidth.applyMatrix4(a), y.halfHeight.applyMatrix4(a), v++; + } else if (b.isPointLight) { + const y = n.point[f]; + y.position.setFromMatrixPosition(b.matrixWorld), y.position.applyMatrix4(p), f++; + } else if (b.isHemisphereLight) { + const y = n.hemi[x]; + y.direction.setFromMatrixPosition(b.matrixWorld), y.direction.transformDirection(p), x++; + } + } + } + return { + setup: o, + setupView: c, + state: n + }; +} +function ao(i) { + const t = new Jf(i), e = [], n = []; + function s(u) { + l.camera = u, e.length = 0, n.length = 0; + } + function r(u) { + e.push(u); + } + function a(u) { + n.push(u); + } + function o() { + t.setup(e); + } + function c(u) { + t.setupView(e, u); + } + const l = { + lightsArray: e, + shadowsArray: n, + camera: null, + lights: t, + transmissionRenderTarget: {} + }; + return { + init: s, + state: l, + setupLights: o, + setupLightsView: c, + pushLight: r, + pushShadow: a + }; +} +function Qf(i) { + let t = /* @__PURE__ */ new WeakMap(); + function e(s, r = 0) { + const a = t.get(s); + let o; + return a === void 0 ? (o = new ao(i), t.set(s, [o])) : r >= a.length ? (o = new ao(i), a.push(o)) : o = a[r], o; + } + function n() { + t = /* @__PURE__ */ new WeakMap(); + } + return { + get: e, + dispose: n + }; +} +const tp = `void main() { + gl_Position = vec4( position, 1.0 ); +}`, ep = `uniform sampler2D shadow_pass; +uniform vec2 resolution; +uniform float radius; +#include +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 np(i, t, e) { + let n = new $r(); + const s = new Ct(), r = new Ct(), a = new re(), o = new Ec({ depthPacking: Il }), c = new yc(), l = {}, u = e.maxTextureSize, d = { [vn]: Ae, [Ae]: vn, [De]: De }, f = new xn({ + defines: { + VSM_SAMPLES: 8 + }, + uniforms: { + shadow_pass: { value: null }, + resolution: { value: new Ct() }, + radius: { value: 4 } + }, + vertexShader: tp, + fragmentShader: ep + }), m = f.clone(); + m.defines.HORIZONTAL_PASS = 1; + const v = new an(); + v.setAttribute( + "position", + new Fe( + new Float32Array([-1, -1, 0.5, 3, -1, 0.5, -1, 3, 0.5]), + 3 + ) + ); + const x = new be(v, f), p = this; + this.enabled = !1, this.autoUpdate = !0, this.needsUpdate = !1, this.type = fo; + let h = this.type; + this.render = function(P, w, F) { + if (p.enabled === !1 || p.autoUpdate === !1 && p.needsUpdate === !1 || P.length === 0) return; + const S = i.getRenderTarget(), M = i.getActiveCubeFace(), C = i.getActiveMipmapLevel(), z = i.state; + z.setBlending(_n), z.buffers.depth.getReversed() === !0 ? z.buffers.color.setClear(0, 0, 0, 0) : z.buffers.color.setClear(1, 1, 1, 1), z.buffers.depth.setTest(!0), z.setScissorTest(!1); + const G = h !== nn && this.type === nn, K = h === nn && this.type !== nn; + for (let W = 0, Y = P.length; W < Y; W++) { + const Z = P[W], H = Z.shadow; + if (H === void 0) { + console.warn("THREE.WebGLShadowMap:", Z, "has no shadow."); + continue; + } + if (H.autoUpdate === !1 && H.needsUpdate === !1) continue; + s.copy(H.mapSize); + const rt = H.getFrameExtents(); + if (s.multiply(rt), r.copy(H.mapSize), (s.x > u || s.y > u) && (s.x > u && (r.x = Math.floor(u / rt.x), s.x = r.x * rt.x, H.mapSize.x = r.x), s.y > u && (r.y = Math.floor(u / rt.y), s.y = r.y * rt.y, H.mapSize.y = r.y)), H.map === null || G === !0 || K === !0) { + const Et = this.type !== nn ? { minFilter: Ge, magFilter: Ge } : {}; + H.map !== null && H.map.dispose(), H.map = new Nn(s.x, s.y, Et), H.map.texture.name = Z.name + ".shadowMap", H.camera.updateProjectionMatrix(); + } + i.setRenderTarget(H.map), i.clear(); + const ct = H.getViewportCount(); + for (let Et = 0; Et < ct; Et++) { + const Ot = H.getViewport(Et); + a.set( + r.x * Ot.x, + r.y * Ot.y, + r.x * Ot.z, + r.y * Ot.w + ), z.viewport(a), H.updateMatrices(Z, Et), n = H.getFrustum(), y(w, F, H.camera, Z, this.type); + } + H.isPointLightShadow !== !0 && this.type === nn && A(H, F), H.needsUpdate = !1; + } + h = this.type, p.needsUpdate = !1, i.setRenderTarget(S, M, C); + }; + function A(P, w) { + const F = t.update(x); + f.defines.VSM_SAMPLES !== P.blurSamples && (f.defines.VSM_SAMPLES = P.blurSamples, m.defines.VSM_SAMPLES = P.blurSamples, f.needsUpdate = !0, m.needsUpdate = !0), P.mapPass === null && (P.mapPass = new Nn(s.x, s.y)), f.uniforms.shadow_pass.value = P.map.texture, f.uniforms.resolution.value = P.mapSize, f.uniforms.radius.value = P.radius, i.setRenderTarget(P.mapPass), i.clear(), i.renderBufferDirect(w, null, F, f, x, null), m.uniforms.shadow_pass.value = P.mapPass.texture, m.uniforms.resolution.value = P.mapSize, m.uniforms.radius.value = P.radius, i.setRenderTarget(P.map), i.clear(), i.renderBufferDirect(w, null, F, m, x, null); + } + function b(P, w, F, S) { + let M = null; + const C = F.isPointLight === !0 ? P.customDistanceMaterial : P.customDepthMaterial; + if (C !== void 0) + M = C; + else if (M = F.isPointLight === !0 ? c : o, i.localClippingEnabled && w.clipShadows === !0 && Array.isArray(w.clippingPlanes) && w.clippingPlanes.length !== 0 || w.displacementMap && w.displacementScale !== 0 || w.alphaMap && w.alphaTest > 0 || w.map && w.alphaTest > 0 || w.alphaToCoverage === !0) { + const z = M.uuid, G = w.uuid; + let K = l[z]; + K === void 0 && (K = {}, l[z] = K); + let W = K[G]; + W === void 0 && (W = M.clone(), K[G] = W, w.addEventListener("dispose", D)), M = W; + } + if (M.visible = w.visible, M.wireframe = w.wireframe, S === nn ? M.side = w.shadowSide !== null ? w.shadowSide : w.side : M.side = w.shadowSide !== null ? w.shadowSide : d[w.side], M.alphaMap = w.alphaMap, M.alphaTest = w.alphaToCoverage === !0 ? 0.5 : w.alphaTest, M.map = w.map, M.clipShadows = w.clipShadows, M.clippingPlanes = w.clippingPlanes, M.clipIntersection = w.clipIntersection, M.displacementMap = w.displacementMap, M.displacementScale = w.displacementScale, M.displacementBias = w.displacementBias, M.wireframeLinewidth = w.wireframeLinewidth, M.linewidth = w.linewidth, F.isPointLight === !0 && M.isMeshDistanceMaterial === !0) { + const z = i.properties.get(M); + z.light = F; + } + return M; + } + function y(P, w, F, S, M) { + if (P.visible === !1) return; + if (P.layers.test(w.layers) && (P.isMesh || P.isLine || P.isPoints) && (P.castShadow || P.receiveShadow && M === nn) && (!P.frustumCulled || n.intersectsObject(P))) { + P.modelViewMatrix.multiplyMatrices(F.matrixWorldInverse, P.matrixWorld); + const G = t.update(P), K = P.material; + if (Array.isArray(K)) { + const W = G.groups; + for (let Y = 0, Z = W.length; Y < Z; Y++) { + const H = W[Y], rt = K[H.materialIndex]; + if (rt && rt.visible) { + const ct = b(P, rt, S, M); + P.onBeforeShadow(i, P, w, F, G, ct, H), i.renderBufferDirect(F, null, G, ct, P, H), P.onAfterShadow(i, P, w, F, G, ct, H); + } + } + } else if (K.visible) { + const W = b(P, K, S, M); + P.onBeforeShadow(i, P, w, F, G, W, null), i.renderBufferDirect(F, null, G, W, P, null), P.onAfterShadow(i, P, w, F, G, W, null); + } + } + const z = P.children; + for (let G = 0, K = z.length; G < K; G++) + y(z[G], w, F, S, M); + } + function D(P) { + P.target.removeEventListener("dispose", D); + for (const F in l) { + const S = l[F], M = P.target.uuid; + M in S && (S[M].dispose(), delete S[M]); + } + } +} +const ip = { + [Zs]: $s, + [Js]: er, + [Qs]: nr, + [si]: tr, + [$s]: Zs, + [er]: Js, + [nr]: Qs, + [tr]: si +}; +function sp(i, t) { + function e() { + let R = !1; + const et = new re(); + let it = null; + const ut = new re(0, 0, 0, 0); + return { + setMask: function(J) { + it !== J && !R && (i.colorMask(J, J, J, J), it = J); + }, + setLocked: function(J) { + R = J; + }, + setClear: function(J, q, pt, Dt, $t) { + $t === !0 && (J *= Dt, q *= Dt, pt *= Dt), et.set(J, q, pt, Dt), ut.equals(et) === !1 && (i.clearColor(J, q, pt, Dt), ut.copy(et)); + }, + reset: function() { + R = !1, it = null, ut.set(-1, 0, 0, 0); + } + }; + } + function n() { + let R = !1, et = !1, it = null, ut = null, J = null; + return { + setReversed: function(q) { + if (et !== q) { + const pt = t.get("EXT_clip_control"); + q ? pt.clipControlEXT(pt.LOWER_LEFT_EXT, pt.ZERO_TO_ONE_EXT) : pt.clipControlEXT(pt.LOWER_LEFT_EXT, pt.NEGATIVE_ONE_TO_ONE_EXT), et = q; + const Dt = J; + J = null, this.setClear(Dt); + } + }, + getReversed: function() { + return et; + }, + setTest: function(q) { + q ? $(i.DEPTH_TEST) : dt(i.DEPTH_TEST); + }, + setMask: function(q) { + it !== q && !R && (i.depthMask(q), it = q); + }, + setFunc: function(q) { + if (et && (q = ip[q]), ut !== q) { + switch (q) { + case Zs: + i.depthFunc(i.NEVER); + break; + case $s: + i.depthFunc(i.ALWAYS); + break; + case Js: + i.depthFunc(i.LESS); + break; + case si: + i.depthFunc(i.LEQUAL); + break; + case Qs: + i.depthFunc(i.EQUAL); + break; + case tr: + i.depthFunc(i.GEQUAL); + break; + case er: + i.depthFunc(i.GREATER); + break; + case nr: + i.depthFunc(i.NOTEQUAL); + break; + default: + i.depthFunc(i.LEQUAL); + } + ut = q; + } + }, + setLocked: function(q) { + R = q; + }, + setClear: function(q) { + J !== q && (et && (q = 1 - q), i.clearDepth(q), J = q); + }, + reset: function() { + R = !1, it = null, ut = null, J = null, et = !1; + } + }; + } + function s() { + let R = !1, et = null, it = null, ut = null, J = null, q = null, pt = null, Dt = null, $t = null; + return { + setTest: function(Xt) { + R || (Xt ? $(i.STENCIL_TEST) : dt(i.STENCIL_TEST)); + }, + setMask: function(Xt) { + et !== Xt && !R && (i.stencilMask(Xt), et = Xt); + }, + setFunc: function(Xt, Ze, ke) { + (it !== Xt || ut !== Ze || J !== ke) && (i.stencilFunc(Xt, Ze, ke), it = Xt, ut = Ze, J = ke); + }, + setOp: function(Xt, Ze, ke) { + (q !== Xt || pt !== Ze || Dt !== ke) && (i.stencilOp(Xt, Ze, ke), q = Xt, pt = Ze, Dt = ke); + }, + setLocked: function(Xt) { + R = Xt; + }, + setClear: function(Xt) { + $t !== Xt && (i.clearStencil(Xt), $t = Xt); + }, + reset: function() { + R = !1, et = null, it = null, ut = null, J = null, q = null, pt = null, Dt = null, $t = null; + } + }; + } + const r = new e(), a = new n(), o = new s(), c = /* @__PURE__ */ new WeakMap(), l = /* @__PURE__ */ new WeakMap(); + let u = {}, d = {}, f = /* @__PURE__ */ new WeakMap(), m = [], v = null, x = !1, p = null, h = null, A = null, b = null, y = null, D = null, P = null, w = new Vt(0, 0, 0), F = 0, S = !1, M = null, C = null, z = null, G = null, K = null; + const W = i.getParameter(i.MAX_COMBINED_TEXTURE_IMAGE_UNITS); + let Y = !1, Z = 0; + const H = i.getParameter(i.VERSION); + H.indexOf("WebGL") !== -1 ? (Z = parseFloat(/^WebGL (\d)/.exec(H)[1]), Y = Z >= 1) : H.indexOf("OpenGL ES") !== -1 && (Z = parseFloat(/^OpenGL ES (\d)/.exec(H)[1]), Y = Z >= 2); + let rt = null, ct = {}; + const Et = i.getParameter(i.SCISSOR_BOX), Ot = i.getParameter(i.VIEWPORT), Zt = new re().fromArray(Et), Qt = new re().fromArray(Ot); + function Wt(R, et, it, ut) { + const J = new Uint8Array(4), q = i.createTexture(); + i.bindTexture(R, q), i.texParameteri(R, i.TEXTURE_MIN_FILTER, i.NEAREST), i.texParameteri(R, i.TEXTURE_MAG_FILTER, i.NEAREST); + for (let pt = 0; pt < it; pt++) + R === i.TEXTURE_3D || R === i.TEXTURE_2D_ARRAY ? i.texImage3D(et, 0, i.RGBA, 1, 1, ut, 0, i.RGBA, i.UNSIGNED_BYTE, J) : i.texImage2D(et + pt, 0, i.RGBA, 1, 1, 0, i.RGBA, i.UNSIGNED_BYTE, J); + return q; + } + const X = {}; + X[i.TEXTURE_2D] = Wt(i.TEXTURE_2D, i.TEXTURE_2D, 1), X[i.TEXTURE_CUBE_MAP] = Wt(i.TEXTURE_CUBE_MAP, i.TEXTURE_CUBE_MAP_POSITIVE_X, 6), X[i.TEXTURE_2D_ARRAY] = Wt(i.TEXTURE_2D_ARRAY, i.TEXTURE_2D_ARRAY, 1, 1), X[i.TEXTURE_3D] = Wt(i.TEXTURE_3D, i.TEXTURE_3D, 1, 1), r.setClear(0, 0, 0, 1), a.setClear(1), o.setClear(0), $(i.DEPTH_TEST), a.setFunc(si), Rt(!1), mt(oa), $(i.CULL_FACE), te(_n); + function $(R) { + u[R] !== !0 && (i.enable(R), u[R] = !0); + } + function dt(R) { + u[R] !== !1 && (i.disable(R), u[R] = !1); + } + function Pt(R, et) { + return d[R] !== et ? (i.bindFramebuffer(R, et), d[R] = et, R === i.DRAW_FRAMEBUFFER && (d[i.FRAMEBUFFER] = et), R === i.FRAMEBUFFER && (d[i.DRAW_FRAMEBUFFER] = et), !0) : !1; + } + function St(R, et) { + let it = m, ut = !1; + if (R) { + it = f.get(et), it === void 0 && (it = [], f.set(et, it)); + const J = R.textures; + if (it.length !== J.length || it[0] !== i.COLOR_ATTACHMENT0) { + for (let q = 0, pt = J.length; q < pt; q++) + it[q] = i.COLOR_ATTACHMENT0 + q; + it.length = J.length, ut = !0; + } + } else + it[0] !== i.BACK && (it[0] = i.BACK, ut = !0); + ut && i.drawBuffers(it); + } + function Ht(R) { + return v !== R ? (i.useProgram(R), v = R, !0) : !1; + } + const pe = { + [Cn]: i.FUNC_ADD, + [al]: i.FUNC_SUBTRACT, + [ol]: i.FUNC_REVERSE_SUBTRACT + }; + pe[ll] = i.MIN, pe[cl] = i.MAX; + const T = { + [hl]: i.ZERO, + [ul]: i.ONE, + [dl]: i.SRC_COLOR, + [Ks]: i.SRC_ALPHA, + [vl]: i.SRC_ALPHA_SATURATE, + [_l]: i.DST_COLOR, + [pl]: i.DST_ALPHA, + [fl]: i.ONE_MINUS_SRC_COLOR, + [js]: i.ONE_MINUS_SRC_ALPHA, + [gl]: i.ONE_MINUS_DST_COLOR, + [ml]: i.ONE_MINUS_DST_ALPHA, + [xl]: i.CONSTANT_COLOR, + [Ml]: i.ONE_MINUS_CONSTANT_COLOR, + [Sl]: i.CONSTANT_ALPHA, + [El]: i.ONE_MINUS_CONSTANT_ALPHA + }; + function te(R, et, it, ut, J, q, pt, Dt, $t, Xt) { + if (R === _n) { + x === !0 && (dt(i.BLEND), x = !1); + return; + } + if (x === !1 && ($(i.BLEND), x = !0), R !== rl) { + if (R !== p || Xt !== S) { + if ((h !== Cn || y !== Cn) && (i.blendEquation(i.FUNC_ADD), h = Cn, y = Cn), Xt) + switch (R) { + case ni: + i.blendFuncSeparate(i.ONE, i.ONE_MINUS_SRC_ALPHA, i.ONE, i.ONE_MINUS_SRC_ALPHA); + break; + case la: + i.blendFunc(i.ONE, i.ONE); + break; + case ca: + i.blendFuncSeparate(i.ZERO, i.ONE_MINUS_SRC_COLOR, i.ZERO, i.ONE); + break; + case ha: + i.blendFuncSeparate(i.DST_COLOR, i.ONE_MINUS_SRC_ALPHA, i.ZERO, i.ONE); + break; + default: + console.error("THREE.WebGLState: Invalid blending: ", R); + break; + } + else + switch (R) { + case ni: + i.blendFuncSeparate(i.SRC_ALPHA, i.ONE_MINUS_SRC_ALPHA, i.ONE, i.ONE_MINUS_SRC_ALPHA); + break; + case la: + i.blendFuncSeparate(i.SRC_ALPHA, i.ONE, i.ONE, i.ONE); + break; + case ca: + console.error("THREE.WebGLState: SubtractiveBlending requires material.premultipliedAlpha = true"); + break; + case ha: + console.error("THREE.WebGLState: MultiplyBlending requires material.premultipliedAlpha = true"); + break; + default: + console.error("THREE.WebGLState: Invalid blending: ", R); + break; + } + A = null, b = null, D = null, P = null, w.set(0, 0, 0), F = 0, p = R, S = Xt; + } + return; + } + J = J || et, q = q || it, pt = pt || ut, (et !== h || J !== y) && (i.blendEquationSeparate(pe[et], pe[J]), h = et, y = J), (it !== A || ut !== b || q !== D || pt !== P) && (i.blendFuncSeparate(T[it], T[ut], T[q], T[pt]), A = it, b = ut, D = q, P = pt), (Dt.equals(w) === !1 || $t !== F) && (i.blendColor(Dt.r, Dt.g, Dt.b, $t), w.copy(Dt), F = $t), p = R, S = !1; + } + function Lt(R, et) { + R.side === De ? dt(i.CULL_FACE) : $(i.CULL_FACE); + let it = R.side === Ae; + et && (it = !it), Rt(it), R.blending === ni && R.transparent === !1 ? te(_n) : te(R.blending, R.blendEquation, R.blendSrc, R.blendDst, R.blendEquationAlpha, R.blendSrcAlpha, R.blendDstAlpha, R.blendColor, R.blendAlpha, R.premultipliedAlpha), a.setFunc(R.depthFunc), a.setTest(R.depthTest), a.setMask(R.depthWrite), r.setMask(R.colorWrite); + const ut = R.stencilWrite; + o.setTest(ut), ut && (o.setMask(R.stencilWriteMask), o.setFunc(R.stencilFunc, R.stencilRef, R.stencilFuncMask), o.setOp(R.stencilFail, R.stencilZFail, R.stencilZPass)), _t(R.polygonOffset, R.polygonOffsetFactor, R.polygonOffsetUnits), R.alphaToCoverage === !0 ? $(i.SAMPLE_ALPHA_TO_COVERAGE) : dt(i.SAMPLE_ALPHA_TO_COVERAGE); + } + function Rt(R) { + M !== R && (R ? i.frontFace(i.CW) : i.frontFace(i.CCW), M = R); + } + function mt(R) { + R !== nl ? ($(i.CULL_FACE), R !== C && (R === oa ? i.cullFace(i.BACK) : R === il ? i.cullFace(i.FRONT) : i.cullFace(i.FRONT_AND_BACK))) : dt(i.CULL_FACE), C = R; + } + function ee(R) { + R !== z && (Y && i.lineWidth(R), z = R); + } + function _t(R, et, it) { + R ? ($(i.POLYGON_OFFSET_FILL), (G !== et || K !== it) && (i.polygonOffset(et, it), G = et, K = it)) : dt(i.POLYGON_OFFSET_FILL); + } + function Nt(R) { + R ? $(i.SCISSOR_TEST) : dt(i.SCISSOR_TEST); + } + function de(R) { + R === void 0 && (R = i.TEXTURE0 + W - 1), rt !== R && (i.activeTexture(R), rt = R); + } + function oe(R, et, it) { + it === void 0 && (rt === null ? it = i.TEXTURE0 + W - 1 : it = rt); + let ut = ct[it]; + ut === void 0 && (ut = { type: void 0, texture: void 0 }, ct[it] = ut), (ut.type !== R || ut.texture !== et) && (rt !== it && (i.activeTexture(it), rt = it), i.bindTexture(R, et || X[R]), ut.type = R, ut.texture = et); + } + function E() { + const R = ct[rt]; + R !== void 0 && R.type !== void 0 && (i.bindTexture(R.type, null), R.type = void 0, R.texture = void 0); + } + function _() { + try { + i.compressedTexImage2D(...arguments); + } catch (R) { + console.error("THREE.WebGLState:", R); + } + } + function I() { + try { + i.compressedTexImage3D(...arguments); + } catch (R) { + console.error("THREE.WebGLState:", R); + } + } + function k() { + try { + i.texSubImage2D(...arguments); + } catch (R) { + console.error("THREE.WebGLState:", R); + } + } + function j() { + try { + i.texSubImage3D(...arguments); + } catch (R) { + console.error("THREE.WebGLState:", R); + } + } + function V() { + try { + i.compressedTexSubImage2D(...arguments); + } catch (R) { + console.error("THREE.WebGLState:", R); + } + } + function Mt() { + try { + i.compressedTexSubImage3D(...arguments); + } catch (R) { + console.error("THREE.WebGLState:", R); + } + } + function nt() { + try { + i.texStorage2D(...arguments); + } catch (R) { + console.error("THREE.WebGLState:", R); + } + } + function gt() { + try { + i.texStorage3D(...arguments); + } catch (R) { + console.error("THREE.WebGLState:", R); + } + } + function vt() { + try { + i.texImage2D(...arguments); + } catch (R) { + console.error("THREE.WebGLState:", R); + } + } + function tt() { + try { + i.texImage3D(...arguments); + } catch (R) { + console.error("THREE.WebGLState:", R); + } + } + function lt(R) { + Zt.equals(R) === !1 && (i.scissor(R.x, R.y, R.z, R.w), Zt.copy(R)); + } + function At(R) { + Qt.equals(R) === !1 && (i.viewport(R.x, R.y, R.z, R.w), Qt.copy(R)); + } + function xt(R, et) { + let it = l.get(et); + it === void 0 && (it = /* @__PURE__ */ new WeakMap(), l.set(et, it)); + let ut = it.get(R); + ut === void 0 && (ut = i.getUniformBlockIndex(et, R.name), it.set(R, ut)); + } + function at(R, et) { + const ut = l.get(et).get(R); + c.get(et) !== ut && (i.uniformBlockBinding(et, ut, R.__bindingPointIndex), c.set(et, ut)); + } + function Ut() { + i.disable(i.BLEND), i.disable(i.CULL_FACE), i.disable(i.DEPTH_TEST), i.disable(i.POLYGON_OFFSET_FILL), i.disable(i.SCISSOR_TEST), i.disable(i.STENCIL_TEST), i.disable(i.SAMPLE_ALPHA_TO_COVERAGE), i.blendEquation(i.FUNC_ADD), i.blendFunc(i.ONE, i.ZERO), i.blendFuncSeparate(i.ONE, i.ZERO, i.ONE, i.ZERO), i.blendColor(0, 0, 0, 0), i.colorMask(!0, !0, !0, !0), i.clearColor(0, 0, 0, 0), i.depthMask(!0), i.depthFunc(i.LESS), a.setReversed(!1), i.clearDepth(1), i.stencilMask(4294967295), i.stencilFunc(i.ALWAYS, 0, 4294967295), i.stencilOp(i.KEEP, i.KEEP, i.KEEP), i.clearStencil(0), i.cullFace(i.BACK), i.frontFace(i.CCW), i.polygonOffset(0, 0), i.activeTexture(i.TEXTURE0), i.bindFramebuffer(i.FRAMEBUFFER, null), i.bindFramebuffer(i.DRAW_FRAMEBUFFER, null), i.bindFramebuffer(i.READ_FRAMEBUFFER, null), i.useProgram(null), i.lineWidth(1), i.scissor(0, 0, i.canvas.width, i.canvas.height), i.viewport(0, 0, i.canvas.width, i.canvas.height), u = {}, rt = null, ct = {}, d = {}, f = /* @__PURE__ */ new WeakMap(), m = [], v = null, x = !1, p = null, h = null, A = null, b = null, y = null, D = null, P = null, w = new Vt(0, 0, 0), F = 0, S = !1, M = null, C = null, z = null, G = null, K = null, Zt.set(0, 0, i.canvas.width, i.canvas.height), Qt.set(0, 0, i.canvas.width, i.canvas.height), r.reset(), a.reset(), o.reset(); + } + return { + buffers: { + color: r, + depth: a, + stencil: o + }, + enable: $, + disable: dt, + bindFramebuffer: Pt, + drawBuffers: St, + useProgram: Ht, + setBlending: te, + setMaterial: Lt, + setFlipSided: Rt, + setCullFace: mt, + setLineWidth: ee, + setPolygonOffset: _t, + setScissorTest: Nt, + activeTexture: de, + bindTexture: oe, + unbindTexture: E, + compressedTexImage2D: _, + compressedTexImage3D: I, + texImage2D: vt, + texImage3D: tt, + updateUBOMapping: xt, + uniformBlockBinding: at, + texStorage2D: nt, + texStorage3D: gt, + texSubImage2D: k, + texSubImage3D: j, + compressedTexSubImage2D: V, + compressedTexSubImage3D: Mt, + scissor: lt, + viewport: At, + reset: Ut + }; +} +function rp(i, t, e, n, s, r, a) { + const o = t.has("WEBGL_multisampled_render_to_texture") ? t.get("WEBGL_multisampled_render_to_texture") : null, c = typeof navigator > "u" ? !1 : /OculusBrowser/g.test(navigator.userAgent), l = new Ct(), u = /* @__PURE__ */ new WeakMap(); + let d; + const f = /* @__PURE__ */ new WeakMap(); + let m = !1; + try { + m = typeof OffscreenCanvas < "u" && new OffscreenCanvas(1, 1).getContext("2d") !== null; + } catch { + } + function v(E, _) { + return m ? ( + // eslint-disable-next-line compat/compat + new OffscreenCanvas(E, _) + ) : os("canvas"); + } + function x(E, _, I) { + let k = 1; + const j = oe(E); + if ((j.width > I || j.height > I) && (k = I / Math.max(j.width, j.height)), k < 1) + if (typeof HTMLImageElement < "u" && E instanceof HTMLImageElement || typeof HTMLCanvasElement < "u" && E instanceof HTMLCanvasElement || typeof ImageBitmap < "u" && E instanceof ImageBitmap || typeof VideoFrame < "u" && E instanceof VideoFrame) { + const V = Math.floor(k * j.width), Mt = Math.floor(k * j.height); + d === void 0 && (d = v(V, Mt)); + const nt = _ ? v(V, Mt) : d; + return nt.width = V, nt.height = Mt, nt.getContext("2d").drawImage(E, 0, 0, V, Mt), console.warn("THREE.WebGLRenderer: Texture has been resized from (" + j.width + "x" + j.height + ") to (" + V + "x" + Mt + ")."), nt; + } else + return "data" in E && console.warn("THREE.WebGLRenderer: Image in DataTexture is too big (" + j.width + "x" + j.height + ")."), E; + return E; + } + function p(E) { + return E.generateMipmaps; + } + function h(E) { + i.generateMipmap(E); + } + function A(E) { + return E.isWebGLCubeRenderTarget ? i.TEXTURE_CUBE_MAP : E.isWebGL3DRenderTarget ? i.TEXTURE_3D : E.isWebGLArrayRenderTarget || E.isCompressedArrayTexture ? i.TEXTURE_2D_ARRAY : i.TEXTURE_2D; + } + function b(E, _, I, k, j = !1) { + if (E !== null) { + if (i[E] !== void 0) return i[E]; + console.warn("THREE.WebGLRenderer: Attempt to use non-existing WebGL internal format '" + E + "'"); + } + let V = _; + if (_ === i.RED && (I === i.FLOAT && (V = i.R32F), I === i.HALF_FLOAT && (V = i.R16F), I === i.UNSIGNED_BYTE && (V = i.R8)), _ === i.RED_INTEGER && (I === i.UNSIGNED_BYTE && (V = i.R8UI), I === i.UNSIGNED_SHORT && (V = i.R16UI), I === i.UNSIGNED_INT && (V = i.R32UI), I === i.BYTE && (V = i.R8I), I === i.SHORT && (V = i.R16I), I === i.INT && (V = i.R32I)), _ === i.RG && (I === i.FLOAT && (V = i.RG32F), I === i.HALF_FLOAT && (V = i.RG16F), I === i.UNSIGNED_BYTE && (V = i.RG8)), _ === i.RG_INTEGER && (I === i.UNSIGNED_BYTE && (V = i.RG8UI), I === i.UNSIGNED_SHORT && (V = i.RG16UI), I === i.UNSIGNED_INT && (V = i.RG32UI), I === i.BYTE && (V = i.RG8I), I === i.SHORT && (V = i.RG16I), I === i.INT && (V = i.RG32I)), _ === i.RGB_INTEGER && (I === i.UNSIGNED_BYTE && (V = i.RGB8UI), I === i.UNSIGNED_SHORT && (V = i.RGB16UI), I === i.UNSIGNED_INT && (V = i.RGB32UI), I === i.BYTE && (V = i.RGB8I), I === i.SHORT && (V = i.RGB16I), I === i.INT && (V = i.RGB32I)), _ === i.RGBA_INTEGER && (I === i.UNSIGNED_BYTE && (V = i.RGBA8UI), I === i.UNSIGNED_SHORT && (V = i.RGBA16UI), I === i.UNSIGNED_INT && (V = i.RGBA32UI), I === i.BYTE && (V = i.RGBA8I), I === i.SHORT && (V = i.RGBA16I), I === i.INT && (V = i.RGBA32I)), _ === i.RGB && (I === i.UNSIGNED_INT_5_9_9_9_REV && (V = i.RGB9_E5), I === i.UNSIGNED_INT_10F_11F_11F_REV && (V = i.R11F_G11F_B10F)), _ === i.RGBA) { + const Mt = j ? rs : kt.getTransfer(k); + I === i.FLOAT && (V = i.RGBA32F), I === i.HALF_FLOAT && (V = i.RGBA16F), I === i.UNSIGNED_BYTE && (V = Mt === qt ? i.SRGB8_ALPHA8 : i.RGBA8), I === i.UNSIGNED_SHORT_4_4_4_4 && (V = i.RGBA4), I === i.UNSIGNED_SHORT_5_5_5_1 && (V = i.RGB5_A1); + } + return (V === i.R16F || V === i.R32F || V === i.RG16F || V === i.RG32F || V === i.RGBA16F || V === i.RGBA32F) && t.get("EXT_color_buffer_float"), V; + } + function y(E, _) { + let I; + return E ? _ === null || _ === Un || _ === vi ? I = i.DEPTH24_STENCIL8 : _ === sn ? I = i.DEPTH32F_STENCIL8 : _ === gi && (I = i.DEPTH24_STENCIL8, console.warn("DepthTexture: 16 bit depth attachment is not supported with stencil. Using 24-bit attachment.")) : _ === null || _ === Un || _ === vi ? I = i.DEPTH_COMPONENT24 : _ === sn ? I = i.DEPTH_COMPONENT32F : _ === gi && (I = i.DEPTH_COMPONENT16), I; + } + function D(E, _) { + return p(E) === !0 || E.isFramebufferTexture && E.minFilter !== Ge && E.minFilter !== Xe ? Math.log2(Math.max(_.width, _.height)) + 1 : E.mipmaps !== void 0 && E.mipmaps.length > 0 ? E.mipmaps.length : E.isCompressedTexture && Array.isArray(E.image) ? _.mipmaps.length : 1; + } + function P(E) { + const _ = E.target; + _.removeEventListener("dispose", P), F(_), _.isVideoTexture && u.delete(_); + } + function w(E) { + const _ = E.target; + _.removeEventListener("dispose", w), M(_); + } + function F(E) { + const _ = n.get(E); + if (_.__webglInit === void 0) return; + const I = E.source, k = f.get(I); + if (k) { + const j = k[_.__cacheKey]; + j.usedTimes--, j.usedTimes === 0 && S(E), Object.keys(k).length === 0 && f.delete(I); + } + n.remove(E); + } + function S(E) { + const _ = n.get(E); + i.deleteTexture(_.__webglTexture); + const I = E.source, k = f.get(I); + delete k[_.__cacheKey], a.memory.textures--; + } + function M(E) { + const _ = n.get(E); + if (E.depthTexture && (E.depthTexture.dispose(), n.remove(E.depthTexture)), E.isWebGLCubeRenderTarget) + for (let k = 0; k < 6; k++) { + if (Array.isArray(_.__webglFramebuffer[k])) + for (let j = 0; j < _.__webglFramebuffer[k].length; j++) i.deleteFramebuffer(_.__webglFramebuffer[k][j]); + else + i.deleteFramebuffer(_.__webglFramebuffer[k]); + _.__webglDepthbuffer && i.deleteRenderbuffer(_.__webglDepthbuffer[k]); + } + else { + if (Array.isArray(_.__webglFramebuffer)) + for (let k = 0; k < _.__webglFramebuffer.length; k++) i.deleteFramebuffer(_.__webglFramebuffer[k]); + else + i.deleteFramebuffer(_.__webglFramebuffer); + if (_.__webglDepthbuffer && i.deleteRenderbuffer(_.__webglDepthbuffer), _.__webglMultisampledFramebuffer && i.deleteFramebuffer(_.__webglMultisampledFramebuffer), _.__webglColorRenderbuffer) + for (let k = 0; k < _.__webglColorRenderbuffer.length; k++) + _.__webglColorRenderbuffer[k] && i.deleteRenderbuffer(_.__webglColorRenderbuffer[k]); + _.__webglDepthRenderbuffer && i.deleteRenderbuffer(_.__webglDepthRenderbuffer); + } + const I = E.textures; + for (let k = 0, j = I.length; k < j; k++) { + const V = n.get(I[k]); + V.__webglTexture && (i.deleteTexture(V.__webglTexture), a.memory.textures--), n.remove(I[k]); + } + n.remove(E); + } + let C = 0; + function z() { + C = 0; + } + function G() { + const E = C; + return E >= s.maxTextures && console.warn("THREE.WebGLTextures: Trying to use " + E + " texture units while this GPU supports only " + s.maxTextures), C += 1, E; + } + function K(E) { + const _ = []; + return _.push(E.wrapS), _.push(E.wrapT), _.push(E.wrapR || 0), _.push(E.magFilter), _.push(E.minFilter), _.push(E.anisotropy), _.push(E.internalFormat), _.push(E.format), _.push(E.type), _.push(E.generateMipmaps), _.push(E.premultiplyAlpha), _.push(E.flipY), _.push(E.unpackAlignment), _.push(E.colorSpace), _.join(); + } + function W(E, _) { + const I = n.get(E); + if (E.isVideoTexture && Nt(E), E.isRenderTargetTexture === !1 && E.isExternalTexture !== !0 && E.version > 0 && I.__version !== E.version) { + const k = E.image; + if (k === null) + console.warn("THREE.WebGLRenderer: Texture marked for update but no image data found."); + else if (k.complete === !1) + console.warn("THREE.WebGLRenderer: Texture marked for update but image is incomplete"); + else { + X(I, E, _); + return; + } + } else E.isExternalTexture && (I.__webglTexture = E.sourceTexture ? E.sourceTexture : null); + e.bindTexture(i.TEXTURE_2D, I.__webglTexture, i.TEXTURE0 + _); + } + function Y(E, _) { + const I = n.get(E); + if (E.isRenderTargetTexture === !1 && E.version > 0 && I.__version !== E.version) { + X(I, E, _); + return; + } + e.bindTexture(i.TEXTURE_2D_ARRAY, I.__webglTexture, i.TEXTURE0 + _); + } + function Z(E, _) { + const I = n.get(E); + if (E.isRenderTargetTexture === !1 && E.version > 0 && I.__version !== E.version) { + X(I, E, _); + return; + } + e.bindTexture(i.TEXTURE_3D, I.__webglTexture, i.TEXTURE0 + _); + } + function H(E, _) { + const I = n.get(E); + if (E.version > 0 && I.__version !== E.version) { + $(I, E, _); + return; + } + e.bindTexture(i.TEXTURE_CUBE_MAP, I.__webglTexture, i.TEXTURE0 + _); + } + const rt = { + [rr]: i.REPEAT, + [Dn]: i.CLAMP_TO_EDGE, + [ar]: i.MIRRORED_REPEAT + }, ct = { + [Ge]: i.NEAREST, + [Ll]: i.NEAREST_MIPMAP_NEAREST, + [Ci]: i.NEAREST_MIPMAP_LINEAR, + [Xe]: i.LINEAR, + [fs]: i.LINEAR_MIPMAP_NEAREST, + [Ln]: i.LINEAR_MIPMAP_LINEAR + }, Et = { + [Fl]: i.NEVER, + [Gl]: i.ALWAYS, + [Ol]: i.LESS, + [To]: i.LEQUAL, + [Bl]: i.EQUAL, + [Vl]: i.GEQUAL, + [zl]: i.GREATER, + [Hl]: i.NOTEQUAL + }; + function Ot(E, _) { + if (_.type === sn && t.has("OES_texture_float_linear") === !1 && (_.magFilter === Xe || _.magFilter === fs || _.magFilter === Ci || _.magFilter === Ln || _.minFilter === Xe || _.minFilter === fs || _.minFilter === Ci || _.minFilter === Ln) && console.warn("THREE.WebGLRenderer: Unable to use linear filtering with floating point textures. OES_texture_float_linear not supported on this device."), i.texParameteri(E, i.TEXTURE_WRAP_S, rt[_.wrapS]), i.texParameteri(E, i.TEXTURE_WRAP_T, rt[_.wrapT]), (E === i.TEXTURE_3D || E === i.TEXTURE_2D_ARRAY) && i.texParameteri(E, i.TEXTURE_WRAP_R, rt[_.wrapR]), i.texParameteri(E, i.TEXTURE_MAG_FILTER, ct[_.magFilter]), i.texParameteri(E, i.TEXTURE_MIN_FILTER, ct[_.minFilter]), _.compareFunction && (i.texParameteri(E, i.TEXTURE_COMPARE_MODE, i.COMPARE_REF_TO_TEXTURE), i.texParameteri(E, i.TEXTURE_COMPARE_FUNC, Et[_.compareFunction])), t.has("EXT_texture_filter_anisotropic") === !0) { + if (_.magFilter === Ge || _.minFilter !== Ci && _.minFilter !== Ln || _.type === sn && t.has("OES_texture_float_linear") === !1) return; + if (_.anisotropy > 1 || n.get(_).__currentAnisotropy) { + const I = t.get("EXT_texture_filter_anisotropic"); + i.texParameterf(E, I.TEXTURE_MAX_ANISOTROPY_EXT, Math.min(_.anisotropy, s.getMaxAnisotropy())), n.get(_).__currentAnisotropy = _.anisotropy; + } + } + } + function Zt(E, _) { + let I = !1; + E.__webglInit === void 0 && (E.__webglInit = !0, _.addEventListener("dispose", P)); + const k = _.source; + let j = f.get(k); + j === void 0 && (j = {}, f.set(k, j)); + const V = K(_); + if (V !== E.__cacheKey) { + j[V] === void 0 && (j[V] = { + texture: i.createTexture(), + usedTimes: 0 + }, a.memory.textures++, I = !0), j[V].usedTimes++; + const Mt = j[E.__cacheKey]; + Mt !== void 0 && (j[E.__cacheKey].usedTimes--, Mt.usedTimes === 0 && S(_)), E.__cacheKey = V, E.__webglTexture = j[V].texture; + } + return I; + } + function Qt(E, _, I) { + return Math.floor(Math.floor(E / I) / _); + } + function Wt(E, _, I, k) { + const V = E.updateRanges; + if (V.length === 0) + e.texSubImage2D(i.TEXTURE_2D, 0, 0, 0, _.width, _.height, I, k, _.data); + else { + V.sort((tt, lt) => tt.start - lt.start); + let Mt = 0; + for (let tt = 1; tt < V.length; tt++) { + const lt = V[Mt], At = V[tt], xt = lt.start + lt.count, at = Qt(At.start, _.width, 4), Ut = Qt(lt.start, _.width, 4); + At.start <= xt + 1 && at === Ut && Qt(At.start + At.count - 1, _.width, 4) === at ? lt.count = Math.max( + lt.count, + At.start + At.count - lt.start + ) : (++Mt, V[Mt] = At); + } + V.length = Mt + 1; + const nt = i.getParameter(i.UNPACK_ROW_LENGTH), gt = i.getParameter(i.UNPACK_SKIP_PIXELS), vt = i.getParameter(i.UNPACK_SKIP_ROWS); + i.pixelStorei(i.UNPACK_ROW_LENGTH, _.width); + for (let tt = 0, lt = V.length; tt < lt; tt++) { + const At = V[tt], xt = Math.floor(At.start / 4), at = Math.ceil(At.count / 4), Ut = xt % _.width, R = Math.floor(xt / _.width), et = at, it = 1; + i.pixelStorei(i.UNPACK_SKIP_PIXELS, Ut), i.pixelStorei(i.UNPACK_SKIP_ROWS, R), e.texSubImage2D(i.TEXTURE_2D, 0, Ut, R, et, it, I, k, _.data); + } + E.clearUpdateRanges(), i.pixelStorei(i.UNPACK_ROW_LENGTH, nt), i.pixelStorei(i.UNPACK_SKIP_PIXELS, gt), i.pixelStorei(i.UNPACK_SKIP_ROWS, vt); + } + } + function X(E, _, I) { + let k = i.TEXTURE_2D; + (_.isDataArrayTexture || _.isCompressedArrayTexture) && (k = i.TEXTURE_2D_ARRAY), _.isData3DTexture && (k = i.TEXTURE_3D); + const j = Zt(E, _), V = _.source; + e.bindTexture(k, E.__webglTexture, i.TEXTURE0 + I); + const Mt = n.get(V); + if (V.version !== Mt.__version || j === !0) { + e.activeTexture(i.TEXTURE0 + I); + const nt = kt.getPrimaries(kt.workingColorSpace), gt = _.colorSpace === mn ? null : kt.getPrimaries(_.colorSpace), vt = _.colorSpace === mn || nt === gt ? i.NONE : i.BROWSER_DEFAULT_WEBGL; + i.pixelStorei(i.UNPACK_FLIP_Y_WEBGL, _.flipY), i.pixelStorei(i.UNPACK_PREMULTIPLY_ALPHA_WEBGL, _.premultiplyAlpha), i.pixelStorei(i.UNPACK_ALIGNMENT, _.unpackAlignment), i.pixelStorei(i.UNPACK_COLORSPACE_CONVERSION_WEBGL, vt); + let tt = x(_.image, !1, s.maxTextureSize); + tt = de(_, tt); + const lt = r.convert(_.format, _.colorSpace), At = r.convert(_.type); + let xt = b(_.internalFormat, lt, At, _.colorSpace, _.isVideoTexture); + Ot(k, _); + let at; + const Ut = _.mipmaps, R = _.isVideoTexture !== !0, et = Mt.__version === void 0 || j === !0, it = V.dataReady, ut = D(_, tt); + if (_.isDepthTexture) + xt = y(_.format === Mi, _.type), et && (R ? e.texStorage2D(i.TEXTURE_2D, 1, xt, tt.width, tt.height) : e.texImage2D(i.TEXTURE_2D, 0, xt, tt.width, tt.height, 0, lt, At, null)); + else if (_.isDataTexture) + if (Ut.length > 0) { + R && et && e.texStorage2D(i.TEXTURE_2D, ut, xt, Ut[0].width, Ut[0].height); + for (let J = 0, q = Ut.length; J < q; J++) + at = Ut[J], R ? it && e.texSubImage2D(i.TEXTURE_2D, J, 0, 0, at.width, at.height, lt, At, at.data) : e.texImage2D(i.TEXTURE_2D, J, xt, at.width, at.height, 0, lt, At, at.data); + _.generateMipmaps = !1; + } else + R ? (et && e.texStorage2D(i.TEXTURE_2D, ut, xt, tt.width, tt.height), it && Wt(_, tt, lt, At)) : e.texImage2D(i.TEXTURE_2D, 0, xt, tt.width, tt.height, 0, lt, At, tt.data); + else if (_.isCompressedTexture) + if (_.isCompressedArrayTexture) { + R && et && e.texStorage3D(i.TEXTURE_2D_ARRAY, ut, xt, Ut[0].width, Ut[0].height, tt.depth); + for (let J = 0, q = Ut.length; J < q; J++) + if (at = Ut[J], _.format !== Ve) + if (lt !== null) + if (R) { + if (it) + if (_.layerUpdates.size > 0) { + const pt = Fa(at.width, at.height, _.format, _.type); + for (const Dt of _.layerUpdates) { + const $t = at.data.subarray( + Dt * pt / at.data.BYTES_PER_ELEMENT, + (Dt + 1) * pt / at.data.BYTES_PER_ELEMENT + ); + e.compressedTexSubImage3D(i.TEXTURE_2D_ARRAY, J, 0, 0, Dt, at.width, at.height, 1, lt, $t); + } + _.clearLayerUpdates(); + } else + e.compressedTexSubImage3D(i.TEXTURE_2D_ARRAY, J, 0, 0, 0, at.width, at.height, tt.depth, lt, at.data); + } else + e.compressedTexImage3D(i.TEXTURE_2D_ARRAY, J, xt, at.width, at.height, tt.depth, 0, at.data, 0, 0); + else + console.warn("THREE.WebGLRenderer: Attempt to load unsupported compressed texture format in .uploadTexture()"); + else + R ? it && e.texSubImage3D(i.TEXTURE_2D_ARRAY, J, 0, 0, 0, at.width, at.height, tt.depth, lt, At, at.data) : e.texImage3D(i.TEXTURE_2D_ARRAY, J, xt, at.width, at.height, tt.depth, 0, lt, At, at.data); + } else { + R && et && e.texStorage2D(i.TEXTURE_2D, ut, xt, Ut[0].width, Ut[0].height); + for (let J = 0, q = Ut.length; J < q; J++) + at = Ut[J], _.format !== Ve ? lt !== null ? R ? it && e.compressedTexSubImage2D(i.TEXTURE_2D, J, 0, 0, at.width, at.height, lt, at.data) : e.compressedTexImage2D(i.TEXTURE_2D, J, xt, at.width, at.height, 0, at.data) : console.warn("THREE.WebGLRenderer: Attempt to load unsupported compressed texture format in .uploadTexture()") : R ? it && e.texSubImage2D(i.TEXTURE_2D, J, 0, 0, at.width, at.height, lt, At, at.data) : e.texImage2D(i.TEXTURE_2D, J, xt, at.width, at.height, 0, lt, At, at.data); + } + else if (_.isDataArrayTexture) + if (R) { + if (et && e.texStorage3D(i.TEXTURE_2D_ARRAY, ut, xt, tt.width, tt.height, tt.depth), it) + if (_.layerUpdates.size > 0) { + const J = Fa(tt.width, tt.height, _.format, _.type); + for (const q of _.layerUpdates) { + const pt = tt.data.subarray( + q * J / tt.data.BYTES_PER_ELEMENT, + (q + 1) * J / tt.data.BYTES_PER_ELEMENT + ); + e.texSubImage3D(i.TEXTURE_2D_ARRAY, 0, 0, 0, q, tt.width, tt.height, 1, lt, At, pt); + } + _.clearLayerUpdates(); + } else + e.texSubImage3D(i.TEXTURE_2D_ARRAY, 0, 0, 0, 0, tt.width, tt.height, tt.depth, lt, At, tt.data); + } else + e.texImage3D(i.TEXTURE_2D_ARRAY, 0, xt, tt.width, tt.height, tt.depth, 0, lt, At, tt.data); + else if (_.isData3DTexture) + R ? (et && e.texStorage3D(i.TEXTURE_3D, ut, xt, tt.width, tt.height, tt.depth), it && e.texSubImage3D(i.TEXTURE_3D, 0, 0, 0, 0, tt.width, tt.height, tt.depth, lt, At, tt.data)) : e.texImage3D(i.TEXTURE_3D, 0, xt, tt.width, tt.height, tt.depth, 0, lt, At, tt.data); + else if (_.isFramebufferTexture) { + if (et) + if (R) + e.texStorage2D(i.TEXTURE_2D, ut, xt, tt.width, tt.height); + else { + let J = tt.width, q = tt.height; + for (let pt = 0; pt < ut; pt++) + e.texImage2D(i.TEXTURE_2D, pt, xt, J, q, 0, lt, At, null), J >>= 1, q >>= 1; + } + } else if (Ut.length > 0) { + if (R && et) { + const J = oe(Ut[0]); + e.texStorage2D(i.TEXTURE_2D, ut, xt, J.width, J.height); + } + for (let J = 0, q = Ut.length; J < q; J++) + at = Ut[J], R ? it && e.texSubImage2D(i.TEXTURE_2D, J, 0, 0, lt, At, at) : e.texImage2D(i.TEXTURE_2D, J, xt, lt, At, at); + _.generateMipmaps = !1; + } else if (R) { + if (et) { + const J = oe(tt); + e.texStorage2D(i.TEXTURE_2D, ut, xt, J.width, J.height); + } + it && e.texSubImage2D(i.TEXTURE_2D, 0, 0, 0, lt, At, tt); + } else + e.texImage2D(i.TEXTURE_2D, 0, xt, lt, At, tt); + p(_) && h(k), Mt.__version = V.version, _.onUpdate && _.onUpdate(_); + } + E.__version = _.version; + } + function $(E, _, I) { + if (_.image.length !== 6) return; + const k = Zt(E, _), j = _.source; + e.bindTexture(i.TEXTURE_CUBE_MAP, E.__webglTexture, i.TEXTURE0 + I); + const V = n.get(j); + if (j.version !== V.__version || k === !0) { + e.activeTexture(i.TEXTURE0 + I); + const Mt = kt.getPrimaries(kt.workingColorSpace), nt = _.colorSpace === mn ? null : kt.getPrimaries(_.colorSpace), gt = _.colorSpace === mn || Mt === nt ? i.NONE : i.BROWSER_DEFAULT_WEBGL; + i.pixelStorei(i.UNPACK_FLIP_Y_WEBGL, _.flipY), i.pixelStorei(i.UNPACK_PREMULTIPLY_ALPHA_WEBGL, _.premultiplyAlpha), i.pixelStorei(i.UNPACK_ALIGNMENT, _.unpackAlignment), i.pixelStorei(i.UNPACK_COLORSPACE_CONVERSION_WEBGL, gt); + const vt = _.isCompressedTexture || _.image[0].isCompressedTexture, tt = _.image[0] && _.image[0].isDataTexture, lt = []; + for (let q = 0; q < 6; q++) + !vt && !tt ? lt[q] = x(_.image[q], !0, s.maxCubemapSize) : lt[q] = tt ? _.image[q].image : _.image[q], lt[q] = de(_, lt[q]); + const At = lt[0], xt = r.convert(_.format, _.colorSpace), at = r.convert(_.type), Ut = b(_.internalFormat, xt, at, _.colorSpace), R = _.isVideoTexture !== !0, et = V.__version === void 0 || k === !0, it = j.dataReady; + let ut = D(_, At); + Ot(i.TEXTURE_CUBE_MAP, _); + let J; + if (vt) { + R && et && e.texStorage2D(i.TEXTURE_CUBE_MAP, ut, Ut, At.width, At.height); + for (let q = 0; q < 6; q++) { + J = lt[q].mipmaps; + for (let pt = 0; pt < J.length; pt++) { + const Dt = J[pt]; + _.format !== Ve ? xt !== null ? R ? it && e.compressedTexSubImage2D(i.TEXTURE_CUBE_MAP_POSITIVE_X + q, pt, 0, 0, Dt.width, Dt.height, xt, Dt.data) : e.compressedTexImage2D(i.TEXTURE_CUBE_MAP_POSITIVE_X + q, pt, Ut, Dt.width, Dt.height, 0, Dt.data) : console.warn("THREE.WebGLRenderer: Attempt to load unsupported compressed texture format in .setTextureCube()") : R ? it && e.texSubImage2D(i.TEXTURE_CUBE_MAP_POSITIVE_X + q, pt, 0, 0, Dt.width, Dt.height, xt, at, Dt.data) : e.texImage2D(i.TEXTURE_CUBE_MAP_POSITIVE_X + q, pt, Ut, Dt.width, Dt.height, 0, xt, at, Dt.data); + } + } + } else { + if (J = _.mipmaps, R && et) { + J.length > 0 && ut++; + const q = oe(lt[0]); + e.texStorage2D(i.TEXTURE_CUBE_MAP, ut, Ut, q.width, q.height); + } + for (let q = 0; q < 6; q++) + if (tt) { + R ? it && e.texSubImage2D(i.TEXTURE_CUBE_MAP_POSITIVE_X + q, 0, 0, 0, lt[q].width, lt[q].height, xt, at, lt[q].data) : e.texImage2D(i.TEXTURE_CUBE_MAP_POSITIVE_X + q, 0, Ut, lt[q].width, lt[q].height, 0, xt, at, lt[q].data); + for (let pt = 0; pt < J.length; pt++) { + const $t = J[pt].image[q].image; + R ? it && e.texSubImage2D(i.TEXTURE_CUBE_MAP_POSITIVE_X + q, pt + 1, 0, 0, $t.width, $t.height, xt, at, $t.data) : e.texImage2D(i.TEXTURE_CUBE_MAP_POSITIVE_X + q, pt + 1, Ut, $t.width, $t.height, 0, xt, at, $t.data); + } + } else { + R ? it && e.texSubImage2D(i.TEXTURE_CUBE_MAP_POSITIVE_X + q, 0, 0, 0, xt, at, lt[q]) : e.texImage2D(i.TEXTURE_CUBE_MAP_POSITIVE_X + q, 0, Ut, xt, at, lt[q]); + for (let pt = 0; pt < J.length; pt++) { + const Dt = J[pt]; + R ? it && e.texSubImage2D(i.TEXTURE_CUBE_MAP_POSITIVE_X + q, pt + 1, 0, 0, xt, at, Dt.image[q]) : e.texImage2D(i.TEXTURE_CUBE_MAP_POSITIVE_X + q, pt + 1, Ut, xt, at, Dt.image[q]); + } + } + } + p(_) && h(i.TEXTURE_CUBE_MAP), V.__version = j.version, _.onUpdate && _.onUpdate(_); + } + E.__version = _.version; + } + function dt(E, _, I, k, j, V) { + const Mt = r.convert(I.format, I.colorSpace), nt = r.convert(I.type), gt = b(I.internalFormat, Mt, nt, I.colorSpace), vt = n.get(_), tt = n.get(I); + if (tt.__renderTarget = _, !vt.__hasExternalTextures) { + const lt = Math.max(1, _.width >> V), At = Math.max(1, _.height >> V); + j === i.TEXTURE_3D || j === i.TEXTURE_2D_ARRAY ? e.texImage3D(j, V, gt, lt, At, _.depth, 0, Mt, nt, null) : e.texImage2D(j, V, gt, lt, At, 0, Mt, nt, null); + } + e.bindFramebuffer(i.FRAMEBUFFER, E), _t(_) ? o.framebufferTexture2DMultisampleEXT(i.FRAMEBUFFER, k, j, tt.__webglTexture, 0, ee(_)) : (j === i.TEXTURE_2D || j >= i.TEXTURE_CUBE_MAP_POSITIVE_X && j <= i.TEXTURE_CUBE_MAP_NEGATIVE_Z) && i.framebufferTexture2D(i.FRAMEBUFFER, k, j, tt.__webglTexture, V), e.bindFramebuffer(i.FRAMEBUFFER, null); + } + function Pt(E, _, I) { + if (i.bindRenderbuffer(i.RENDERBUFFER, E), _.depthBuffer) { + const k = _.depthTexture, j = k && k.isDepthTexture ? k.type : null, V = y(_.stencilBuffer, j), Mt = _.stencilBuffer ? i.DEPTH_STENCIL_ATTACHMENT : i.DEPTH_ATTACHMENT, nt = ee(_); + _t(_) ? o.renderbufferStorageMultisampleEXT(i.RENDERBUFFER, nt, V, _.width, _.height) : I ? i.renderbufferStorageMultisample(i.RENDERBUFFER, nt, V, _.width, _.height) : i.renderbufferStorage(i.RENDERBUFFER, V, _.width, _.height), i.framebufferRenderbuffer(i.FRAMEBUFFER, Mt, i.RENDERBUFFER, E); + } else { + const k = _.textures; + for (let j = 0; j < k.length; j++) { + const V = k[j], Mt = r.convert(V.format, V.colorSpace), nt = r.convert(V.type), gt = b(V.internalFormat, Mt, nt, V.colorSpace), vt = ee(_); + I && _t(_) === !1 ? i.renderbufferStorageMultisample(i.RENDERBUFFER, vt, gt, _.width, _.height) : _t(_) ? o.renderbufferStorageMultisampleEXT(i.RENDERBUFFER, vt, gt, _.width, _.height) : i.renderbufferStorage(i.RENDERBUFFER, gt, _.width, _.height); + } + } + i.bindRenderbuffer(i.RENDERBUFFER, null); + } + function St(E, _) { + if (_ && _.isWebGLCubeRenderTarget) throw new Error("Depth Texture with cube render targets is not supported"); + if (e.bindFramebuffer(i.FRAMEBUFFER, E), !(_.depthTexture && _.depthTexture.isDepthTexture)) + throw new Error("renderTarget.depthTexture must be an instance of THREE.DepthTexture"); + const k = n.get(_.depthTexture); + k.__renderTarget = _, (!k.__webglTexture || _.depthTexture.image.width !== _.width || _.depthTexture.image.height !== _.height) && (_.depthTexture.image.width = _.width, _.depthTexture.image.height = _.height, _.depthTexture.needsUpdate = !0), W(_.depthTexture, 0); + const j = k.__webglTexture, V = ee(_); + if (_.depthTexture.format === xi) + _t(_) ? o.framebufferTexture2DMultisampleEXT(i.FRAMEBUFFER, i.DEPTH_ATTACHMENT, i.TEXTURE_2D, j, 0, V) : i.framebufferTexture2D(i.FRAMEBUFFER, i.DEPTH_ATTACHMENT, i.TEXTURE_2D, j, 0); + else if (_.depthTexture.format === Mi) + _t(_) ? o.framebufferTexture2DMultisampleEXT(i.FRAMEBUFFER, i.DEPTH_STENCIL_ATTACHMENT, i.TEXTURE_2D, j, 0, V) : i.framebufferTexture2D(i.FRAMEBUFFER, i.DEPTH_STENCIL_ATTACHMENT, i.TEXTURE_2D, j, 0); + else + throw new Error("Unknown depthTexture format"); + } + function Ht(E) { + const _ = n.get(E), I = E.isWebGLCubeRenderTarget === !0; + if (_.__boundDepthTexture !== E.depthTexture) { + const k = E.depthTexture; + if (_.__depthDisposeCallback && _.__depthDisposeCallback(), k) { + const j = () => { + delete _.__boundDepthTexture, delete _.__depthDisposeCallback, k.removeEventListener("dispose", j); + }; + k.addEventListener("dispose", j), _.__depthDisposeCallback = j; + } + _.__boundDepthTexture = k; + } + if (E.depthTexture && !_.__autoAllocateDepthBuffer) { + if (I) throw new Error("target.depthTexture not supported in Cube render targets"); + const k = E.texture.mipmaps; + k && k.length > 0 ? St(_.__webglFramebuffer[0], E) : St(_.__webglFramebuffer, E); + } else if (I) { + _.__webglDepthbuffer = []; + for (let k = 0; k < 6; k++) + if (e.bindFramebuffer(i.FRAMEBUFFER, _.__webglFramebuffer[k]), _.__webglDepthbuffer[k] === void 0) + _.__webglDepthbuffer[k] = i.createRenderbuffer(), Pt(_.__webglDepthbuffer[k], E, !1); + else { + const j = E.stencilBuffer ? i.DEPTH_STENCIL_ATTACHMENT : i.DEPTH_ATTACHMENT, V = _.__webglDepthbuffer[k]; + i.bindRenderbuffer(i.RENDERBUFFER, V), i.framebufferRenderbuffer(i.FRAMEBUFFER, j, i.RENDERBUFFER, V); + } + } else { + const k = E.texture.mipmaps; + if (k && k.length > 0 ? e.bindFramebuffer(i.FRAMEBUFFER, _.__webglFramebuffer[0]) : e.bindFramebuffer(i.FRAMEBUFFER, _.__webglFramebuffer), _.__webglDepthbuffer === void 0) + _.__webglDepthbuffer = i.createRenderbuffer(), Pt(_.__webglDepthbuffer, E, !1); + else { + const j = E.stencilBuffer ? i.DEPTH_STENCIL_ATTACHMENT : i.DEPTH_ATTACHMENT, V = _.__webglDepthbuffer; + i.bindRenderbuffer(i.RENDERBUFFER, V), i.framebufferRenderbuffer(i.FRAMEBUFFER, j, i.RENDERBUFFER, V); + } + } + e.bindFramebuffer(i.FRAMEBUFFER, null); + } + function pe(E, _, I) { + const k = n.get(E); + _ !== void 0 && dt(k.__webglFramebuffer, E, E.texture, i.COLOR_ATTACHMENT0, i.TEXTURE_2D, 0), I !== void 0 && Ht(E); + } + function T(E) { + const _ = E.texture, I = n.get(E), k = n.get(_); + E.addEventListener("dispose", w); + const j = E.textures, V = E.isWebGLCubeRenderTarget === !0, Mt = j.length > 1; + if (Mt || (k.__webglTexture === void 0 && (k.__webglTexture = i.createTexture()), k.__version = _.version, a.memory.textures++), V) { + I.__webglFramebuffer = []; + for (let nt = 0; nt < 6; nt++) + if (_.mipmaps && _.mipmaps.length > 0) { + I.__webglFramebuffer[nt] = []; + for (let gt = 0; gt < _.mipmaps.length; gt++) + I.__webglFramebuffer[nt][gt] = i.createFramebuffer(); + } else + I.__webglFramebuffer[nt] = i.createFramebuffer(); + } else { + if (_.mipmaps && _.mipmaps.length > 0) { + I.__webglFramebuffer = []; + for (let nt = 0; nt < _.mipmaps.length; nt++) + I.__webglFramebuffer[nt] = i.createFramebuffer(); + } else + I.__webglFramebuffer = i.createFramebuffer(); + if (Mt) + for (let nt = 0, gt = j.length; nt < gt; nt++) { + const vt = n.get(j[nt]); + vt.__webglTexture === void 0 && (vt.__webglTexture = i.createTexture(), a.memory.textures++); + } + if (E.samples > 0 && _t(E) === !1) { + I.__webglMultisampledFramebuffer = i.createFramebuffer(), I.__webglColorRenderbuffer = [], e.bindFramebuffer(i.FRAMEBUFFER, I.__webglMultisampledFramebuffer); + for (let nt = 0; nt < j.length; nt++) { + const gt = j[nt]; + I.__webglColorRenderbuffer[nt] = i.createRenderbuffer(), i.bindRenderbuffer(i.RENDERBUFFER, I.__webglColorRenderbuffer[nt]); + const vt = r.convert(gt.format, gt.colorSpace), tt = r.convert(gt.type), lt = b(gt.internalFormat, vt, tt, gt.colorSpace, E.isXRRenderTarget === !0), At = ee(E); + i.renderbufferStorageMultisample(i.RENDERBUFFER, At, lt, E.width, E.height), i.framebufferRenderbuffer(i.FRAMEBUFFER, i.COLOR_ATTACHMENT0 + nt, i.RENDERBUFFER, I.__webglColorRenderbuffer[nt]); + } + i.bindRenderbuffer(i.RENDERBUFFER, null), E.depthBuffer && (I.__webglDepthRenderbuffer = i.createRenderbuffer(), Pt(I.__webglDepthRenderbuffer, E, !0)), e.bindFramebuffer(i.FRAMEBUFFER, null); + } + } + if (V) { + e.bindTexture(i.TEXTURE_CUBE_MAP, k.__webglTexture), Ot(i.TEXTURE_CUBE_MAP, _); + for (let nt = 0; nt < 6; nt++) + if (_.mipmaps && _.mipmaps.length > 0) + for (let gt = 0; gt < _.mipmaps.length; gt++) + dt(I.__webglFramebuffer[nt][gt], E, _, i.COLOR_ATTACHMENT0, i.TEXTURE_CUBE_MAP_POSITIVE_X + nt, gt); + else + dt(I.__webglFramebuffer[nt], E, _, i.COLOR_ATTACHMENT0, i.TEXTURE_CUBE_MAP_POSITIVE_X + nt, 0); + p(_) && h(i.TEXTURE_CUBE_MAP), e.unbindTexture(); + } else if (Mt) { + for (let nt = 0, gt = j.length; nt < gt; nt++) { + const vt = j[nt], tt = n.get(vt); + let lt = i.TEXTURE_2D; + (E.isWebGL3DRenderTarget || E.isWebGLArrayRenderTarget) && (lt = E.isWebGL3DRenderTarget ? i.TEXTURE_3D : i.TEXTURE_2D_ARRAY), e.bindTexture(lt, tt.__webglTexture), Ot(lt, vt), dt(I.__webglFramebuffer, E, vt, i.COLOR_ATTACHMENT0 + nt, lt, 0), p(vt) && h(lt); + } + e.unbindTexture(); + } else { + let nt = i.TEXTURE_2D; + if ((E.isWebGL3DRenderTarget || E.isWebGLArrayRenderTarget) && (nt = E.isWebGL3DRenderTarget ? i.TEXTURE_3D : i.TEXTURE_2D_ARRAY), e.bindTexture(nt, k.__webglTexture), Ot(nt, _), _.mipmaps && _.mipmaps.length > 0) + for (let gt = 0; gt < _.mipmaps.length; gt++) + dt(I.__webglFramebuffer[gt], E, _, i.COLOR_ATTACHMENT0, nt, gt); + else + dt(I.__webglFramebuffer, E, _, i.COLOR_ATTACHMENT0, nt, 0); + p(_) && h(nt), e.unbindTexture(); + } + E.depthBuffer && Ht(E); + } + function te(E) { + const _ = E.textures; + for (let I = 0, k = _.length; I < k; I++) { + const j = _[I]; + if (p(j)) { + const V = A(E), Mt = n.get(j).__webglTexture; + e.bindTexture(V, Mt), h(V), e.unbindTexture(); + } + } + } + const Lt = [], Rt = []; + function mt(E) { + if (E.samples > 0) { + if (_t(E) === !1) { + const _ = E.textures, I = E.width, k = E.height; + let j = i.COLOR_BUFFER_BIT; + const V = E.stencilBuffer ? i.DEPTH_STENCIL_ATTACHMENT : i.DEPTH_ATTACHMENT, Mt = n.get(E), nt = _.length > 1; + if (nt) + for (let vt = 0; vt < _.length; vt++) + e.bindFramebuffer(i.FRAMEBUFFER, Mt.__webglMultisampledFramebuffer), i.framebufferRenderbuffer(i.FRAMEBUFFER, i.COLOR_ATTACHMENT0 + vt, i.RENDERBUFFER, null), e.bindFramebuffer(i.FRAMEBUFFER, Mt.__webglFramebuffer), i.framebufferTexture2D(i.DRAW_FRAMEBUFFER, i.COLOR_ATTACHMENT0 + vt, i.TEXTURE_2D, null, 0); + e.bindFramebuffer(i.READ_FRAMEBUFFER, Mt.__webglMultisampledFramebuffer); + const gt = E.texture.mipmaps; + gt && gt.length > 0 ? e.bindFramebuffer(i.DRAW_FRAMEBUFFER, Mt.__webglFramebuffer[0]) : e.bindFramebuffer(i.DRAW_FRAMEBUFFER, Mt.__webglFramebuffer); + for (let vt = 0; vt < _.length; vt++) { + if (E.resolveDepthBuffer && (E.depthBuffer && (j |= i.DEPTH_BUFFER_BIT), E.stencilBuffer && E.resolveStencilBuffer && (j |= i.STENCIL_BUFFER_BIT)), nt) { + i.framebufferRenderbuffer(i.READ_FRAMEBUFFER, i.COLOR_ATTACHMENT0, i.RENDERBUFFER, Mt.__webglColorRenderbuffer[vt]); + const tt = n.get(_[vt]).__webglTexture; + i.framebufferTexture2D(i.DRAW_FRAMEBUFFER, i.COLOR_ATTACHMENT0, i.TEXTURE_2D, tt, 0); + } + i.blitFramebuffer(0, 0, I, k, 0, 0, I, k, j, i.NEAREST), c === !0 && (Lt.length = 0, Rt.length = 0, Lt.push(i.COLOR_ATTACHMENT0 + vt), E.depthBuffer && E.resolveDepthBuffer === !1 && (Lt.push(V), Rt.push(V), i.invalidateFramebuffer(i.DRAW_FRAMEBUFFER, Rt)), i.invalidateFramebuffer(i.READ_FRAMEBUFFER, Lt)); + } + if (e.bindFramebuffer(i.READ_FRAMEBUFFER, null), e.bindFramebuffer(i.DRAW_FRAMEBUFFER, null), nt) + for (let vt = 0; vt < _.length; vt++) { + e.bindFramebuffer(i.FRAMEBUFFER, Mt.__webglMultisampledFramebuffer), i.framebufferRenderbuffer(i.FRAMEBUFFER, i.COLOR_ATTACHMENT0 + vt, i.RENDERBUFFER, Mt.__webglColorRenderbuffer[vt]); + const tt = n.get(_[vt]).__webglTexture; + e.bindFramebuffer(i.FRAMEBUFFER, Mt.__webglFramebuffer), i.framebufferTexture2D(i.DRAW_FRAMEBUFFER, i.COLOR_ATTACHMENT0 + vt, i.TEXTURE_2D, tt, 0); + } + e.bindFramebuffer(i.DRAW_FRAMEBUFFER, Mt.__webglMultisampledFramebuffer); + } else if (E.depthBuffer && E.resolveDepthBuffer === !1 && c) { + const _ = E.stencilBuffer ? i.DEPTH_STENCIL_ATTACHMENT : i.DEPTH_ATTACHMENT; + i.invalidateFramebuffer(i.DRAW_FRAMEBUFFER, [_]); + } + } + } + function ee(E) { + return Math.min(s.maxSamples, E.samples); + } + function _t(E) { + const _ = n.get(E); + return E.samples > 0 && t.has("WEBGL_multisampled_render_to_texture") === !0 && _.__useRenderToTexture !== !1; + } + function Nt(E) { + const _ = a.render.frame; + u.get(E) !== _ && (u.set(E, _), E.update()); + } + function de(E, _) { + const I = E.colorSpace, k = E.format, j = E.type; + return E.isCompressedTexture === !0 || E.isVideoTexture === !0 || I !== oi && I !== mn && (kt.getTransfer(I) === qt ? (k !== Ve || j !== Ke) && console.warn("THREE.WebGLTextures: sRGB encoded textures have to use RGBAFormat and UnsignedByteType.") : console.error("THREE.WebGLTextures: Unsupported texture color space:", I)), _; + } + function oe(E) { + return typeof HTMLImageElement < "u" && E instanceof HTMLImageElement ? (l.width = E.naturalWidth || E.width, l.height = E.naturalHeight || E.height) : typeof VideoFrame < "u" && E instanceof VideoFrame ? (l.width = E.displayWidth, l.height = E.displayHeight) : (l.width = E.width, l.height = E.height), l; + } + this.allocateTextureUnit = G, this.resetTextureUnits = z, this.setTexture2D = W, this.setTexture2DArray = Y, this.setTexture3D = Z, this.setTextureCube = H, this.rebindTextures = pe, this.setupRenderTarget = T, this.updateRenderTargetMipmap = te, this.updateMultisampleRenderTarget = mt, this.setupDepthRenderbuffer = Ht, this.setupFrameBufferTexture = dt, this.useMultisampledRTT = _t; +} +function ap(i, t) { + function e(n, s = mn) { + let r; + const a = kt.getTransfer(s); + if (n === Ke) return i.UNSIGNED_BYTE; + if (n === Vr) return i.UNSIGNED_SHORT_4_4_4_4; + if (n === Gr) return i.UNSIGNED_SHORT_5_5_5_1; + if (n === go) return i.UNSIGNED_INT_5_9_9_9_REV; + if (n === vo) return i.UNSIGNED_INT_10F_11F_11F_REV; + if (n === mo) return i.BYTE; + if (n === _o) return i.SHORT; + if (n === gi) return i.UNSIGNED_SHORT; + if (n === Hr) return i.INT; + if (n === Un) return i.UNSIGNED_INT; + if (n === sn) return i.FLOAT; + if (n === Ei) return i.HALF_FLOAT; + if (n === xo) return i.ALPHA; + if (n === Mo) return i.RGB; + if (n === Ve) return i.RGBA; + if (n === xi) return i.DEPTH_COMPONENT; + if (n === Mi) return i.DEPTH_STENCIL; + if (n === So) return i.RED; + if (n === kr) return i.RED_INTEGER; + if (n === Eo) return i.RG; + if (n === Wr) return i.RG_INTEGER; + if (n === Xr) return i.RGBA_INTEGER; + if (n === Qi || n === ts || n === es || n === ns) + if (a === qt) + if (r = t.get("WEBGL_compressed_texture_s3tc_srgb"), r !== null) { + if (n === Qi) return r.COMPRESSED_SRGB_S3TC_DXT1_EXT; + if (n === ts) return r.COMPRESSED_SRGB_ALPHA_S3TC_DXT1_EXT; + if (n === es) return r.COMPRESSED_SRGB_ALPHA_S3TC_DXT3_EXT; + if (n === ns) return r.COMPRESSED_SRGB_ALPHA_S3TC_DXT5_EXT; + } else + return null; + else if (r = t.get("WEBGL_compressed_texture_s3tc"), r !== null) { + if (n === Qi) return r.COMPRESSED_RGB_S3TC_DXT1_EXT; + if (n === ts) return r.COMPRESSED_RGBA_S3TC_DXT1_EXT; + if (n === es) return r.COMPRESSED_RGBA_S3TC_DXT3_EXT; + if (n === ns) return r.COMPRESSED_RGBA_S3TC_DXT5_EXT; + } else + return null; + if (n === or || n === lr || n === cr || n === hr) + if (r = t.get("WEBGL_compressed_texture_pvrtc"), r !== null) { + if (n === or) return r.COMPRESSED_RGB_PVRTC_4BPPV1_IMG; + if (n === lr) return r.COMPRESSED_RGB_PVRTC_2BPPV1_IMG; + if (n === cr) return r.COMPRESSED_RGBA_PVRTC_4BPPV1_IMG; + if (n === hr) return r.COMPRESSED_RGBA_PVRTC_2BPPV1_IMG; + } else + return null; + if (n === ur || n === dr || n === fr) + if (r = t.get("WEBGL_compressed_texture_etc"), r !== null) { + if (n === ur || n === dr) return a === qt ? r.COMPRESSED_SRGB8_ETC2 : r.COMPRESSED_RGB8_ETC2; + if (n === fr) return a === qt ? r.COMPRESSED_SRGB8_ALPHA8_ETC2_EAC : r.COMPRESSED_RGBA8_ETC2_EAC; + } else + return null; + if (n === pr || n === mr || n === _r || n === gr || n === vr || n === xr || n === Mr || n === Sr || n === Er || n === yr || n === Tr || n === br || n === Ar || n === Rr) + if (r = t.get("WEBGL_compressed_texture_astc"), r !== null) { + if (n === pr) return a === qt ? r.COMPRESSED_SRGB8_ALPHA8_ASTC_4x4_KHR : r.COMPRESSED_RGBA_ASTC_4x4_KHR; + if (n === mr) return a === qt ? r.COMPRESSED_SRGB8_ALPHA8_ASTC_5x4_KHR : r.COMPRESSED_RGBA_ASTC_5x4_KHR; + if (n === _r) return a === qt ? r.COMPRESSED_SRGB8_ALPHA8_ASTC_5x5_KHR : r.COMPRESSED_RGBA_ASTC_5x5_KHR; + if (n === gr) return a === qt ? r.COMPRESSED_SRGB8_ALPHA8_ASTC_6x5_KHR : r.COMPRESSED_RGBA_ASTC_6x5_KHR; + if (n === vr) return a === qt ? r.COMPRESSED_SRGB8_ALPHA8_ASTC_6x6_KHR : r.COMPRESSED_RGBA_ASTC_6x6_KHR; + if (n === xr) return a === qt ? r.COMPRESSED_SRGB8_ALPHA8_ASTC_8x5_KHR : r.COMPRESSED_RGBA_ASTC_8x5_KHR; + if (n === Mr) return a === qt ? r.COMPRESSED_SRGB8_ALPHA8_ASTC_8x6_KHR : r.COMPRESSED_RGBA_ASTC_8x6_KHR; + if (n === Sr) return a === qt ? r.COMPRESSED_SRGB8_ALPHA8_ASTC_8x8_KHR : r.COMPRESSED_RGBA_ASTC_8x8_KHR; + if (n === Er) return a === qt ? r.COMPRESSED_SRGB8_ALPHA8_ASTC_10x5_KHR : r.COMPRESSED_RGBA_ASTC_10x5_KHR; + if (n === yr) return a === qt ? r.COMPRESSED_SRGB8_ALPHA8_ASTC_10x6_KHR : r.COMPRESSED_RGBA_ASTC_10x6_KHR; + if (n === Tr) return a === qt ? r.COMPRESSED_SRGB8_ALPHA8_ASTC_10x8_KHR : r.COMPRESSED_RGBA_ASTC_10x8_KHR; + if (n === br) return a === qt ? r.COMPRESSED_SRGB8_ALPHA8_ASTC_10x10_KHR : r.COMPRESSED_RGBA_ASTC_10x10_KHR; + if (n === Ar) return a === qt ? r.COMPRESSED_SRGB8_ALPHA8_ASTC_12x10_KHR : r.COMPRESSED_RGBA_ASTC_12x10_KHR; + if (n === Rr) return a === qt ? r.COMPRESSED_SRGB8_ALPHA8_ASTC_12x12_KHR : r.COMPRESSED_RGBA_ASTC_12x12_KHR; + } else + return null; + if (n === wr || n === Cr || n === Pr) + if (r = t.get("EXT_texture_compression_bptc"), r !== null) { + if (n === wr) return a === qt ? r.COMPRESSED_SRGB_ALPHA_BPTC_UNORM_EXT : r.COMPRESSED_RGBA_BPTC_UNORM_EXT; + if (n === Cr) return r.COMPRESSED_RGB_BPTC_SIGNED_FLOAT_EXT; + if (n === Pr) return r.COMPRESSED_RGB_BPTC_UNSIGNED_FLOAT_EXT; + } else + return null; + if (n === Dr || n === Lr || n === Ur || n === Ir) + if (r = t.get("EXT_texture_compression_rgtc"), r !== null) { + if (n === Dr) return r.COMPRESSED_RED_RGTC1_EXT; + if (n === Lr) return r.COMPRESSED_SIGNED_RED_RGTC1_EXT; + if (n === Ur) return r.COMPRESSED_RED_GREEN_RGTC2_EXT; + if (n === Ir) return r.COMPRESSED_SIGNED_RED_GREEN_RGTC2_EXT; + } else + return null; + return n === vi ? i.UNSIGNED_INT_24_8 : i[n] !== void 0 ? i[n] : null; + } + return { convert: e }; +} +const op = ` +void main() { + + gl_Position = vec4( position, 1.0 ); + +}`, lp = ` +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 cp { + /** + * 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(t, e) { + if (this.texture === null) { + const n = new Io(t.texture); + (t.depthNear !== e.depthNear || t.depthFar !== e.depthFar) && (this.depthNear = t.depthNear, this.depthFar = t.depthFar), this.texture = n; + } + } + /** + * Returns a plane mesh that visualizes the depth texture. + * + * @param {ArrayCamera} cameraXR - The XR camera. + * @return {?Mesh} The plane mesh. + */ + getMesh(t) { + if (this.texture !== null && this.mesh === null) { + const e = t.cameras[0].viewport, n = new xn({ + vertexShader: op, + fragmentShader: lp, + uniforms: { + depthColor: { value: this.texture }, + depthWidth: { value: e.z }, + depthHeight: { value: e.w } + } + }); + this.mesh = new be(new cs(20, 20), n); + } + 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 hp extends Fn { + /** + * Constructs a new WebGL renderer. + * + * @param {WebGLRenderer} renderer - The renderer. + * @param {WebGL2RenderingContext} gl - The rendering context. + */ + constructor(t, e) { + super(); + const n = this; + let s = null, r = 1, a = null, o = "local-floor", c = 1, l = null, u = null, d = null, f = null, m = null, v = null; + const x = typeof XRWebGLBinding < "u", p = new cp(), h = {}, A = e.getContextAttributes(); + let b = null, y = null; + const D = [], P = [], w = new Ct(); + let F = null; + const S = new Ne(); + S.viewport = new re(); + const M = new Ne(); + M.viewport = new re(); + const C = [S, M], z = new wc(); + let G = null, K = null; + this.cameraAutoUpdate = !0, this.enabled = !1, this.isPresenting = !1, this.getController = function(X) { + let $ = D[X]; + return $ === void 0 && ($ = new Ns(), D[X] = $), $.getTargetRaySpace(); + }, this.getControllerGrip = function(X) { + let $ = D[X]; + return $ === void 0 && ($ = new Ns(), D[X] = $), $.getGripSpace(); + }, this.getHand = function(X) { + let $ = D[X]; + return $ === void 0 && ($ = new Ns(), D[X] = $), $.getHandSpace(); + }; + function W(X) { + const $ = P.indexOf(X.inputSource); + if ($ === -1) + return; + const dt = D[$]; + dt !== void 0 && (dt.update(X.inputSource, X.frame, l || a), dt.dispatchEvent({ type: X.type, data: X.inputSource })); + } + function Y() { + s.removeEventListener("select", W), s.removeEventListener("selectstart", W), s.removeEventListener("selectend", W), s.removeEventListener("squeeze", W), s.removeEventListener("squeezestart", W), s.removeEventListener("squeezeend", W), s.removeEventListener("end", Y), s.removeEventListener("inputsourceschange", Z); + for (let X = 0; X < D.length; X++) { + const $ = P[X]; + $ !== null && (P[X] = null, D[X].disconnect($)); + } + G = null, K = null, p.reset(); + for (const X in h) + delete h[X]; + t.setRenderTarget(b), m = null, f = null, d = null, s = null, y = null, Wt.stop(), n.isPresenting = !1, t.setPixelRatio(F), t.setSize(w.width, w.height, !1), n.dispatchEvent({ type: "sessionend" }); + } + this.setFramebufferScaleFactor = function(X) { + r = X, n.isPresenting === !0 && console.warn("THREE.WebXRManager: Cannot change framebuffer scale while presenting."); + }, this.setReferenceSpaceType = function(X) { + o = X, n.isPresenting === !0 && console.warn("THREE.WebXRManager: Cannot change reference space type while presenting."); + }, this.getReferenceSpace = function() { + return l || a; + }, this.setReferenceSpace = function(X) { + l = X; + }, this.getBaseLayer = function() { + return f !== null ? f : m; + }, this.getBinding = function() { + return d === null && x && (d = new XRWebGLBinding(s, e)), d; + }, this.getFrame = function() { + return v; + }, this.getSession = function() { + return s; + }, this.setSession = async function(X) { + if (s = X, s !== null) { + if (b = t.getRenderTarget(), s.addEventListener("select", W), s.addEventListener("selectstart", W), s.addEventListener("selectend", W), s.addEventListener("squeeze", W), s.addEventListener("squeezestart", W), s.addEventListener("squeezeend", W), s.addEventListener("end", Y), s.addEventListener("inputsourceschange", Z), A.xrCompatible !== !0 && await e.makeXRCompatible(), F = t.getPixelRatio(), t.getSize(w), x && "createProjectionLayer" in XRWebGLBinding.prototype) { + let dt = null, Pt = null, St = null; + A.depth && (St = A.stencil ? e.DEPTH24_STENCIL8 : e.DEPTH_COMPONENT24, dt = A.stencil ? Mi : xi, Pt = A.stencil ? vi : Un); + const Ht = { + colorFormat: e.RGBA8, + depthFormat: St, + scaleFactor: r + }; + d = this.getBinding(), f = d.createProjectionLayer(Ht), s.updateRenderState({ layers: [f] }), t.setPixelRatio(1), t.setSize(f.textureWidth, f.textureHeight, !1), y = new Nn( + f.textureWidth, + f.textureHeight, + { + format: Ve, + type: Ke, + depthTexture: new Uo(f.textureWidth, f.textureHeight, Pt, void 0, void 0, void 0, void 0, void 0, void 0, dt), + stencilBuffer: A.stencil, + colorSpace: t.outputColorSpace, + samples: A.antialias ? 4 : 0, + resolveDepthBuffer: f.ignoreDepthValues === !1, + resolveStencilBuffer: f.ignoreDepthValues === !1 + } + ); + } else { + const dt = { + antialias: A.antialias, + alpha: !0, + depth: A.depth, + stencil: A.stencil, + framebufferScaleFactor: r + }; + m = new XRWebGLLayer(s, e, dt), s.updateRenderState({ baseLayer: m }), t.setPixelRatio(1), t.setSize(m.framebufferWidth, m.framebufferHeight, !1), y = new Nn( + m.framebufferWidth, + m.framebufferHeight, + { + format: Ve, + type: Ke, + colorSpace: t.outputColorSpace, + stencilBuffer: A.stencil, + resolveDepthBuffer: m.ignoreDepthValues === !1, + resolveStencilBuffer: m.ignoreDepthValues === !1 + } + ); + } + y.isXRRenderTarget = !0, this.setFoveation(c), l = null, a = await s.requestReferenceSpace(o), Wt.setContext(s), Wt.start(), n.isPresenting = !0, n.dispatchEvent({ type: "sessionstart" }); + } + }, this.getEnvironmentBlendMode = function() { + if (s !== null) + return s.environmentBlendMode; + }, this.getDepthTexture = function() { + return p.getDepthTexture(); + }; + function Z(X) { + for (let $ = 0; $ < X.removed.length; $++) { + const dt = X.removed[$], Pt = P.indexOf(dt); + Pt >= 0 && (P[Pt] = null, D[Pt].disconnect(dt)); + } + for (let $ = 0; $ < X.added.length; $++) { + const dt = X.added[$]; + let Pt = P.indexOf(dt); + if (Pt === -1) { + for (let Ht = 0; Ht < D.length; Ht++) + if (Ht >= P.length) { + P.push(dt), Pt = Ht; + break; + } else if (P[Ht] === null) { + P[Ht] = dt, Pt = Ht; + break; + } + if (Pt === -1) break; + } + const St = D[Pt]; + St && St.connect(dt); + } + } + const H = new N(), rt = new N(); + function ct(X, $, dt) { + H.setFromMatrixPosition($.matrixWorld), rt.setFromMatrixPosition(dt.matrixWorld); + const Pt = H.distanceTo(rt), St = $.projectionMatrix.elements, Ht = dt.projectionMatrix.elements, pe = St[14] / (St[10] - 1), T = St[14] / (St[10] + 1), te = (St[9] + 1) / St[5], Lt = (St[9] - 1) / St[5], Rt = (St[8] - 1) / St[0], mt = (Ht[8] + 1) / Ht[0], ee = pe * Rt, _t = pe * mt, Nt = Pt / (-Rt + mt), de = Nt * -Rt; + if ($.matrixWorld.decompose(X.position, X.quaternion, X.scale), X.translateX(de), X.translateZ(Nt), X.matrixWorld.compose(X.position, X.quaternion, X.scale), X.matrixWorldInverse.copy(X.matrixWorld).invert(), St[10] === -1) + X.projectionMatrix.copy($.projectionMatrix), X.projectionMatrixInverse.copy($.projectionMatrixInverse); + else { + const oe = pe + Nt, E = T + Nt, _ = ee - de, I = _t + (Pt - de), k = te * T / E * oe, j = Lt * T / E * oe; + X.projectionMatrix.makePerspective(_, I, k, j, oe, E), X.projectionMatrixInverse.copy(X.projectionMatrix).invert(); + } + } + function Et(X, $) { + $ === null ? X.matrixWorld.copy(X.matrix) : X.matrixWorld.multiplyMatrices($.matrixWorld, X.matrix), X.matrixWorldInverse.copy(X.matrixWorld).invert(); + } + this.updateCamera = function(X) { + if (s === null) return; + let $ = X.near, dt = X.far; + p.texture !== null && (p.depthNear > 0 && ($ = p.depthNear), p.depthFar > 0 && (dt = p.depthFar)), z.near = M.near = S.near = $, z.far = M.far = S.far = dt, (G !== z.near || K !== z.far) && (s.updateRenderState({ + depthNear: z.near, + depthFar: z.far + }), G = z.near, K = z.far), z.layers.mask = X.layers.mask | 6, S.layers.mask = z.layers.mask & 3, M.layers.mask = z.layers.mask & 5; + const Pt = X.parent, St = z.cameras; + Et(z, Pt); + for (let Ht = 0; Ht < St.length; Ht++) + Et(St[Ht], Pt); + St.length === 2 ? ct(z, S, M) : z.projectionMatrix.copy(S.projectionMatrix), Ot(X, z, Pt); + }; + function Ot(X, $, dt) { + dt === null ? X.matrix.copy($.matrixWorld) : (X.matrix.copy(dt.matrixWorld), X.matrix.invert(), X.matrix.multiply($.matrixWorld)), X.matrix.decompose(X.position, X.quaternion, X.scale), X.updateMatrixWorld(!0), X.projectionMatrix.copy($.projectionMatrix), X.projectionMatrixInverse.copy($.projectionMatrixInverse), X.isPerspectiveCamera && (X.fov = Nr * 2 * Math.atan(1 / X.projectionMatrix.elements[5]), X.zoom = 1); + } + this.getCamera = function() { + return z; + }, this.getFoveation = function() { + if (!(f === null && m === null)) + return c; + }, this.setFoveation = function(X) { + c = X, f !== null && (f.fixedFoveation = X), m !== null && m.fixedFoveation !== void 0 && (m.fixedFoveation = X); + }, this.hasDepthSensing = function() { + return p.texture !== null; + }, this.getDepthSensingMesh = function() { + return p.getMesh(z); + }, this.getCameraTexture = function(X) { + return h[X]; + }; + let Zt = null; + function Qt(X, $) { + if (u = $.getViewerPose(l || a), v = $, u !== null) { + const dt = u.views; + m !== null && (t.setRenderTargetFramebuffer(y, m.framebuffer), t.setRenderTarget(y)); + let Pt = !1; + dt.length !== z.cameras.length && (z.cameras.length = 0, Pt = !0); + for (let T = 0; T < dt.length; T++) { + const te = dt[T]; + let Lt = null; + if (m !== null) + Lt = m.getViewport(te); + else { + const mt = d.getViewSubImage(f, te); + Lt = mt.viewport, T === 0 && (t.setRenderTargetTextures( + y, + mt.colorTexture, + mt.depthStencilTexture + ), t.setRenderTarget(y)); + } + let Rt = C[T]; + Rt === void 0 && (Rt = new Ne(), Rt.layers.enable(T), Rt.viewport = new re(), C[T] = Rt), Rt.matrix.fromArray(te.transform.matrix), Rt.matrix.decompose(Rt.position, Rt.quaternion, Rt.scale), Rt.projectionMatrix.fromArray(te.projectionMatrix), Rt.projectionMatrixInverse.copy(Rt.projectionMatrix).invert(), Rt.viewport.set(Lt.x, Lt.y, Lt.width, Lt.height), T === 0 && (z.matrix.copy(Rt.matrix), z.matrix.decompose(z.position, z.quaternion, z.scale)), Pt === !0 && z.cameras.push(Rt); + } + const St = s.enabledFeatures; + if (St && St.includes("depth-sensing") && s.depthUsage == "gpu-optimized" && x) { + d = n.getBinding(); + const T = d.getDepthInformation(dt[0]); + T && T.isValid && T.texture && p.init(T, s.renderState); + } + if (St && St.includes("camera-access") && x) { + t.state.unbindTexture(), d = n.getBinding(); + for (let T = 0; T < dt.length; T++) { + const te = dt[T].camera; + if (te) { + let Lt = h[te]; + Lt || (Lt = new Io(), h[te] = Lt); + const Rt = d.getCameraImage(te); + Lt.sourceTexture = Rt; + } + } + } + } + for (let dt = 0; dt < D.length; dt++) { + const Pt = P[dt], St = D[dt]; + Pt !== null && St !== void 0 && St.update(Pt, $, l || a); + } + Zt && Zt(X, $), $.detectedPlanes && n.dispatchEvent({ type: "planesdetected", data: $ }), v = null; + } + const Wt = new Oo(); + Wt.setAnimationLoop(Qt), this.setAnimationLoop = function(X) { + Zt = X; + }, this.dispose = function() { + }; + } +} +const Rn = /* @__PURE__ */ new je(), up = /* @__PURE__ */ new ae(); +function dp(i, t) { + function e(p, h) { + p.matrixAutoUpdate === !0 && p.updateMatrix(), h.value.copy(p.matrix); + } + function n(p, h) { + h.color.getRGB(p.fogColor.value, Po(i)), h.isFog ? (p.fogNear.value = h.near, p.fogFar.value = h.far) : h.isFogExp2 && (p.fogDensity.value = h.density); + } + function s(p, h, A, b, y) { + h.isMeshBasicMaterial || h.isMeshLambertMaterial ? r(p, h) : h.isMeshToonMaterial ? (r(p, h), d(p, h)) : h.isMeshPhongMaterial ? (r(p, h), u(p, h)) : h.isMeshStandardMaterial ? (r(p, h), f(p, h), h.isMeshPhysicalMaterial && m(p, h, y)) : h.isMeshMatcapMaterial ? (r(p, h), v(p, h)) : h.isMeshDepthMaterial ? r(p, h) : h.isMeshDistanceMaterial ? (r(p, h), x(p, h)) : h.isMeshNormalMaterial ? r(p, h) : h.isLineBasicMaterial ? (a(p, h), h.isLineDashedMaterial && o(p, h)) : h.isPointsMaterial ? c(p, h, A, b) : h.isSpriteMaterial ? l(p, h) : h.isShadowMaterial ? (p.color.value.copy(h.color), p.opacity.value = h.opacity) : h.isShaderMaterial && (h.uniformsNeedUpdate = !1); + } + function r(p, h) { + p.opacity.value = h.opacity, h.color && p.diffuse.value.copy(h.color), h.emissive && p.emissive.value.copy(h.emissive).multiplyScalar(h.emissiveIntensity), h.map && (p.map.value = h.map, e(h.map, p.mapTransform)), h.alphaMap && (p.alphaMap.value = h.alphaMap, e(h.alphaMap, p.alphaMapTransform)), h.bumpMap && (p.bumpMap.value = h.bumpMap, e(h.bumpMap, p.bumpMapTransform), p.bumpScale.value = h.bumpScale, h.side === Ae && (p.bumpScale.value *= -1)), h.normalMap && (p.normalMap.value = h.normalMap, e(h.normalMap, p.normalMapTransform), p.normalScale.value.copy(h.normalScale), h.side === Ae && p.normalScale.value.negate()), h.displacementMap && (p.displacementMap.value = h.displacementMap, e(h.displacementMap, p.displacementMapTransform), p.displacementScale.value = h.displacementScale, p.displacementBias.value = h.displacementBias), h.emissiveMap && (p.emissiveMap.value = h.emissiveMap, e(h.emissiveMap, p.emissiveMapTransform)), h.specularMap && (p.specularMap.value = h.specularMap, e(h.specularMap, p.specularMapTransform)), h.alphaTest > 0 && (p.alphaTest.value = h.alphaTest); + const A = t.get(h), b = A.envMap, y = A.envMapRotation; + b && (p.envMap.value = b, Rn.copy(y), Rn.x *= -1, Rn.y *= -1, Rn.z *= -1, b.isCubeTexture && b.isRenderTargetTexture === !1 && (Rn.y *= -1, Rn.z *= -1), p.envMapRotation.value.setFromMatrix4(up.makeRotationFromEuler(Rn)), p.flipEnvMap.value = b.isCubeTexture && b.isRenderTargetTexture === !1 ? -1 : 1, p.reflectivity.value = h.reflectivity, p.ior.value = h.ior, p.refractionRatio.value = h.refractionRatio), h.lightMap && (p.lightMap.value = h.lightMap, p.lightMapIntensity.value = h.lightMapIntensity, e(h.lightMap, p.lightMapTransform)), h.aoMap && (p.aoMap.value = h.aoMap, p.aoMapIntensity.value = h.aoMapIntensity, e(h.aoMap, p.aoMapTransform)); + } + function a(p, h) { + p.diffuse.value.copy(h.color), p.opacity.value = h.opacity, h.map && (p.map.value = h.map, e(h.map, p.mapTransform)); + } + function o(p, h) { + p.dashSize.value = h.dashSize, p.totalSize.value = h.dashSize + h.gapSize, p.scale.value = h.scale; + } + function c(p, h, A, b) { + p.diffuse.value.copy(h.color), p.opacity.value = h.opacity, p.size.value = h.size * A, p.scale.value = b * 0.5, h.map && (p.map.value = h.map, e(h.map, p.uvTransform)), h.alphaMap && (p.alphaMap.value = h.alphaMap, e(h.alphaMap, p.alphaMapTransform)), h.alphaTest > 0 && (p.alphaTest.value = h.alphaTest); + } + function l(p, h) { + p.diffuse.value.copy(h.color), p.opacity.value = h.opacity, p.rotation.value = h.rotation, h.map && (p.map.value = h.map, e(h.map, p.mapTransform)), h.alphaMap && (p.alphaMap.value = h.alphaMap, e(h.alphaMap, p.alphaMapTransform)), h.alphaTest > 0 && (p.alphaTest.value = h.alphaTest); + } + function u(p, h) { + p.specular.value.copy(h.specular), p.shininess.value = Math.max(h.shininess, 1e-4); + } + function d(p, h) { + h.gradientMap && (p.gradientMap.value = h.gradientMap); + } + function f(p, h) { + p.metalness.value = h.metalness, h.metalnessMap && (p.metalnessMap.value = h.metalnessMap, e(h.metalnessMap, p.metalnessMapTransform)), p.roughness.value = h.roughness, h.roughnessMap && (p.roughnessMap.value = h.roughnessMap, e(h.roughnessMap, p.roughnessMapTransform)), h.envMap && (p.envMapIntensity.value = h.envMapIntensity); + } + function m(p, h, A) { + p.ior.value = h.ior, h.sheen > 0 && (p.sheenColor.value.copy(h.sheenColor).multiplyScalar(h.sheen), p.sheenRoughness.value = h.sheenRoughness, h.sheenColorMap && (p.sheenColorMap.value = h.sheenColorMap, e(h.sheenColorMap, p.sheenColorMapTransform)), h.sheenRoughnessMap && (p.sheenRoughnessMap.value = h.sheenRoughnessMap, e(h.sheenRoughnessMap, p.sheenRoughnessMapTransform))), h.clearcoat > 0 && (p.clearcoat.value = h.clearcoat, p.clearcoatRoughness.value = h.clearcoatRoughness, h.clearcoatMap && (p.clearcoatMap.value = h.clearcoatMap, e(h.clearcoatMap, p.clearcoatMapTransform)), h.clearcoatRoughnessMap && (p.clearcoatRoughnessMap.value = h.clearcoatRoughnessMap, e(h.clearcoatRoughnessMap, p.clearcoatRoughnessMapTransform)), h.clearcoatNormalMap && (p.clearcoatNormalMap.value = h.clearcoatNormalMap, e(h.clearcoatNormalMap, p.clearcoatNormalMapTransform), p.clearcoatNormalScale.value.copy(h.clearcoatNormalScale), h.side === Ae && p.clearcoatNormalScale.value.negate())), h.dispersion > 0 && (p.dispersion.value = h.dispersion), h.iridescence > 0 && (p.iridescence.value = h.iridescence, p.iridescenceIOR.value = h.iridescenceIOR, p.iridescenceThicknessMinimum.value = h.iridescenceThicknessRange[0], p.iridescenceThicknessMaximum.value = h.iridescenceThicknessRange[1], h.iridescenceMap && (p.iridescenceMap.value = h.iridescenceMap, e(h.iridescenceMap, p.iridescenceMapTransform)), h.iridescenceThicknessMap && (p.iridescenceThicknessMap.value = h.iridescenceThicknessMap, e(h.iridescenceThicknessMap, p.iridescenceThicknessMapTransform))), h.transmission > 0 && (p.transmission.value = h.transmission, p.transmissionSamplerMap.value = A.texture, p.transmissionSamplerSize.value.set(A.width, A.height), h.transmissionMap && (p.transmissionMap.value = h.transmissionMap, e(h.transmissionMap, p.transmissionMapTransform)), p.thickness.value = h.thickness, h.thicknessMap && (p.thicknessMap.value = h.thicknessMap, e(h.thicknessMap, p.thicknessMapTransform)), p.attenuationDistance.value = h.attenuationDistance, p.attenuationColor.value.copy(h.attenuationColor)), h.anisotropy > 0 && (p.anisotropyVector.value.set(h.anisotropy * Math.cos(h.anisotropyRotation), h.anisotropy * Math.sin(h.anisotropyRotation)), h.anisotropyMap && (p.anisotropyMap.value = h.anisotropyMap, e(h.anisotropyMap, p.anisotropyMapTransform))), p.specularIntensity.value = h.specularIntensity, p.specularColor.value.copy(h.specularColor), h.specularColorMap && (p.specularColorMap.value = h.specularColorMap, e(h.specularColorMap, p.specularColorMapTransform)), h.specularIntensityMap && (p.specularIntensityMap.value = h.specularIntensityMap, e(h.specularIntensityMap, p.specularIntensityMapTransform)); + } + function v(p, h) { + h.matcap && (p.matcap.value = h.matcap); + } + function x(p, h) { + const A = t.get(h).light; + p.referencePosition.value.setFromMatrixPosition(A.matrixWorld), p.nearDistance.value = A.shadow.camera.near, p.farDistance.value = A.shadow.camera.far; + } + return { + refreshFogUniforms: n, + refreshMaterialUniforms: s + }; +} +function fp(i, t, e, n) { + let s = {}, r = {}, a = []; + const o = i.getParameter(i.MAX_UNIFORM_BUFFER_BINDINGS); + function c(A, b) { + const y = b.program; + n.uniformBlockBinding(A, y); + } + function l(A, b) { + let y = s[A.id]; + y === void 0 && (v(A), y = u(A), s[A.id] = y, A.addEventListener("dispose", p)); + const D = b.program; + n.updateUBOMapping(A, D); + const P = t.render.frame; + r[A.id] !== P && (f(A), r[A.id] = P); + } + function u(A) { + const b = d(); + A.__bindingPointIndex = b; + const y = i.createBuffer(), D = A.__size, P = A.usage; + return i.bindBuffer(i.UNIFORM_BUFFER, y), i.bufferData(i.UNIFORM_BUFFER, D, P), i.bindBuffer(i.UNIFORM_BUFFER, null), i.bindBufferBase(i.UNIFORM_BUFFER, b, y), y; + } + function d() { + for (let A = 0; A < o; A++) + if (a.indexOf(A) === -1) + return a.push(A), A; + return console.error("THREE.WebGLRenderer: Maximum number of simultaneously usable uniforms groups reached."), 0; + } + function f(A) { + const b = s[A.id], y = A.uniforms, D = A.__cache; + i.bindBuffer(i.UNIFORM_BUFFER, b); + for (let P = 0, w = y.length; P < w; P++) { + const F = Array.isArray(y[P]) ? y[P] : [y[P]]; + for (let S = 0, M = F.length; S < M; S++) { + const C = F[S]; + if (m(C, P, S, D) === !0) { + const z = C.__offset, G = Array.isArray(C.value) ? C.value : [C.value]; + let K = 0; + for (let W = 0; W < G.length; W++) { + const Y = G[W], Z = x(Y); + typeof Y == "number" || typeof Y == "boolean" ? (C.__data[0] = Y, i.bufferSubData(i.UNIFORM_BUFFER, z + K, C.__data)) : Y.isMatrix3 ? (C.__data[0] = Y.elements[0], C.__data[1] = Y.elements[1], C.__data[2] = Y.elements[2], C.__data[3] = 0, C.__data[4] = Y.elements[3], C.__data[5] = Y.elements[4], C.__data[6] = Y.elements[5], C.__data[7] = 0, C.__data[8] = Y.elements[6], C.__data[9] = Y.elements[7], C.__data[10] = Y.elements[8], C.__data[11] = 0) : (Y.toArray(C.__data, K), K += Z.storage / Float32Array.BYTES_PER_ELEMENT); + } + i.bufferSubData(i.UNIFORM_BUFFER, z, C.__data); + } + } + } + i.bindBuffer(i.UNIFORM_BUFFER, null); + } + function m(A, b, y, D) { + const P = A.value, w = b + "_" + y; + if (D[w] === void 0) + return typeof P == "number" || typeof P == "boolean" ? D[w] = P : D[w] = P.clone(), !0; + { + const F = D[w]; + if (typeof P == "number" || typeof P == "boolean") { + if (F !== P) + return D[w] = P, !0; + } else if (F.equals(P) === !1) + return F.copy(P), !0; + } + return !1; + } + function v(A) { + const b = A.uniforms; + let y = 0; + const D = 16; + for (let w = 0, F = b.length; w < F; w++) { + const S = Array.isArray(b[w]) ? b[w] : [b[w]]; + for (let M = 0, C = S.length; M < C; M++) { + const z = S[M], G = Array.isArray(z.value) ? z.value : [z.value]; + for (let K = 0, W = G.length; K < W; K++) { + const Y = G[K], Z = x(Y), H = y % D, rt = H % Z.boundary, ct = H + rt; + y += rt, ct !== 0 && D - ct < Z.storage && (y += D - ct), z.__data = new Float32Array(Z.storage / Float32Array.BYTES_PER_ELEMENT), z.__offset = y, y += Z.storage; + } + } + } + const P = y % D; + return P > 0 && (y += D - P), A.__size = y, A.__cache = {}, this; + } + function x(A) { + const b = { + boundary: 0, + // bytes + storage: 0 + // bytes + }; + return typeof A == "number" || typeof A == "boolean" ? (b.boundary = 4, b.storage = 4) : A.isVector2 ? (b.boundary = 8, b.storage = 8) : A.isVector3 || A.isColor ? (b.boundary = 16, b.storage = 12) : A.isVector4 ? (b.boundary = 16, b.storage = 16) : A.isMatrix3 ? (b.boundary = 48, b.storage = 48) : A.isMatrix4 ? (b.boundary = 64, b.storage = 64) : A.isTexture ? console.warn("THREE.WebGLRenderer: Texture samplers can not be part of an uniforms group.") : console.warn("THREE.WebGLRenderer: Unsupported uniform value type.", A), b; + } + function p(A) { + const b = A.target; + b.removeEventListener("dispose", p); + const y = a.indexOf(b.__bindingPointIndex); + a.splice(y, 1), i.deleteBuffer(s[b.id]), delete s[b.id], delete r[b.id]; + } + function h() { + for (const A in s) + i.deleteBuffer(s[A]); + a = [], s = {}, r = {}; + } + return { + bind: c, + update: l, + dispose: h + }; +} +class pp { + /** + * Constructs a new WebGL renderer. + * + * @param {WebGLRenderer~Options} [parameters] - The configuration parameter. + */ + constructor(t = {}) { + const { + canvas: e = Xl(), + context: n = null, + depth: s = !0, + stencil: r = !1, + alpha: a = !1, + antialias: o = !1, + premultipliedAlpha: c = !0, + preserveDrawingBuffer: l = !1, + powerPreference: u = "default", + failIfMajorPerformanceCaveat: d = !1, + reversedDepthBuffer: f = !1 + } = t; + this.isWebGLRenderer = !0; + let m; + if (n !== null) { + if (typeof WebGLRenderingContext < "u" && n instanceof WebGLRenderingContext) + throw new Error("THREE.WebGLRenderer: WebGL 1 is not supported since r163."); + m = n.getContextAttributes().alpha; + } else + m = a; + const v = new Uint32Array(4), x = new Int32Array(4); + let p = null, h = null; + const A = [], b = []; + this.domElement = e, 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 = gn, this.toneMappingExposure = 1, this.transmissionResolutionScale = 1; + const y = this; + let D = !1; + this._outputColorSpace = Te; + let P = 0, w = 0, F = null, S = -1, M = null; + const C = new re(), z = new re(); + let G = null; + const K = new Vt(0); + let W = 0, Y = e.width, Z = e.height, H = 1, rt = null, ct = null; + const Et = new re(0, 0, Y, Z), Ot = new re(0, 0, Y, Z); + let Zt = !1; + const Qt = new $r(); + let Wt = !1, X = !1; + const $ = new ae(), dt = new N(), Pt = new re(), St = { background: null, fog: null, environment: null, overrideMaterial: null, isScene: !0 }; + let Ht = !1; + function pe() { + return F === null ? H : 1; + } + let T = n; + function te(g, L) { + return e.getContext(g, L); + } + try { + const g = { + alpha: !0, + depth: s, + stencil: r, + antialias: o, + premultipliedAlpha: c, + preserveDrawingBuffer: l, + powerPreference: u, + failIfMajorPerformanceCaveat: d + }; + if ("setAttribute" in e && e.setAttribute("data-engine", `three.js r${Br}`), e.addEventListener("webglcontextlost", it, !1), e.addEventListener("webglcontextrestored", ut, !1), e.addEventListener("webglcontextcreationerror", J, !1), T === null) { + const L = "webgl2"; + if (T = te(L, g), T === null) + throw te(L) ? new Error("Error creating WebGL context with your selected attributes.") : new Error("Error creating WebGL context."); + } + } catch (g) { + throw console.error("THREE.WebGLRenderer: " + g.message), g; + } + let Lt, Rt, mt, ee, _t, Nt, de, oe, E, _, I, k, j, V, Mt, nt, gt, vt, tt, lt, At, xt, at, Ut; + function R() { + Lt = new yd(T), Lt.init(), xt = new ap(T, Lt), Rt = new _d(T, Lt, t, xt), mt = new sp(T, Lt), Rt.reversedDepthBuffer && f && mt.buffers.depth.setReversed(!0), ee = new Ad(T), _t = new Xf(), Nt = new rp(T, Lt, mt, _t, Rt, xt, ee), de = new vd(y), oe = new Ed(y), E = new Lc(T), at = new pd(T, E), _ = new Td(T, E, ee, at), I = new wd(T, _, E, ee), tt = new Rd(T, Rt, Nt), nt = new gd(_t), k = new Wf(y, de, oe, Lt, Rt, at, nt), j = new dp(y, _t), V = new qf(), Mt = new Qf(Lt), vt = new fd(y, de, oe, mt, I, m, c), gt = new np(y, I, Rt), Ut = new fp(T, ee, Rt, mt), lt = new md(T, Lt, ee), At = new bd(T, Lt, ee), ee.programs = k.programs, y.capabilities = Rt, y.extensions = Lt, y.properties = _t, y.renderLists = V, y.shadowMap = gt, y.state = mt, y.info = ee; + } + R(); + const et = new hp(y, T); + this.xr = et, this.getContext = function() { + return T; + }, this.getContextAttributes = function() { + return T.getContextAttributes(); + }, this.forceContextLoss = function() { + const g = Lt.get("WEBGL_lose_context"); + g && g.loseContext(); + }, this.forceContextRestore = function() { + const g = Lt.get("WEBGL_lose_context"); + g && g.restoreContext(); + }, this.getPixelRatio = function() { + return H; + }, this.setPixelRatio = function(g) { + g !== void 0 && (H = g, this.setSize(Y, Z, !1)); + }, this.getSize = function(g) { + return g.set(Y, Z); + }, this.setSize = function(g, L, O = !0) { + if (et.isPresenting) { + console.warn("THREE.WebGLRenderer: Can't change size while VR device is presenting."); + return; + } + Y = g, Z = L, e.width = Math.floor(g * H), e.height = Math.floor(L * H), O === !0 && (e.style.width = g + "px", e.style.height = L + "px"), this.setViewport(0, 0, g, L); + }, this.getDrawingBufferSize = function(g) { + return g.set(Y * H, Z * H).floor(); + }, this.setDrawingBufferSize = function(g, L, O) { + Y = g, Z = L, H = O, e.width = Math.floor(g * O), e.height = Math.floor(L * O), this.setViewport(0, 0, g, L); + }, this.getCurrentViewport = function(g) { + return g.copy(C); + }, this.getViewport = function(g) { + return g.copy(Et); + }, this.setViewport = function(g, L, O, B) { + g.isVector4 ? Et.set(g.x, g.y, g.z, g.w) : Et.set(g, L, O, B), mt.viewport(C.copy(Et).multiplyScalar(H).round()); + }, this.getScissor = function(g) { + return g.copy(Ot); + }, this.setScissor = function(g, L, O, B) { + g.isVector4 ? Ot.set(g.x, g.y, g.z, g.w) : Ot.set(g, L, O, B), mt.scissor(z.copy(Ot).multiplyScalar(H).round()); + }, this.getScissorTest = function() { + return Zt; + }, this.setScissorTest = function(g) { + mt.setScissorTest(Zt = g); + }, this.setOpaqueSort = function(g) { + rt = g; + }, this.setTransparentSort = function(g) { + ct = g; + }, this.getClearColor = function(g) { + return g.copy(vt.getClearColor()); + }, this.setClearColor = function() { + vt.setClearColor(...arguments); + }, this.getClearAlpha = function() { + return vt.getClearAlpha(); + }, this.setClearAlpha = function() { + vt.setClearAlpha(...arguments); + }, this.clear = function(g = !0, L = !0, O = !0) { + let B = 0; + if (g) { + let U = !1; + if (F !== null) { + const Q = F.texture.format; + U = Q === Xr || Q === Wr || Q === kr; + } + if (U) { + const Q = F.texture.type, ot = Q === Ke || Q === Un || Q === gi || Q === vi || Q === Vr || Q === Gr, ft = vt.getClearColor(), ht = vt.getClearAlpha(), bt = ft.r, wt = ft.g, yt = ft.b; + ot ? (v[0] = bt, v[1] = wt, v[2] = yt, v[3] = ht, T.clearBufferuiv(T.COLOR, 0, v)) : (x[0] = bt, x[1] = wt, x[2] = yt, x[3] = ht, T.clearBufferiv(T.COLOR, 0, x)); + } else + B |= T.COLOR_BUFFER_BIT; + } + L && (B |= T.DEPTH_BUFFER_BIT), O && (B |= T.STENCIL_BUFFER_BIT, this.state.buffers.stencil.setMask(4294967295)), T.clear(B); + }, 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() { + e.removeEventListener("webglcontextlost", it, !1), e.removeEventListener("webglcontextrestored", ut, !1), e.removeEventListener("webglcontextcreationerror", J, !1), vt.dispose(), V.dispose(), Mt.dispose(), _t.dispose(), de.dispose(), oe.dispose(), I.dispose(), at.dispose(), Ut.dispose(), k.dispose(), et.dispose(), et.removeEventListener("sessionstart", ke), et.removeEventListener("sessionend", ea), Mn.stop(); + }; + function it(g) { + g.preventDefault(), console.log("THREE.WebGLRenderer: Context Lost."), D = !0; + } + function ut() { + console.log("THREE.WebGLRenderer: Context Restored."), D = !1; + const g = ee.autoReset, L = gt.enabled, O = gt.autoUpdate, B = gt.needsUpdate, U = gt.type; + R(), ee.autoReset = g, gt.enabled = L, gt.autoUpdate = O, gt.needsUpdate = B, gt.type = U; + } + function J(g) { + console.error("THREE.WebGLRenderer: A WebGL context could not be created. Reason: ", g.statusMessage); + } + function q(g) { + const L = g.target; + L.removeEventListener("dispose", q), pt(L); + } + function pt(g) { + Dt(g), _t.remove(g); + } + function Dt(g) { + const L = _t.get(g).programs; + L !== void 0 && (L.forEach(function(O) { + k.releaseProgram(O); + }), g.isShaderMaterial && k.releaseShaderCache(g)); + } + this.renderBufferDirect = function(g, L, O, B, U, Q) { + L === null && (L = St); + const ot = U.isMesh && U.matrixWorld.determinant() < 0, ft = ko(g, L, O, B, U); + mt.setMaterial(B, ot); + let ht = O.index, bt = 1; + if (B.wireframe === !0) { + if (ht = _.getWireframeAttribute(O), ht === void 0) return; + bt = 2; + } + const wt = O.drawRange, yt = O.attributes.position; + let zt = wt.start * bt, Yt = (wt.start + wt.count) * bt; + Q !== null && (zt = Math.max(zt, Q.start * bt), Yt = Math.min(Yt, (Q.start + Q.count) * bt)), ht !== null ? (zt = Math.max(zt, 0), Yt = Math.min(Yt, ht.count)) : yt != null && (zt = Math.max(zt, 0), Yt = Math.min(Yt, yt.count)); + const se = Yt - zt; + if (se < 0 || se === 1 / 0) return; + at.setup(U, B, ft, O, ht); + let Jt, jt = lt; + if (ht !== null && (Jt = E.get(ht), jt = At, jt.setIndex(Jt)), U.isMesh) + B.wireframe === !0 ? (mt.setLineWidth(B.wireframeLinewidth * pe()), jt.setMode(T.LINES)) : jt.setMode(T.TRIANGLES); + else if (U.isLine) { + let Tt = B.linewidth; + Tt === void 0 && (Tt = 1), mt.setLineWidth(Tt * pe()), U.isLineSegments ? jt.setMode(T.LINES) : U.isLineLoop ? jt.setMode(T.LINE_LOOP) : jt.setMode(T.LINE_STRIP); + } else U.isPoints ? jt.setMode(T.POINTS) : U.isSprite && jt.setMode(T.TRIANGLES); + if (U.isBatchedMesh) + if (U._multiDrawInstances !== null) + Si("THREE.WebGLRenderer: renderMultiDrawInstances has been deprecated and will be removed in r184. Append to renderMultiDraw arguments and use indirection."), jt.renderMultiDrawInstances(U._multiDrawStarts, U._multiDrawCounts, U._multiDrawCount, U._multiDrawInstances); + else if (Lt.get("WEBGL_multi_draw")) + jt.renderMultiDraw(U._multiDrawStarts, U._multiDrawCounts, U._multiDrawCount); + else { + const Tt = U._multiDrawStarts, ne = U._multiDrawCounts, Gt = U._multiDrawCount, Re = ht ? E.get(ht).bytesPerElement : 1, On = _t.get(B).currentProgram.getUniforms(); + for (let we = 0; we < Gt; we++) + On.setValue(T, "_gl_DrawID", we), jt.render(Tt[we] / Re, ne[we]); + } + else if (U.isInstancedMesh) + jt.renderInstances(zt, se, U.count); + else if (O.isInstancedBufferGeometry) { + const Tt = O._maxInstanceCount !== void 0 ? O._maxInstanceCount : 1 / 0, ne = Math.min(O.instanceCount, Tt); + jt.renderInstances(zt, se, ne); + } else + jt.render(zt, se); + }; + function $t(g, L, O) { + g.transparent === !0 && g.side === De && g.forceSinglePass === !1 ? (g.side = Ae, g.needsUpdate = !0, wi(g, L, O), g.side = vn, g.needsUpdate = !0, wi(g, L, O), g.side = De) : wi(g, L, O); + } + this.compile = function(g, L, O = null) { + O === null && (O = g), h = Mt.get(O), h.init(L), b.push(h), O.traverseVisible(function(U) { + U.isLight && U.layers.test(L.layers) && (h.pushLight(U), U.castShadow && h.pushShadow(U)); + }), g !== O && g.traverseVisible(function(U) { + U.isLight && U.layers.test(L.layers) && (h.pushLight(U), U.castShadow && h.pushShadow(U)); + }), h.setupLights(); + const B = /* @__PURE__ */ new Set(); + return g.traverse(function(U) { + if (!(U.isMesh || U.isPoints || U.isLine || U.isSprite)) + return; + const Q = U.material; + if (Q) + if (Array.isArray(Q)) + for (let ot = 0; ot < Q.length; ot++) { + const ft = Q[ot]; + $t(ft, O, U), B.add(ft); + } + else + $t(Q, O, U), B.add(Q); + }), h = b.pop(), B; + }, this.compileAsync = function(g, L, O = null) { + const B = this.compile(g, L, O); + return new Promise((U) => { + function Q() { + if (B.forEach(function(ot) { + _t.get(ot).currentProgram.isReady() && B.delete(ot); + }), B.size === 0) { + U(g); + return; + } + setTimeout(Q, 10); + } + Lt.get("KHR_parallel_shader_compile") !== null ? Q() : setTimeout(Q, 10); + }); + }; + let Xt = null; + function Ze(g) { + Xt && Xt(g); + } + function ke() { + Mn.stop(); + } + function ea() { + Mn.start(); + } + const Mn = new Oo(); + Mn.setAnimationLoop(Ze), typeof self < "u" && Mn.setContext(self), this.setAnimationLoop = function(g) { + Xt = g, et.setAnimationLoop(g), g === null ? Mn.stop() : Mn.start(); + }, et.addEventListener("sessionstart", ke), et.addEventListener("sessionend", ea), this.render = function(g, L) { + if (L !== void 0 && L.isCamera !== !0) { + console.error("THREE.WebGLRenderer.render: camera is not an instance of THREE.Camera."); + return; + } + if (D === !0) return; + if (g.matrixWorldAutoUpdate === !0 && g.updateMatrixWorld(), L.parent === null && L.matrixWorldAutoUpdate === !0 && L.updateMatrixWorld(), et.enabled === !0 && et.isPresenting === !0 && (et.cameraAutoUpdate === !0 && et.updateCamera(L), L = et.getCamera()), g.isScene === !0 && g.onBeforeRender(y, g, L, F), h = Mt.get(g, b.length), h.init(L), b.push(h), $.multiplyMatrices(L.projectionMatrix, L.matrixWorldInverse), Qt.setFromProjectionMatrix($, Ye, L.reversedDepth), X = this.localClippingEnabled, Wt = nt.init(this.clippingPlanes, X), p = V.get(g, A.length), p.init(), A.push(p), et.enabled === !0 && et.isPresenting === !0) { + const Q = y.xr.getDepthSensingMesh(); + Q !== null && us(Q, L, -1 / 0, y.sortObjects); + } + us(g, L, 0, y.sortObjects), p.finish(), y.sortObjects === !0 && p.sort(rt, ct), Ht = et.enabled === !1 || et.isPresenting === !1 || et.hasDepthSensing() === !1, Ht && vt.addToRenderList(p, g), this.info.render.frame++, Wt === !0 && nt.beginShadows(); + const O = h.state.shadowsArray; + gt.render(O, g, L), Wt === !0 && nt.endShadows(), this.info.autoReset === !0 && this.info.reset(); + const B = p.opaque, U = p.transmissive; + if (h.setupLights(), L.isArrayCamera) { + const Q = L.cameras; + if (U.length > 0) + for (let ot = 0, ft = Q.length; ot < ft; ot++) { + const ht = Q[ot]; + ia(B, U, g, ht); + } + Ht && vt.render(g); + for (let ot = 0, ft = Q.length; ot < ft; ot++) { + const ht = Q[ot]; + na(p, g, ht, ht.viewport); + } + } else + U.length > 0 && ia(B, U, g, L), Ht && vt.render(g), na(p, g, L); + F !== null && w === 0 && (Nt.updateMultisampleRenderTarget(F), Nt.updateRenderTargetMipmap(F)), g.isScene === !0 && g.onAfterRender(y, g, L), at.resetDefaultState(), S = -1, M = null, b.pop(), b.length > 0 ? (h = b[b.length - 1], Wt === !0 && nt.setGlobalState(y.clippingPlanes, h.state.camera)) : h = null, A.pop(), A.length > 0 ? p = A[A.length - 1] : p = null; + }; + function us(g, L, O, B) { + if (g.visible === !1) return; + if (g.layers.test(L.layers)) { + if (g.isGroup) + O = g.renderOrder; + else if (g.isLOD) + g.autoUpdate === !0 && g.update(L); + else if (g.isLight) + h.pushLight(g), g.castShadow && h.pushShadow(g); + else if (g.isSprite) { + if (!g.frustumCulled || Qt.intersectsSprite(g)) { + B && Pt.setFromMatrixPosition(g.matrixWorld).applyMatrix4($); + const ot = I.update(g), ft = g.material; + ft.visible && p.push(g, ot, ft, O, Pt.z, null); + } + } else if ((g.isMesh || g.isLine || g.isPoints) && (!g.frustumCulled || Qt.intersectsObject(g))) { + const ot = I.update(g), ft = g.material; + if (B && (g.boundingSphere !== void 0 ? (g.boundingSphere === null && g.computeBoundingSphere(), Pt.copy(g.boundingSphere.center)) : (ot.boundingSphere === null && ot.computeBoundingSphere(), Pt.copy(ot.boundingSphere.center)), Pt.applyMatrix4(g.matrixWorld).applyMatrix4($)), Array.isArray(ft)) { + const ht = ot.groups; + for (let bt = 0, wt = ht.length; bt < wt; bt++) { + const yt = ht[bt], zt = ft[yt.materialIndex]; + zt && zt.visible && p.push(g, ot, zt, O, Pt.z, yt); + } + } else ft.visible && p.push(g, ot, ft, O, Pt.z, null); + } + } + const Q = g.children; + for (let ot = 0, ft = Q.length; ot < ft; ot++) + us(Q[ot], L, O, B); + } + function na(g, L, O, B) { + const U = g.opaque, Q = g.transmissive, ot = g.transparent; + h.setupLightsView(O), Wt === !0 && nt.setGlobalState(y.clippingPlanes, O), B && mt.viewport(C.copy(B)), U.length > 0 && Ri(U, L, O), Q.length > 0 && Ri(Q, L, O), ot.length > 0 && Ri(ot, L, O), mt.buffers.depth.setTest(!0), mt.buffers.depth.setMask(!0), mt.buffers.color.setMask(!0), mt.setPolygonOffset(!1); + } + function ia(g, L, O, B) { + if ((O.isScene === !0 ? O.overrideMaterial : null) !== null) + return; + h.state.transmissionRenderTarget[B.id] === void 0 && (h.state.transmissionRenderTarget[B.id] = new Nn(1, 1, { + generateMipmaps: !0, + type: Lt.has("EXT_color_buffer_half_float") || Lt.has("EXT_color_buffer_float") ? Ei : Ke, + minFilter: Ln, + samples: 4, + stencilBuffer: r, + resolveDepthBuffer: !1, + resolveStencilBuffer: !1, + colorSpace: kt.workingColorSpace + })); + const Q = h.state.transmissionRenderTarget[B.id], ot = B.viewport || C; + Q.setSize(ot.z * y.transmissionResolutionScale, ot.w * y.transmissionResolutionScale); + const ft = y.getRenderTarget(), ht = y.getActiveCubeFace(), bt = y.getActiveMipmapLevel(); + y.setRenderTarget(Q), y.getClearColor(K), W = y.getClearAlpha(), W < 1 && y.setClearColor(16777215, 0.5), y.clear(), Ht && vt.render(O); + const wt = y.toneMapping; + y.toneMapping = gn; + const yt = B.viewport; + if (B.viewport !== void 0 && (B.viewport = void 0), h.setupLightsView(B), Wt === !0 && nt.setGlobalState(y.clippingPlanes, B), Ri(g, O, B), Nt.updateMultisampleRenderTarget(Q), Nt.updateRenderTargetMipmap(Q), Lt.has("WEBGL_multisampled_render_to_texture") === !1) { + let zt = !1; + for (let Yt = 0, se = L.length; Yt < se; Yt++) { + const Jt = L[Yt], jt = Jt.object, Tt = Jt.geometry, ne = Jt.material, Gt = Jt.group; + if (ne.side === De && jt.layers.test(B.layers)) { + const Re = ne.side; + ne.side = Ae, ne.needsUpdate = !0, sa(jt, O, B, Tt, ne, Gt), ne.side = Re, ne.needsUpdate = !0, zt = !0; + } + } + zt === !0 && (Nt.updateMultisampleRenderTarget(Q), Nt.updateRenderTargetMipmap(Q)); + } + y.setRenderTarget(ft, ht, bt), y.setClearColor(K, W), yt !== void 0 && (B.viewport = yt), y.toneMapping = wt; + } + function Ri(g, L, O) { + const B = L.isScene === !0 ? L.overrideMaterial : null; + for (let U = 0, Q = g.length; U < Q; U++) { + const ot = g[U], ft = ot.object, ht = ot.geometry, bt = ot.group; + let wt = ot.material; + wt.allowOverride === !0 && B !== null && (wt = B), ft.layers.test(O.layers) && sa(ft, L, O, ht, wt, bt); + } + } + function sa(g, L, O, B, U, Q) { + g.onBeforeRender(y, L, O, B, U, Q), g.modelViewMatrix.multiplyMatrices(O.matrixWorldInverse, g.matrixWorld), g.normalMatrix.getNormalMatrix(g.modelViewMatrix), U.onBeforeRender(y, L, O, B, g, Q), U.transparent === !0 && U.side === De && U.forceSinglePass === !1 ? (U.side = Ae, U.needsUpdate = !0, y.renderBufferDirect(O, L, B, U, g, Q), U.side = vn, U.needsUpdate = !0, y.renderBufferDirect(O, L, B, U, g, Q), U.side = De) : y.renderBufferDirect(O, L, B, U, g, Q), g.onAfterRender(y, L, O, B, U, Q); + } + function wi(g, L, O) { + L.isScene !== !0 && (L = St); + const B = _t.get(g), U = h.state.lights, Q = h.state.shadowsArray, ot = U.state.version, ft = k.getParameters(g, U.state, Q, L, O), ht = k.getProgramCacheKey(ft); + let bt = B.programs; + B.environment = g.isMeshStandardMaterial ? L.environment : null, B.fog = L.fog, B.envMap = (g.isMeshStandardMaterial ? oe : de).get(g.envMap || B.environment), B.envMapRotation = B.environment !== null && g.envMap === null ? L.environmentRotation : g.envMapRotation, bt === void 0 && (g.addEventListener("dispose", q), bt = /* @__PURE__ */ new Map(), B.programs = bt); + let wt = bt.get(ht); + if (wt !== void 0) { + if (B.currentProgram === wt && B.lightsStateVersion === ot) + return aa(g, ft), wt; + } else + ft.uniforms = k.getUniforms(g), g.onBeforeCompile(ft, y), wt = k.acquireProgram(ft, ht), bt.set(ht, wt), B.uniforms = ft.uniforms; + const yt = B.uniforms; + return (!g.isShaderMaterial && !g.isRawShaderMaterial || g.clipping === !0) && (yt.clippingPlanes = nt.uniform), aa(g, ft), B.needsLights = Xo(g), B.lightsStateVersion = ot, B.needsLights && (yt.ambientLightColor.value = U.state.ambient, yt.lightProbe.value = U.state.probe, yt.directionalLights.value = U.state.directional, yt.directionalLightShadows.value = U.state.directionalShadow, yt.spotLights.value = U.state.spot, yt.spotLightShadows.value = U.state.spotShadow, yt.rectAreaLights.value = U.state.rectArea, yt.ltc_1.value = U.state.rectAreaLTC1, yt.ltc_2.value = U.state.rectAreaLTC2, yt.pointLights.value = U.state.point, yt.pointLightShadows.value = U.state.pointShadow, yt.hemisphereLights.value = U.state.hemi, yt.directionalShadowMap.value = U.state.directionalShadowMap, yt.directionalShadowMatrix.value = U.state.directionalShadowMatrix, yt.spotShadowMap.value = U.state.spotShadowMap, yt.spotLightMatrix.value = U.state.spotLightMatrix, yt.spotLightMap.value = U.state.spotLightMap, yt.pointShadowMap.value = U.state.pointShadowMap, yt.pointShadowMatrix.value = U.state.pointShadowMatrix), B.currentProgram = wt, B.uniformsList = null, wt; + } + function ra(g) { + if (g.uniformsList === null) { + const L = g.currentProgram.getUniforms(); + g.uniformsList = ss.seqWithValue(L.seq, g.uniforms); + } + return g.uniformsList; + } + function aa(g, L) { + const O = _t.get(g); + O.outputColorSpace = L.outputColorSpace, O.batching = L.batching, O.batchingColor = L.batchingColor, O.instancing = L.instancing, O.instancingColor = L.instancingColor, O.instancingMorph = L.instancingMorph, O.skinning = L.skinning, O.morphTargets = L.morphTargets, O.morphNormals = L.morphNormals, O.morphColors = L.morphColors, O.morphTargetsCount = L.morphTargetsCount, O.numClippingPlanes = L.numClippingPlanes, O.numIntersection = L.numClipIntersection, O.vertexAlphas = L.vertexAlphas, O.vertexTangents = L.vertexTangents, O.toneMapping = L.toneMapping; + } + function ko(g, L, O, B, U) { + L.isScene !== !0 && (L = St), Nt.resetTextureUnits(); + const Q = L.fog, ot = B.isMeshStandardMaterial ? L.environment : null, ft = F === null ? y.outputColorSpace : F.isXRRenderTarget === !0 ? F.texture.colorSpace : oi, ht = (B.isMeshStandardMaterial ? oe : de).get(B.envMap || ot), bt = B.vertexColors === !0 && !!O.attributes.color && O.attributes.color.itemSize === 4, wt = !!O.attributes.tangent && (!!B.normalMap || B.anisotropy > 0), yt = !!O.morphAttributes.position, zt = !!O.morphAttributes.normal, Yt = !!O.morphAttributes.color; + let se = gn; + B.toneMapped && (F === null || F.isXRRenderTarget === !0) && (se = y.toneMapping); + const Jt = O.morphAttributes.position || O.morphAttributes.normal || O.morphAttributes.color, jt = Jt !== void 0 ? Jt.length : 0, Tt = _t.get(B), ne = h.state.lights; + if (Wt === !0 && (X === !0 || g !== M)) { + const ve = g === M && B.id === S; + nt.setState(B, g, ve); + } + let Gt = !1; + B.version === Tt.__version ? (Tt.needsLights && Tt.lightsStateVersion !== ne.state.version || Tt.outputColorSpace !== ft || U.isBatchedMesh && Tt.batching === !1 || !U.isBatchedMesh && Tt.batching === !0 || U.isBatchedMesh && Tt.batchingColor === !0 && U.colorTexture === null || U.isBatchedMesh && Tt.batchingColor === !1 && U.colorTexture !== null || U.isInstancedMesh && Tt.instancing === !1 || !U.isInstancedMesh && Tt.instancing === !0 || U.isSkinnedMesh && Tt.skinning === !1 || !U.isSkinnedMesh && Tt.skinning === !0 || U.isInstancedMesh && Tt.instancingColor === !0 && U.instanceColor === null || U.isInstancedMesh && Tt.instancingColor === !1 && U.instanceColor !== null || U.isInstancedMesh && Tt.instancingMorph === !0 && U.morphTexture === null || U.isInstancedMesh && Tt.instancingMorph === !1 && U.morphTexture !== null || Tt.envMap !== ht || B.fog === !0 && Tt.fog !== Q || Tt.numClippingPlanes !== void 0 && (Tt.numClippingPlanes !== nt.numPlanes || Tt.numIntersection !== nt.numIntersection) || Tt.vertexAlphas !== bt || Tt.vertexTangents !== wt || Tt.morphTargets !== yt || Tt.morphNormals !== zt || Tt.morphColors !== Yt || Tt.toneMapping !== se || Tt.morphTargetsCount !== jt) && (Gt = !0) : (Gt = !0, Tt.__version = B.version); + let Re = Tt.currentProgram; + Gt === !0 && (Re = wi(B, L, U)); + let On = !1, we = !1, hi = !1; + const ie = Re.getUniforms(), Le = Tt.uniforms; + if (mt.useProgram(Re.program) && (On = !0, we = !0, hi = !0), B.id !== S && (S = B.id, we = !0), On || M !== g) { + mt.buffers.depth.getReversed() && g.reversedDepth !== !0 && (g._reversedDepth = !0, g.updateProjectionMatrix()), ie.setValue(T, "projectionMatrix", g.projectionMatrix), ie.setValue(T, "viewMatrix", g.matrixWorldInverse); + const Se = ie.map.cameraPosition; + Se !== void 0 && Se.setValue(T, dt.setFromMatrixPosition(g.matrixWorld)), Rt.logarithmicDepthBuffer && ie.setValue( + T, + "logDepthBufFC", + 2 / (Math.log(g.far + 1) / Math.LN2) + ), (B.isMeshPhongMaterial || B.isMeshToonMaterial || B.isMeshLambertMaterial || B.isMeshBasicMaterial || B.isMeshStandardMaterial || B.isShaderMaterial) && ie.setValue(T, "isOrthographic", g.isOrthographicCamera === !0), M !== g && (M = g, we = !0, hi = !0); + } + if (U.isSkinnedMesh) { + ie.setOptional(T, U, "bindMatrix"), ie.setOptional(T, U, "bindMatrixInverse"); + const ve = U.skeleton; + ve && (ve.boneTexture === null && ve.computeBoneTexture(), ie.setValue(T, "boneTexture", ve.boneTexture, Nt)); + } + U.isBatchedMesh && (ie.setOptional(T, U, "batchingTexture"), ie.setValue(T, "batchingTexture", U._matricesTexture, Nt), ie.setOptional(T, U, "batchingIdTexture"), ie.setValue(T, "batchingIdTexture", U._indirectTexture, Nt), ie.setOptional(T, U, "batchingColorTexture"), U._colorsTexture !== null && ie.setValue(T, "batchingColorTexture", U._colorsTexture, Nt)); + const Ue = O.morphAttributes; + if ((Ue.position !== void 0 || Ue.normal !== void 0 || Ue.color !== void 0) && tt.update(U, O, Re), (we || Tt.receiveShadow !== U.receiveShadow) && (Tt.receiveShadow = U.receiveShadow, ie.setValue(T, "receiveShadow", U.receiveShadow)), B.isMeshGouraudMaterial && B.envMap !== null && (Le.envMap.value = ht, Le.flipEnvMap.value = ht.isCubeTexture && ht.isRenderTargetTexture === !1 ? -1 : 1), B.isMeshStandardMaterial && B.envMap === null && L.environment !== null && (Le.envMapIntensity.value = L.environmentIntensity), we && (ie.setValue(T, "toneMappingExposure", y.toneMappingExposure), Tt.needsLights && Wo(Le, hi), Q && B.fog === !0 && j.refreshFogUniforms(Le, Q), j.refreshMaterialUniforms(Le, B, H, Z, h.state.transmissionRenderTarget[g.id]), ss.upload(T, ra(Tt), Le, Nt)), B.isShaderMaterial && B.uniformsNeedUpdate === !0 && (ss.upload(T, ra(Tt), Le, Nt), B.uniformsNeedUpdate = !1), B.isSpriteMaterial && ie.setValue(T, "center", U.center), ie.setValue(T, "modelViewMatrix", U.modelViewMatrix), ie.setValue(T, "normalMatrix", U.normalMatrix), ie.setValue(T, "modelMatrix", U.matrixWorld), B.isShaderMaterial || B.isRawShaderMaterial) { + const ve = B.uniformsGroups; + for (let Se = 0, ds = ve.length; Se < ds; Se++) { + const Sn = ve[Se]; + Ut.update(Sn, Re), Ut.bind(Sn, Re); + } + } + return Re; + } + function Wo(g, L) { + g.ambientLightColor.needsUpdate = L, g.lightProbe.needsUpdate = L, g.directionalLights.needsUpdate = L, g.directionalLightShadows.needsUpdate = L, g.pointLights.needsUpdate = L, g.pointLightShadows.needsUpdate = L, g.spotLights.needsUpdate = L, g.spotLightShadows.needsUpdate = L, g.rectAreaLights.needsUpdate = L, g.hemisphereLights.needsUpdate = L; + } + function Xo(g) { + return g.isMeshLambertMaterial || g.isMeshToonMaterial || g.isMeshPhongMaterial || g.isMeshStandardMaterial || g.isShadowMaterial || g.isShaderMaterial && g.lights === !0; + } + this.getActiveCubeFace = function() { + return P; + }, this.getActiveMipmapLevel = function() { + return w; + }, this.getRenderTarget = function() { + return F; + }, this.setRenderTargetTextures = function(g, L, O) { + const B = _t.get(g); + B.__autoAllocateDepthBuffer = g.resolveDepthBuffer === !1, B.__autoAllocateDepthBuffer === !1 && (B.__useRenderToTexture = !1), _t.get(g.texture).__webglTexture = L, _t.get(g.depthTexture).__webglTexture = B.__autoAllocateDepthBuffer ? void 0 : O, B.__hasExternalTextures = !0; + }, this.setRenderTargetFramebuffer = function(g, L) { + const O = _t.get(g); + O.__webglFramebuffer = L, O.__useDefaultFramebuffer = L === void 0; + }; + const Yo = T.createFramebuffer(); + this.setRenderTarget = function(g, L = 0, O = 0) { + F = g, P = L, w = O; + let B = !0, U = null, Q = !1, ot = !1; + if (g) { + const ht = _t.get(g); + if (ht.__useDefaultFramebuffer !== void 0) + mt.bindFramebuffer(T.FRAMEBUFFER, null), B = !1; + else if (ht.__webglFramebuffer === void 0) + Nt.setupRenderTarget(g); + else if (ht.__hasExternalTextures) + Nt.rebindTextures(g, _t.get(g.texture).__webglTexture, _t.get(g.depthTexture).__webglTexture); + else if (g.depthBuffer) { + const yt = g.depthTexture; + if (ht.__boundDepthTexture !== yt) { + if (yt !== null && _t.has(yt) && (g.width !== yt.image.width || g.height !== yt.image.height)) + throw new Error("WebGLRenderTarget: Attached DepthTexture is initialized to the incorrect size."); + Nt.setupDepthRenderbuffer(g); + } + } + const bt = g.texture; + (bt.isData3DTexture || bt.isDataArrayTexture || bt.isCompressedArrayTexture) && (ot = !0); + const wt = _t.get(g).__webglFramebuffer; + g.isWebGLCubeRenderTarget ? (Array.isArray(wt[L]) ? U = wt[L][O] : U = wt[L], Q = !0) : g.samples > 0 && Nt.useMultisampledRTT(g) === !1 ? U = _t.get(g).__webglMultisampledFramebuffer : Array.isArray(wt) ? U = wt[O] : U = wt, C.copy(g.viewport), z.copy(g.scissor), G = g.scissorTest; + } else + C.copy(Et).multiplyScalar(H).floor(), z.copy(Ot).multiplyScalar(H).floor(), G = Zt; + if (O !== 0 && (U = Yo), mt.bindFramebuffer(T.FRAMEBUFFER, U) && B && mt.drawBuffers(g, U), mt.viewport(C), mt.scissor(z), mt.setScissorTest(G), Q) { + const ht = _t.get(g.texture); + T.framebufferTexture2D(T.FRAMEBUFFER, T.COLOR_ATTACHMENT0, T.TEXTURE_CUBE_MAP_POSITIVE_X + L, ht.__webglTexture, O); + } else if (ot) { + const ht = L; + for (let bt = 0; bt < g.textures.length; bt++) { + const wt = _t.get(g.textures[bt]); + T.framebufferTextureLayer(T.FRAMEBUFFER, T.COLOR_ATTACHMENT0 + bt, wt.__webglTexture, O, ht); + } + } else if (g !== null && O !== 0) { + const ht = _t.get(g.texture); + T.framebufferTexture2D(T.FRAMEBUFFER, T.COLOR_ATTACHMENT0, T.TEXTURE_2D, ht.__webglTexture, O); + } + S = -1; + }, this.readRenderTargetPixels = function(g, L, O, B, U, Q, ot, ft = 0) { + if (!(g && g.isWebGLRenderTarget)) { + console.error("THREE.WebGLRenderer.readRenderTargetPixels: renderTarget is not THREE.WebGLRenderTarget."); + return; + } + let ht = _t.get(g).__webglFramebuffer; + if (g.isWebGLCubeRenderTarget && ot !== void 0 && (ht = ht[ot]), ht) { + mt.bindFramebuffer(T.FRAMEBUFFER, ht); + try { + const bt = g.textures[ft], wt = bt.format, yt = bt.type; + if (!Rt.textureFormatReadable(wt)) { + console.error("THREE.WebGLRenderer.readRenderTargetPixels: renderTarget is not in RGBA or implementation defined format."); + return; + } + if (!Rt.textureTypeReadable(yt)) { + console.error("THREE.WebGLRenderer.readRenderTargetPixels: renderTarget is not in UnsignedByteType or implementation defined type."); + return; + } + L >= 0 && L <= g.width - B && O >= 0 && O <= g.height - U && (g.textures.length > 1 && T.readBuffer(T.COLOR_ATTACHMENT0 + ft), T.readPixels(L, O, B, U, xt.convert(wt), xt.convert(yt), Q)); + } finally { + const bt = F !== null ? _t.get(F).__webglFramebuffer : null; + mt.bindFramebuffer(T.FRAMEBUFFER, bt); + } + } + }, this.readRenderTargetPixelsAsync = async function(g, L, O, B, U, Q, ot, ft = 0) { + if (!(g && g.isWebGLRenderTarget)) + throw new Error("THREE.WebGLRenderer.readRenderTargetPixels: renderTarget is not THREE.WebGLRenderTarget."); + let ht = _t.get(g).__webglFramebuffer; + if (g.isWebGLCubeRenderTarget && ot !== void 0 && (ht = ht[ot]), ht) + if (L >= 0 && L <= g.width - B && O >= 0 && O <= g.height - U) { + mt.bindFramebuffer(T.FRAMEBUFFER, ht); + const bt = g.textures[ft], wt = bt.format, yt = bt.type; + if (!Rt.textureFormatReadable(wt)) + throw new Error("THREE.WebGLRenderer.readRenderTargetPixelsAsync: renderTarget is not in RGBA or implementation defined format."); + if (!Rt.textureTypeReadable(yt)) + throw new Error("THREE.WebGLRenderer.readRenderTargetPixelsAsync: renderTarget is not in UnsignedByteType or implementation defined type."); + const zt = T.createBuffer(); + T.bindBuffer(T.PIXEL_PACK_BUFFER, zt), T.bufferData(T.PIXEL_PACK_BUFFER, Q.byteLength, T.STREAM_READ), g.textures.length > 1 && T.readBuffer(T.COLOR_ATTACHMENT0 + ft), T.readPixels(L, O, B, U, xt.convert(wt), xt.convert(yt), 0); + const Yt = F !== null ? _t.get(F).__webglFramebuffer : null; + mt.bindFramebuffer(T.FRAMEBUFFER, Yt); + const se = T.fenceSync(T.SYNC_GPU_COMMANDS_COMPLETE, 0); + return T.flush(), await Yl(T, se, 4), T.bindBuffer(T.PIXEL_PACK_BUFFER, zt), T.getBufferSubData(T.PIXEL_PACK_BUFFER, 0, Q), T.deleteBuffer(zt), T.deleteSync(se), Q; + } else + throw new Error("THREE.WebGLRenderer.readRenderTargetPixelsAsync: requested read bounds are out of range."); + }, this.copyFramebufferToTexture = function(g, L = null, O = 0) { + const B = Math.pow(2, -O), U = Math.floor(g.image.width * B), Q = Math.floor(g.image.height * B), ot = L !== null ? L.x : 0, ft = L !== null ? L.y : 0; + Nt.setTexture2D(g, 0), T.copyTexSubImage2D(T.TEXTURE_2D, O, 0, 0, ot, ft, U, Q), mt.unbindTexture(); + }; + const qo = T.createFramebuffer(), Ko = T.createFramebuffer(); + this.copyTextureToTexture = function(g, L, O = null, B = null, U = 0, Q = null) { + Q === null && (U !== 0 ? (Si("WebGLRenderer: copyTextureToTexture function signature has changed to support src and dst mipmap levels."), Q = U, U = 0) : Q = 0); + let ot, ft, ht, bt, wt, yt, zt, Yt, se; + const Jt = g.isCompressedTexture ? g.mipmaps[Q] : g.image; + if (O !== null) + ot = O.max.x - O.min.x, ft = O.max.y - O.min.y, ht = O.isBox3 ? O.max.z - O.min.z : 1, bt = O.min.x, wt = O.min.y, yt = O.isBox3 ? O.min.z : 0; + else { + const Ue = Math.pow(2, -U); + ot = Math.floor(Jt.width * Ue), ft = Math.floor(Jt.height * Ue), g.isDataArrayTexture ? ht = Jt.depth : g.isData3DTexture ? ht = Math.floor(Jt.depth * Ue) : ht = 1, bt = 0, wt = 0, yt = 0; + } + B !== null ? (zt = B.x, Yt = B.y, se = B.z) : (zt = 0, Yt = 0, se = 0); + const jt = xt.convert(L.format), Tt = xt.convert(L.type); + let ne; + L.isData3DTexture ? (Nt.setTexture3D(L, 0), ne = T.TEXTURE_3D) : L.isDataArrayTexture || L.isCompressedArrayTexture ? (Nt.setTexture2DArray(L, 0), ne = T.TEXTURE_2D_ARRAY) : (Nt.setTexture2D(L, 0), ne = T.TEXTURE_2D), T.pixelStorei(T.UNPACK_FLIP_Y_WEBGL, L.flipY), T.pixelStorei(T.UNPACK_PREMULTIPLY_ALPHA_WEBGL, L.premultiplyAlpha), T.pixelStorei(T.UNPACK_ALIGNMENT, L.unpackAlignment); + const Gt = T.getParameter(T.UNPACK_ROW_LENGTH), Re = T.getParameter(T.UNPACK_IMAGE_HEIGHT), On = T.getParameter(T.UNPACK_SKIP_PIXELS), we = T.getParameter(T.UNPACK_SKIP_ROWS), hi = T.getParameter(T.UNPACK_SKIP_IMAGES); + T.pixelStorei(T.UNPACK_ROW_LENGTH, Jt.width), T.pixelStorei(T.UNPACK_IMAGE_HEIGHT, Jt.height), T.pixelStorei(T.UNPACK_SKIP_PIXELS, bt), T.pixelStorei(T.UNPACK_SKIP_ROWS, wt), T.pixelStorei(T.UNPACK_SKIP_IMAGES, yt); + const ie = g.isDataArrayTexture || g.isData3DTexture, Le = L.isDataArrayTexture || L.isData3DTexture; + if (g.isDepthTexture) { + const Ue = _t.get(g), ve = _t.get(L), Se = _t.get(Ue.__renderTarget), ds = _t.get(ve.__renderTarget); + mt.bindFramebuffer(T.READ_FRAMEBUFFER, Se.__webglFramebuffer), mt.bindFramebuffer(T.DRAW_FRAMEBUFFER, ds.__webglFramebuffer); + for (let Sn = 0; Sn < ht; Sn++) + ie && (T.framebufferTextureLayer(T.READ_FRAMEBUFFER, T.COLOR_ATTACHMENT0, _t.get(g).__webglTexture, U, yt + Sn), T.framebufferTextureLayer(T.DRAW_FRAMEBUFFER, T.COLOR_ATTACHMENT0, _t.get(L).__webglTexture, Q, se + Sn)), T.blitFramebuffer(bt, wt, ot, ft, zt, Yt, ot, ft, T.DEPTH_BUFFER_BIT, T.NEAREST); + mt.bindFramebuffer(T.READ_FRAMEBUFFER, null), mt.bindFramebuffer(T.DRAW_FRAMEBUFFER, null); + } else if (U !== 0 || g.isRenderTargetTexture || _t.has(g)) { + const Ue = _t.get(g), ve = _t.get(L); + mt.bindFramebuffer(T.READ_FRAMEBUFFER, qo), mt.bindFramebuffer(T.DRAW_FRAMEBUFFER, Ko); + for (let Se = 0; Se < ht; Se++) + ie ? T.framebufferTextureLayer(T.READ_FRAMEBUFFER, T.COLOR_ATTACHMENT0, Ue.__webglTexture, U, yt + Se) : T.framebufferTexture2D(T.READ_FRAMEBUFFER, T.COLOR_ATTACHMENT0, T.TEXTURE_2D, Ue.__webglTexture, U), Le ? T.framebufferTextureLayer(T.DRAW_FRAMEBUFFER, T.COLOR_ATTACHMENT0, ve.__webglTexture, Q, se + Se) : T.framebufferTexture2D(T.DRAW_FRAMEBUFFER, T.COLOR_ATTACHMENT0, T.TEXTURE_2D, ve.__webglTexture, Q), U !== 0 ? T.blitFramebuffer(bt, wt, ot, ft, zt, Yt, ot, ft, T.COLOR_BUFFER_BIT, T.NEAREST) : Le ? T.copyTexSubImage3D(ne, Q, zt, Yt, se + Se, bt, wt, ot, ft) : T.copyTexSubImage2D(ne, Q, zt, Yt, bt, wt, ot, ft); + mt.bindFramebuffer(T.READ_FRAMEBUFFER, null), mt.bindFramebuffer(T.DRAW_FRAMEBUFFER, null); + } else + Le ? g.isDataTexture || g.isData3DTexture ? T.texSubImage3D(ne, Q, zt, Yt, se, ot, ft, ht, jt, Tt, Jt.data) : L.isCompressedArrayTexture ? T.compressedTexSubImage3D(ne, Q, zt, Yt, se, ot, ft, ht, jt, Jt.data) : T.texSubImage3D(ne, Q, zt, Yt, se, ot, ft, ht, jt, Tt, Jt) : g.isDataTexture ? T.texSubImage2D(T.TEXTURE_2D, Q, zt, Yt, ot, ft, jt, Tt, Jt.data) : g.isCompressedTexture ? T.compressedTexSubImage2D(T.TEXTURE_2D, Q, zt, Yt, Jt.width, Jt.height, jt, Jt.data) : T.texSubImage2D(T.TEXTURE_2D, Q, zt, Yt, ot, ft, jt, Tt, Jt); + T.pixelStorei(T.UNPACK_ROW_LENGTH, Gt), T.pixelStorei(T.UNPACK_IMAGE_HEIGHT, Re), T.pixelStorei(T.UNPACK_SKIP_PIXELS, On), T.pixelStorei(T.UNPACK_SKIP_ROWS, we), T.pixelStorei(T.UNPACK_SKIP_IMAGES, hi), Q === 0 && L.generateMipmaps && T.generateMipmap(ne), mt.unbindTexture(); + }, this.initRenderTarget = function(g) { + _t.get(g).__webglFramebuffer === void 0 && Nt.setupRenderTarget(g); + }, this.initTexture = function(g) { + g.isCubeTexture ? Nt.setTextureCube(g, 0) : g.isData3DTexture ? Nt.setTexture3D(g, 0) : g.isDataArrayTexture || g.isCompressedArrayTexture ? Nt.setTexture2DArray(g, 0) : Nt.setTexture2D(g, 0), mt.unbindTexture(); + }, this.resetState = function() { + P = 0, w = 0, F = null, mt.reset(), at.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 Ye; + } + /** + * Defines the output color space of the renderer. + * + * @type {SRGBColorSpace|LinearSRGBColorSpace} + * @default SRGBColorSpace + */ + get outputColorSpace() { + return this._outputColorSpace; + } + set outputColorSpace(t) { + this._outputColorSpace = t; + const e = this.getContext(); + e.drawingBufferColorSpace = kt._getDrawingBufferColorSpace(t), e.unpackColorSpace = kt._getUnpackColorSpace(); + } +} +const oo = { type: "change" }, ta = { type: "start" }, Go = { type: "end" }, $i = new Kr(), lo = new pn(), mp = Math.cos(70 * Wl.DEG2RAD), ce = new N(), ye = 2 * Math.PI, Kt = { + NONE: -1, + ROTATE: 0, + DOLLY: 1, + PAN: 2, + TOUCH_ROTATE: 3, + TOUCH_PAN: 4, + TOUCH_DOLLY_PAN: 5, + TOUCH_DOLLY_ROTATE: 6 +}, Xs = 1e-6; +class _p extends Pc { + /** + * 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(t, e = null) { + super(t, e), this.state = Kt.NONE, this.target = new N(), this.cursor = new N(), 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: ei.ROTATE, MIDDLE: ei.DOLLY, RIGHT: ei.PAN }, this.touches = { ONE: Qn.ROTATE, TWO: Qn.DOLLY_PAN }, this.target0 = this.target.clone(), this.position0 = this.object.position.clone(), this.zoom0 = this.object.zoom, this._domElementKeyEvents = null, this._lastPosition = new N(), this._lastQuaternion = new In(), this._lastTargetPosition = new N(), this._quat = new In().setFromUnitVectors(t.up, new N(0, 1, 0)), this._quatInverse = this._quat.clone().invert(), this._spherical = new Na(), this._sphericalDelta = new Na(), this._scale = 1, this._panOffset = new N(), this._rotateStart = new Ct(), this._rotateEnd = new Ct(), this._rotateDelta = new Ct(), this._panStart = new Ct(), this._panEnd = new Ct(), this._panDelta = new Ct(), this._dollyStart = new Ct(), this._dollyEnd = new Ct(), this._dollyDelta = new Ct(), this._dollyDirection = new N(), this._mouse = new Ct(), this._performCursorZoom = !1, this._pointers = [], this._pointerPositions = {}, this._controlActive = !1, this._onPointerMove = vp.bind(this), this._onPointerDown = gp.bind(this), this._onPointerUp = xp.bind(this), this._onContextMenu = Ap.bind(this), this._onMouseWheel = Ep.bind(this), this._onKeyDown = yp.bind(this), this._onTouchStart = Tp.bind(this), this._onTouchMove = bp.bind(this), this._onMouseDown = Mp.bind(this), this._onMouseMove = Sp.bind(this), this._interceptControlDown = Rp.bind(this), this._interceptControlUp = wp.bind(this), this.domElement !== null && this.connect(this.domElement), this.update(); + } + connect(t) { + super.connect(t), 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(t) { + t.addEventListener("keydown", this._onKeyDown), this._domElementKeyEvents = t; + } + /** + * 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(oo), this.update(), this.state = Kt.NONE; + } + update(t = null) { + const e = this.object.position; + ce.copy(e).sub(this.target), ce.applyQuaternion(this._quat), this._spherical.setFromVector3(ce), this.autoRotate && this.state === Kt.NONE && this._rotateLeft(this._getAutoRotationAngle(t)), 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 n = this.minAzimuthAngle, s = this.maxAzimuthAngle; + isFinite(n) && isFinite(s) && (n < -Math.PI ? n += ye : n > Math.PI && (n -= ye), s < -Math.PI ? s += ye : s > Math.PI && (s -= ye), n <= s ? this._spherical.theta = Math.max(n, Math.min(s, this._spherical.theta)) : this._spherical.theta = this._spherical.theta > (n + s) / 2 ? Math.max(n, this._spherical.theta) : Math.min(s, 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 r = !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), r = a != this._spherical.radius; + } + if (ce.setFromSpherical(this._spherical), ce.applyQuaternion(this._quatInverse), e.copy(this.target).add(ce), 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 = ce.length(); + a = this._clampDistance(o * this._scale); + const c = o - a; + this.object.position.addScaledVector(this._dollyDirection, c), this.object.updateMatrixWorld(), r = !!c; + } else if (this.object.isOrthographicCamera) { + const o = new N(this._mouse.x, this._mouse.y, 0); + o.unproject(this.object); + const c = this.object.zoom; + this.object.zoom = Math.max(this.minZoom, Math.min(this.maxZoom, this.object.zoom / this._scale)), this.object.updateProjectionMatrix(), r = c !== this.object.zoom; + const l = new N(this._mouse.x, this._mouse.y, 0); + l.unproject(this.object), this.object.position.sub(l).add(o), this.object.updateMatrixWorld(), a = ce.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) : ($i.origin.copy(this.object.position), $i.direction.set(0, 0, -1).transformDirection(this.object.matrix), Math.abs(this.object.up.dot($i.direction)) < mp ? this.object.lookAt(this.target) : (lo.setFromNormalAndCoplanarPoint(this.object.up, this.target), $i.intersectPlane(lo, 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(), r = !0); + } + return this._scale = 1, this._performCursorZoom = !1, r || this._lastPosition.distanceToSquared(this.object.position) > Xs || 8 * (1 - this._lastQuaternion.dot(this.object.quaternion)) > Xs || this._lastTargetPosition.distanceToSquared(this.target) > Xs ? (this.dispatchEvent(oo), this._lastPosition.copy(this.object.position), this._lastQuaternion.copy(this.object.quaternion), this._lastTargetPosition.copy(this.target), !0) : !1; + } + _getAutoRotationAngle(t) { + return t !== null ? ye / 60 * this.autoRotateSpeed * t : ye / 60 / 60 * this.autoRotateSpeed; + } + _getZoomScale(t) { + const e = Math.abs(t * 0.01); + return Math.pow(0.95, this.zoomSpeed * e); + } + _rotateLeft(t) { + this._sphericalDelta.theta -= t; + } + _rotateUp(t) { + this._sphericalDelta.phi -= t; + } + _panLeft(t, e) { + ce.setFromMatrixColumn(e, 0), ce.multiplyScalar(-t), this._panOffset.add(ce); + } + _panUp(t, e) { + this.screenSpacePanning === !0 ? ce.setFromMatrixColumn(e, 1) : (ce.setFromMatrixColumn(e, 0), ce.crossVectors(this.object.up, ce)), ce.multiplyScalar(t), this._panOffset.add(ce); + } + // deltaX and deltaY are in pixels; right and down are positive + _pan(t, e) { + const n = this.domElement; + if (this.object.isPerspectiveCamera) { + const s = this.object.position; + ce.copy(s).sub(this.target); + let r = ce.length(); + r *= Math.tan(this.object.fov / 2 * Math.PI / 180), this._panLeft(2 * t * r / n.clientHeight, this.object.matrix), this._panUp(2 * e * r / n.clientHeight, this.object.matrix); + } else this.object.isOrthographicCamera ? (this._panLeft(t * (this.object.right - this.object.left) / this.object.zoom / n.clientWidth, this.object.matrix), this._panUp(e * (this.object.top - this.object.bottom) / this.object.zoom / n.clientHeight, this.object.matrix)) : (console.warn("WARNING: OrbitControls.js encountered an unknown camera type - pan disabled."), this.enablePan = !1); + } + _dollyOut(t) { + this.object.isPerspectiveCamera || this.object.isOrthographicCamera ? this._scale /= t : (console.warn("WARNING: OrbitControls.js encountered an unknown camera type - dolly/zoom disabled."), this.enableZoom = !1); + } + _dollyIn(t) { + this.object.isPerspectiveCamera || this.object.isOrthographicCamera ? this._scale *= t : (console.warn("WARNING: OrbitControls.js encountered an unknown camera type - dolly/zoom disabled."), this.enableZoom = !1); + } + _updateZoomParameters(t, e) { + if (!this.zoomToCursor) + return; + this._performCursorZoom = !0; + const n = this.domElement.getBoundingClientRect(), s = t - n.left, r = e - n.top, a = n.width, o = n.height; + this._mouse.x = s / a * 2 - 1, this._mouse.y = -(r / o) * 2 + 1, this._dollyDirection.set(this._mouse.x, this._mouse.y, 1).unproject(this.object).sub(this.object.position).normalize(); + } + _clampDistance(t) { + return Math.max(this.minDistance, Math.min(this.maxDistance, t)); + } + // + // event callbacks - update the object state + // + _handleMouseDownRotate(t) { + this._rotateStart.set(t.clientX, t.clientY); + } + _handleMouseDownDolly(t) { + this._updateZoomParameters(t.clientX, t.clientX), this._dollyStart.set(t.clientX, t.clientY); + } + _handleMouseDownPan(t) { + this._panStart.set(t.clientX, t.clientY); + } + _handleMouseMoveRotate(t) { + this._rotateEnd.set(t.clientX, t.clientY), this._rotateDelta.subVectors(this._rotateEnd, this._rotateStart).multiplyScalar(this.rotateSpeed); + const e = this.domElement; + this._rotateLeft(ye * this._rotateDelta.x / e.clientHeight), this._rotateUp(ye * this._rotateDelta.y / e.clientHeight), this._rotateStart.copy(this._rotateEnd), this.update(); + } + _handleMouseMoveDolly(t) { + this._dollyEnd.set(t.clientX, t.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(t) { + this._panEnd.set(t.clientX, t.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(t) { + this._updateZoomParameters(t.clientX, t.clientY), t.deltaY < 0 ? this._dollyIn(this._getZoomScale(t.deltaY)) : t.deltaY > 0 && this._dollyOut(this._getZoomScale(t.deltaY)), this.update(); + } + _handleKeyDown(t) { + let e = !1; + switch (t.code) { + case this.keys.UP: + t.ctrlKey || t.metaKey || t.shiftKey ? this.enableRotate && this._rotateUp(ye * this.keyRotateSpeed / this.domElement.clientHeight) : this.enablePan && this._pan(0, this.keyPanSpeed), e = !0; + break; + case this.keys.BOTTOM: + t.ctrlKey || t.metaKey || t.shiftKey ? this.enableRotate && this._rotateUp(-ye * this.keyRotateSpeed / this.domElement.clientHeight) : this.enablePan && this._pan(0, -this.keyPanSpeed), e = !0; + break; + case this.keys.LEFT: + t.ctrlKey || t.metaKey || t.shiftKey ? this.enableRotate && this._rotateLeft(ye * this.keyRotateSpeed / this.domElement.clientHeight) : this.enablePan && this._pan(this.keyPanSpeed, 0), e = !0; + break; + case this.keys.RIGHT: + t.ctrlKey || t.metaKey || t.shiftKey ? this.enableRotate && this._rotateLeft(-ye * this.keyRotateSpeed / this.domElement.clientHeight) : this.enablePan && this._pan(-this.keyPanSpeed, 0), e = !0; + break; + } + e && (t.preventDefault(), this.update()); + } + _handleTouchStartRotate(t) { + if (this._pointers.length === 1) + this._rotateStart.set(t.pageX, t.pageY); + else { + const e = this._getSecondPointerPosition(t), n = 0.5 * (t.pageX + e.x), s = 0.5 * (t.pageY + e.y); + this._rotateStart.set(n, s); + } + } + _handleTouchStartPan(t) { + if (this._pointers.length === 1) + this._panStart.set(t.pageX, t.pageY); + else { + const e = this._getSecondPointerPosition(t), n = 0.5 * (t.pageX + e.x), s = 0.5 * (t.pageY + e.y); + this._panStart.set(n, s); + } + } + _handleTouchStartDolly(t) { + const e = this._getSecondPointerPosition(t), n = t.pageX - e.x, s = t.pageY - e.y, r = Math.sqrt(n * n + s * s); + this._dollyStart.set(0, r); + } + _handleTouchStartDollyPan(t) { + this.enableZoom && this._handleTouchStartDolly(t), this.enablePan && this._handleTouchStartPan(t); + } + _handleTouchStartDollyRotate(t) { + this.enableZoom && this._handleTouchStartDolly(t), this.enableRotate && this._handleTouchStartRotate(t); + } + _handleTouchMoveRotate(t) { + if (this._pointers.length == 1) + this._rotateEnd.set(t.pageX, t.pageY); + else { + const n = this._getSecondPointerPosition(t), s = 0.5 * (t.pageX + n.x), r = 0.5 * (t.pageY + n.y); + this._rotateEnd.set(s, r); + } + this._rotateDelta.subVectors(this._rotateEnd, this._rotateStart).multiplyScalar(this.rotateSpeed); + const e = this.domElement; + this._rotateLeft(ye * this._rotateDelta.x / e.clientHeight), this._rotateUp(ye * this._rotateDelta.y / e.clientHeight), this._rotateStart.copy(this._rotateEnd); + } + _handleTouchMovePan(t) { + if (this._pointers.length === 1) + this._panEnd.set(t.pageX, t.pageY); + else { + const e = this._getSecondPointerPosition(t), n = 0.5 * (t.pageX + e.x), s = 0.5 * (t.pageY + e.y); + this._panEnd.set(n, s); + } + this._panDelta.subVectors(this._panEnd, this._panStart).multiplyScalar(this.panSpeed), this._pan(this._panDelta.x, this._panDelta.y), this._panStart.copy(this._panEnd); + } + _handleTouchMoveDolly(t) { + const e = this._getSecondPointerPosition(t), n = t.pageX - e.x, s = t.pageY - e.y, r = Math.sqrt(n * n + s * s); + this._dollyEnd.set(0, r), 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 = (t.pageX + e.x) * 0.5, o = (t.pageY + e.y) * 0.5; + this._updateZoomParameters(a, o); + } + _handleTouchMoveDollyPan(t) { + this.enableZoom && this._handleTouchMoveDolly(t), this.enablePan && this._handleTouchMovePan(t); + } + _handleTouchMoveDollyRotate(t) { + this.enableZoom && this._handleTouchMoveDolly(t), this.enableRotate && this._handleTouchMoveRotate(t); + } + // pointers + _addPointer(t) { + this._pointers.push(t.pointerId); + } + _removePointer(t) { + delete this._pointerPositions[t.pointerId]; + for (let e = 0; e < this._pointers.length; e++) + if (this._pointers[e] == t.pointerId) { + this._pointers.splice(e, 1); + return; + } + } + _isTrackingPointer(t) { + for (let e = 0; e < this._pointers.length; e++) + if (this._pointers[e] == t.pointerId) return !0; + return !1; + } + _trackPointer(t) { + let e = this._pointerPositions[t.pointerId]; + e === void 0 && (e = new Ct(), this._pointerPositions[t.pointerId] = e), e.set(t.pageX, t.pageY); + } + _getSecondPointerPosition(t) { + const e = t.pointerId === this._pointers[0] ? this._pointers[1] : this._pointers[0]; + return this._pointerPositions[e]; + } + // + _customWheelEvent(t) { + const e = t.deltaMode, n = { + clientX: t.clientX, + clientY: t.clientY, + deltaY: t.deltaY + }; + switch (e) { + case 1: + n.deltaY *= 16; + break; + case 2: + n.deltaY *= 100; + break; + } + return t.ctrlKey && !this._controlActive && (n.deltaY *= 10), n; + } +} +function gp(i) { + this.enabled !== !1 && (this._pointers.length === 0 && (this.domElement.setPointerCapture(i.pointerId), this.domElement.addEventListener("pointermove", this._onPointerMove), this.domElement.addEventListener("pointerup", this._onPointerUp)), !this._isTrackingPointer(i) && (this._addPointer(i), i.pointerType === "touch" ? this._onTouchStart(i) : this._onMouseDown(i))); +} +function vp(i) { + this.enabled !== !1 && (i.pointerType === "touch" ? this._onTouchMove(i) : this._onMouseMove(i)); +} +function xp(i) { + switch (this._removePointer(i), this._pointers.length) { + case 0: + this.domElement.releasePointerCapture(i.pointerId), this.domElement.removeEventListener("pointermove", this._onPointerMove), this.domElement.removeEventListener("pointerup", this._onPointerUp), this.dispatchEvent(Go), this.state = Kt.NONE; + break; + case 1: + const t = this._pointers[0], e = this._pointerPositions[t]; + this._onTouchStart({ pointerId: t, pageX: e.x, pageY: e.y }); + break; + } +} +function Mp(i) { + let t; + switch (i.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 ei.DOLLY: + if (this.enableZoom === !1) return; + this._handleMouseDownDolly(i), this.state = Kt.DOLLY; + break; + case ei.ROTATE: + if (i.ctrlKey || i.metaKey || i.shiftKey) { + if (this.enablePan === !1) return; + this._handleMouseDownPan(i), this.state = Kt.PAN; + } else { + if (this.enableRotate === !1) return; + this._handleMouseDownRotate(i), this.state = Kt.ROTATE; + } + break; + case ei.PAN: + if (i.ctrlKey || i.metaKey || i.shiftKey) { + if (this.enableRotate === !1) return; + this._handleMouseDownRotate(i), this.state = Kt.ROTATE; + } else { + if (this.enablePan === !1) return; + this._handleMouseDownPan(i), this.state = Kt.PAN; + } + break; + default: + this.state = Kt.NONE; + } + this.state !== Kt.NONE && this.dispatchEvent(ta); +} +function Sp(i) { + switch (this.state) { + case Kt.ROTATE: + if (this.enableRotate === !1) return; + this._handleMouseMoveRotate(i); + break; + case Kt.DOLLY: + if (this.enableZoom === !1) return; + this._handleMouseMoveDolly(i); + break; + case Kt.PAN: + if (this.enablePan === !1) return; + this._handleMouseMovePan(i); + break; + } +} +function Ep(i) { + this.enabled === !1 || this.enableZoom === !1 || this.state !== Kt.NONE || (i.preventDefault(), this.dispatchEvent(ta), this._handleMouseWheel(this._customWheelEvent(i)), this.dispatchEvent(Go)); +} +function yp(i) { + this.enabled !== !1 && this._handleKeyDown(i); +} +function Tp(i) { + switch (this._trackPointer(i), this._pointers.length) { + case 1: + switch (this.touches.ONE) { + case Qn.ROTATE: + if (this.enableRotate === !1) return; + this._handleTouchStartRotate(i), this.state = Kt.TOUCH_ROTATE; + break; + case Qn.PAN: + if (this.enablePan === !1) return; + this._handleTouchStartPan(i), this.state = Kt.TOUCH_PAN; + break; + default: + this.state = Kt.NONE; + } + break; + case 2: + switch (this.touches.TWO) { + case Qn.DOLLY_PAN: + if (this.enableZoom === !1 && this.enablePan === !1) return; + this._handleTouchStartDollyPan(i), this.state = Kt.TOUCH_DOLLY_PAN; + break; + case Qn.DOLLY_ROTATE: + if (this.enableZoom === !1 && this.enableRotate === !1) return; + this._handleTouchStartDollyRotate(i), this.state = Kt.TOUCH_DOLLY_ROTATE; + break; + default: + this.state = Kt.NONE; + } + break; + default: + this.state = Kt.NONE; + } + this.state !== Kt.NONE && this.dispatchEvent(ta); +} +function bp(i) { + switch (this._trackPointer(i), this.state) { + case Kt.TOUCH_ROTATE: + if (this.enableRotate === !1) return; + this._handleTouchMoveRotate(i), this.update(); + break; + case Kt.TOUCH_PAN: + if (this.enablePan === !1) return; + this._handleTouchMovePan(i), this.update(); + break; + case Kt.TOUCH_DOLLY_PAN: + if (this.enableZoom === !1 && this.enablePan === !1) return; + this._handleTouchMoveDollyPan(i), this.update(); + break; + case Kt.TOUCH_DOLLY_ROTATE: + if (this.enableZoom === !1 && this.enableRotate === !1) return; + this._handleTouchMoveDollyRotate(i), this.update(); + break; + default: + this.state = Kt.NONE; + } +} +function Ap(i) { + this.enabled !== !1 && i.preventDefault(); +} +function Rp(i) { + i.key === "Control" && (this._controlActive = !0, this.domElement.getRootNode().addEventListener("keyup", this._interceptControlUp, { passive: !0, capture: !0 })); +} +function wp(i) { + i.key === "Control" && (this._controlActive = !1, this.domElement.getRootNode().removeEventListener("keyup", this._interceptControlUp, { passive: !0, capture: !0 })); +} +const co = 0.02; +function Ji(i, t) { + return Math.abs(i[0] - t[0]) < co && Math.abs(i[1] - t[1]) < co; +} +function Cp(i) { + const t = i.map( + (n) => n.outline.map((s, r) => ({ + from: s, + to: n.outline[(r + 1) % n.outline.length] + })) + ), e = []; + return t.forEach((n, s) => { + for (const r of n) + t.some( + (o, c) => c !== s && o.some( + (l) => Ji(l.from, r.from) && Ji(l.to, r.to) || Ji(l.from, r.to) && Ji(l.to, r.from) + ) + ) || e.push(r); + }), e; +} +function Pp(i) { + const t = [1 / 0, 1 / 0, 1 / 0], e = [-1 / 0, -1 / 0, -1 / 0]; + for (const n of i) + for (let s = 0; s < 3; s++) + t[s] = Math.min(t[s], n[s]), e[s] = Math.max(e[s], n[s]); + return { min: t, max: e }; +} +function ho(i, t) { + return Math.hypot(i[0] - t[0], i[1] - t[1], i[2] - t[2]); +} +function Dp(i) { + return { width: ho(i[0], i[1]), height: ho(i[0], i[3]) }; +} +function fn([i, t, e]) { + return new N(i, e, -t); +} +function Ys(i, t) { + const e = new an(), n = []; + for (let s = 1; s < i.length - 1; s++) + for (const r of [i[0], i[s], i[s + 1]]) n.push(r.x, r.y, r.z); + if (e.setAttribute("position", new Fe(new Float32Array(n), 3)), t) { + const s = [0, 0, 1, 0, 1, 1, 0, 0, 1, 1, 0, 1]; + e.setAttribute("uv", new Fe(new Float32Array(s), 2)); + } + return e.computeVertexNormals(), e; +} +const uo = 220; +class Lp { + constructor(t, e, n, s) { + this.onPanelClick = s, this.renderer = new pp({ antialias: !0, alpha: !0 }), this.renderer.outputColorSpace = Te, this.renderer.setPixelRatio(Math.min(window.devicePixelRatio, 2)), this.element = this.renderer.domElement, this.element.style.touchAction = "none", this.scene.add(new Rc(16777215, 1.6)); + const r = new Ac(16777215, 1.8); + r.position.set(-8, 20, 12), this.scene.add(r), this.materials = { + ground: new Os({ side: De }), + wall: new Os({ side: De }), + roof: new Os({ side: De }) + }, this.setColors(n); + const a = [...t.flatMap((f) => f.outline), ...e.flatMap((f) => f.corners)], o = Pp(a), c = [ + (o.min[0] + o.max[0]) / 2, + (o.min[1] + o.max[1]) / 2, + 0 + ], l = Math.max(o.max[0] - o.min[0], o.max[1] - o.min[1], o.max[2]), u = new be(new Jr(l * 1.6, 64), this.materials.ground); + u.rotation.x = -Math.PI / 2, u.position.copy(fn(c)), u.position.y = -0.01, this.scene.add(u); + for (const f of t) + this.scene.add(new be(Ys(f.outline.map(fn), !1), this.materials.roof)); + for (const f of Cp(t)) { + const m = [ + fn([f.from[0], f.from[1], 0]), + fn([f.to[0], f.to[1], 0]), + fn(f.to), + fn(f.from) + ]; + this.scene.add(new be(Ys(m, !1), this.materials.wall)); + } + for (const f of e) this.addPanel(f); + this.target = fn([c[0], c[1], o.max[2] * 0.45]); + const d = l * 2.3; + this.homePosition = this.target.clone().add(new N(d * 0.18, d * 0.78, d * 0.6)), this.camera.position.copy(this.homePosition), this.controls = new _p(this.camera, this.element), this.controls.target.copy(this.target), this.controls.maxPolarAngle = Math.PI / 2 - 0.05, this.controls.minDistance = l * 0.6, this.controls.maxDistance = l * 5, this.controls.addEventListener("change", () => this.requestRender()), this.controls.update(), this.element.addEventListener("pointerdown", (f) => { + this.pointerDown = new Ct(f.clientX, f.clientY); + }), this.element.addEventListener("pointerup", (f) => this.handlePointerUp(f)); + } + element; + renderer; + scene = new gc(); + camera = new Ne(35, 1, 0.1, 500); + controls; + panels = /* @__PURE__ */ new Map(); + target; + homePosition; + renderQueued = !1; + pointerDown; + materials; + setColors(t) { + this.materials.ground.color = new Vt(t.ground), this.materials.wall.color = new Vt(t.wall), this.materials.roof.color = new Vt(t.roof), this.requestRender(); + } + addPanel(t) { + const { width: e, height: n } = Dp(t.corners), s = document.createElement("canvas"); + s.width = Math.round(e * uo), s.height = Math.round(n * uo); + const r = new Sc(s); + r.colorSpace = Te, r.anisotropy = 4; + const a = new Zr({ map: r, side: De }), o = new be(Ys(t.corners.map(fn), !0), a); + o.userData.panelId = t.id, this.scene.add(o), this.panels.set(t.id, { config: t, mesh: o, canvas: s, texture: r }); + } + /** Repaint the panels whose state changed. */ + updatePanels(t, e) { + let n = !1; + for (const [s, r] of this.panels) { + const a = t.get(s) ?? { status: "failed" }, o = a.status === "ok" ? `${Math.round(a.power)}|${e}` : "failed"; + o !== r.key && (r.key = o, Up(r.canvas, s, a, e), r.texture.needsUpdate = !0, n = !0); + } + n && this.requestRender(); + } + resetView() { + this.camera.position.copy(this.homePosition), this.controls.target.copy(this.target), this.controls.update(); + } + setSize(t, e) { + t <= 0 || e <= 0 || (this.renderer.setSize(t, e, !1), this.camera.aspect = t / e, this.camera.updateProjectionMatrix(), this.render()); + } + requestRender() { + this.renderQueued || (this.renderQueued = !0, requestAnimationFrame(() => { + this.renderQueued = !1, this.render(); + })); + } + render() { + this.renderer.render(this.scene, this.camera); + } + handlePointerUp(t) { + const e = this.pointerDown; + if (this.pointerDown = void 0, !e || e.distanceTo(new Ct(t.clientX, t.clientY)) > 6) return; + const n = this.element.getBoundingClientRect(), s = new Ct( + (t.clientX - n.left) / n.width * 2 - 1, + -((t.clientY - n.top) / n.height) * 2 + 1 + ), r = new Cc(); + r.setFromCamera(s, this.camera); + const a = [...this.panels.values()].map((l) => l.mesh), c = r.intersectObjects(a, !1)[0]?.object.userData.panelId; + typeof c == "string" && this.onPanelClick(c); + } + dispose() { + this.controls.dispose(); + for (const t of this.panels.values()) + t.texture.dispose(), t.mesh.geometry.dispose(), t.mesh.material.dispose(); + this.scene.traverse((t) => { + t instanceof be && t.geometry.dispose(); + }), Object.values(this.materials).forEach((t) => t.dispose()), this.renderer.dispose(); + } +} +function Up(i, t, e, n) { + const s = i.getContext("2d"); + if (!s) return; + const { width: r, height: a } = i, o = e.status !== "ok", c = o ? [96, 100, 108] : Jo(e.power, n), l = o ? "#ffffff" : Qo([c[0], c[1], c[2]]); + if (s.fillStyle = `rgb(${c[0]},${c[1]},${c[2]})`, s.fillRect(0, 0, r, a), o) { + s.strokeStyle = "rgba(255,255,255,0.18)", s.lineWidth = Math.max(4, r / 40); + for (let m = -a; m < r; m += r / 6) + s.beginPath(), s.moveTo(m, a), s.lineTo(m + a, 0), s.stroke(); + } else { + s.strokeStyle = "rgba(255,255,255,0.12)", s.lineWidth = 2; + const m = r > a ? 8 : 4, v = r > a ? 4 : 8; + for (let x = 1; x < m; x++) + s.beginPath(), s.moveTo(r / m * x, 0), s.lineTo(r / m * x, a), s.stroke(); + for (let x = 1; x < v; x++) + s.beginPath(), s.moveTo(0, a / v * x), s.lineTo(r, a / v * x), s.stroke(); + } + const u = Math.max(6, Math.min(r, a) / 22); + s.strokeStyle = o ? "#e5484d" : "rgba(10,14,24,0.85)", s.lineWidth = u, s.strokeRect(u / 2, u / 2, r - u, a - u); + const d = o ? "–" : tl(e.power), f = Math.min(r, a); + s.fillStyle = l, s.textAlign = "center", s.textBaseline = "middle", s.font = `700 ${Math.round(f * 0.3)}px system-ui, sans-serif`, s.fillText(d, r / 2, a * 0.44, r * 0.9), s.font = `500 ${Math.round(f * 0.16)}px system-ui, sans-serif`, s.globalAlpha = 0.85, s.fillText(t, r / 2, a * 0.78, r * 0.9), s.globalAlpha = 1; +} +const qs = "solaredge-roof-card", Ip = "M12,4C14.1,4 16.1,4.8 17.6,6.3C20.7,9.4 20.7,14.5 17.6,17.6C15.8,19.5 13.3,20.2 10.9,19.9L11.4,17.9C13.1,18.1 14.9,17.5 16.2,16.2C18.5,13.9 18.5,10.1 16.2,7.7C15.1,6.6 13.5,6 12,6V10.6L7,5.6L12,0.6V4M6.3,17.6C3.7,15 3.3,11 5.1,7.9L6.6,9.4C5.5,11.6 5.9,14.4 7.8,16.2C8.3,16.7 8.9,17.1 9.6,17.4L9,19.4C8,19 7.1,18.4 6.3,17.6Z"; +class Np extends HTMLElement { + config; + _hass; + scene; + resizeObserver; + entities = /* @__PURE__ */ new Map(); + entityCount = -1; + root; + stage; + status; + legendMax; + constructor() { + super(), this.root = this.attachShadow({ mode: "open" }); + } + static getStubConfig() { + return { layout: { roofs: [], panels: [] } }; + } + setConfig(t) { + if (!t?.layout || !Array.isArray(t.layout.panels) || !Array.isArray(t.layout.roofs)) + throw new Error("layout.roofs und layout.panels fehlen"); + if (t.max_power !== void 0 && !(Number(t.max_power) > 0)) + throw new Error("max_power muss größer als 0 sein"); + this.config = t, this.entityCount = -1, this.teardownScene(), this.renderShell(), this.isConnected && this.setupScene(); + } + set hass(t) { + this._hass = t, this.update(); + } + getCardSize() { + return 8; + } + getGridOptions() { + return { columns: 12, min_columns: 6, min_rows: 6 }; + } + connectedCallback() { + this.config && !this.scene && this.setupScene(); + } + disconnectedCallback() { + this.teardownScene(); + } + get maxPower() { + return Number(this.config?.max_power ?? 460); + } + renderShell() { + const t = this.config?.title ?? "Dach"; + this.root.innerHTML = ` + + +
+

+ + +
+
+
+ 0 W + ausgefallen +
+
`, this.root.querySelector("h2").textContent = t, this.stage = this.root.querySelector(".stage"), this.status = this.root.querySelector(".status"), this.legendMax = this.root.querySelector(".max"), this.legendMax.textContent = `${this.maxPower} W`, this.root.querySelector("button").addEventListener("click", () => this.scene?.resetView()); + } + sceneColors() { + const t = getComputedStyle(this), e = this._hass && this._hass.themes?.darkMode; + return { + background: t.getPropertyValue("--card-background-color") || "#fff", + ground: e ? "#2a2f2a" : "#cfd6c8", + wall: e ? "#8a8d92" : "#e4e2dc", + roof: e ? "#4b4f56" : "#7b7f86" + }; + } + setupScene() { + if (!this.config || !this.stage) return; + const { roofs: t, panels: e } = this.config.layout; + this.scene = new Lp( + t, + e, + this.sceneColors(), + (n) => this.openMoreInfo(n) + ), this.stage.append(this.scene.element), this.resizeObserver = new ResizeObserver(() => { + !this.stage || !this.scene || this.scene.setSize(this.stage.clientWidth, this.stage.clientHeight); + }), this.resizeObserver.observe(this.stage), this.update(); + } + teardownScene() { + this.resizeObserver?.disconnect(), this.resizeObserver = void 0, this.scene?.element.remove(), this.scene?.dispose(), this.scene = void 0; + } + update() { + const t = this._hass, e = this.config; + if (!t || !e) return; + const n = e.layout.panels.map((o) => o.id), s = Object.keys(t.states).length; + s !== this.entityCount && (this.entities = jo(t.states, n), this.entityCount = s); + const { panels: r, newestMeasurement: a } = $o(t.states, this.entities, n); + if (this.scene?.updatePanels(r, this.maxPower), this.status) { + const o = t.locale?.language ?? t.language ?? "de"; + this.status.textContent = a === void 0 ? "Stand: –" : `Stand: ${new Date(a).toLocaleTimeString(o, { + hour: "2-digit", + minute: "2-digit" + })}`; + } + } + openMoreInfo(t) { + const e = this.entities.get(t); + e && this.dispatchEvent( + new CustomEvent("hass-more-info", { detail: { entityId: e }, bubbles: !0, composed: !0 }) + ); + } +} +customElements.get(qs) || (customElements.define(qs, Np), (window.customCards ??= []).push({ + type: qs, + name: "SolarEdge Dach", + description: "3D-Dachansicht mit der aktuellen Leistung jedes Panels" +})); diff --git a/custom_components/solaredge_optimizers/manifest.json b/custom_components/solaredge_optimizers/manifest.json index 3047771..cd269ca 100644 --- a/custom_components/solaredge_optimizers/manifest.json +++ b/custom_components/solaredge_optimizers/manifest.json @@ -1,12 +1,18 @@ { "domain": "solaredge_optimizers", "name": "SolarEdge Optimizers", - "codeowners": ["@jensneuber"], + "codeowners": [ + "@jensneuber" + ], + "after_dependencies": [ + "frontend", + "http" + ], "config_flow": true, "documentation": "https://git.jensneuber.de/jens/ha-solaredge-optimizers", "integration_type": "hub", "iot_class": "local_polling", "issue_tracker": "https://git.jensneuber.de/jens/ha-solaredge-optimizers/issues", "requirements": [], - "version": "0.4.0" + "version": "0.5.0" } diff --git a/frontend/.gitignore b/frontend/.gitignore new file mode 100644 index 0000000..c2658d7 --- /dev/null +++ b/frontend/.gitignore @@ -0,0 +1 @@ +node_modules/ diff --git a/frontend/bun.lock b/frontend/bun.lock new file mode 100644 index 0000000..9c83abb --- /dev/null +++ b/frontend/bun.lock @@ -0,0 +1,241 @@ +{ + "lockfileVersion": 2, + "configVersion": 1, + "workspaces": { + "": { + "name": "solaredge-roof-card", + "dependencies": { + "three": "0.180.0", + }, + "devDependencies": { + "@types/three": "0.180.0", + "typescript": "5.9.3", + "vite": "7.1.12", + "vitest": "3.2.4", + }, + }, + }, + "packages": { + "@dimforge/rapier3d-compat": ["@dimforge/rapier3d-compat@0.12.0", "", {}, "sha512-uekIGetywIgopfD97oDL5PfeezkFpNhwlzlaEYNOA0N6ghdsOvh/HYjSMek5Q2O1PYvRSDFcqFVJl4r4ZBwOow=="], + + "@esbuild/aix-ppc64": ["@esbuild/aix-ppc64@0.25.12", "", { "os": "aix", "cpu": "ppc64" }, "sha512-Hhmwd6CInZ3dwpuGTF8fJG6yoWmsToE+vYgD4nytZVxcu1ulHpUQRAB1UJ8+N1Am3Mz4+xOByoQoSZf4D+CpkA=="], + + "@esbuild/android-arm": ["@esbuild/android-arm@0.25.12", "", { "os": "android", "cpu": "arm" }, "sha512-VJ+sKvNA/GE7Ccacc9Cha7bpS8nyzVv0jdVgwNDaR4gDMC/2TTRc33Ip8qrNYUcpkOHUT5OZ0bUcNNVZQ9RLlg=="], + + "@esbuild/android-arm64": ["@esbuild/android-arm64@0.25.12", "", { "os": "android", "cpu": "arm64" }, "sha512-6AAmLG7zwD1Z159jCKPvAxZd4y/VTO0VkprYy+3N2FtJ8+BQWFXU+OxARIwA46c5tdD9SsKGZ/1ocqBS/gAKHg=="], + + "@esbuild/android-x64": ["@esbuild/android-x64@0.25.12", "", { "os": "android", "cpu": "x64" }, "sha512-5jbb+2hhDHx5phYR2By8GTWEzn6I9UqR11Kwf22iKbNpYrsmRB18aX/9ivc5cabcUiAT/wM+YIZ6SG9QO6a8kg=="], + + "@esbuild/darwin-arm64": ["@esbuild/darwin-arm64@0.25.12", "", { "os": "darwin", "cpu": "arm64" }, "sha512-N3zl+lxHCifgIlcMUP5016ESkeQjLj/959RxxNYIthIg+CQHInujFuXeWbWMgnTo4cp5XVHqFPmpyu9J65C1Yg=="], + + "@esbuild/darwin-x64": ["@esbuild/darwin-x64@0.25.12", "", { "os": "darwin", "cpu": "x64" }, "sha512-HQ9ka4Kx21qHXwtlTUVbKJOAnmG1ipXhdWTmNXiPzPfWKpXqASVcWdnf2bnL73wgjNrFXAa3yYvBSd9pzfEIpA=="], + + "@esbuild/freebsd-arm64": ["@esbuild/freebsd-arm64@0.25.12", "", { "os": "freebsd", "cpu": "arm64" }, "sha512-gA0Bx759+7Jve03K1S0vkOu5Lg/85dou3EseOGUes8flVOGxbhDDh/iZaoek11Y8mtyKPGF3vP8XhnkDEAmzeg=="], + + "@esbuild/freebsd-x64": ["@esbuild/freebsd-x64@0.25.12", "", { "os": "freebsd", "cpu": "x64" }, "sha512-TGbO26Yw2xsHzxtbVFGEXBFH0FRAP7gtcPE7P5yP7wGy7cXK2oO7RyOhL5NLiqTlBh47XhmIUXuGciXEqYFfBQ=="], + + "@esbuild/linux-arm": ["@esbuild/linux-arm@0.25.12", "", { "os": "linux", "cpu": "arm" }, "sha512-lPDGyC1JPDou8kGcywY0YILzWlhhnRjdof3UlcoqYmS9El818LLfJJc3PXXgZHrHCAKs/Z2SeZtDJr5MrkxtOw=="], + + "@esbuild/linux-arm64": ["@esbuild/linux-arm64@0.25.12", "", { "os": "linux", "cpu": "arm64" }, "sha512-8bwX7a8FghIgrupcxb4aUmYDLp8pX06rGh5HqDT7bB+8Rdells6mHvrFHHW2JAOPZUbnjUpKTLg6ECyzvas2AQ=="], + + "@esbuild/linux-ia32": ["@esbuild/linux-ia32@0.25.12", "", { "os": "linux", "cpu": "ia32" }, "sha512-0y9KrdVnbMM2/vG8KfU0byhUN+EFCny9+8g202gYqSSVMonbsCfLjUO+rCci7pM0WBEtz+oK/PIwHkzxkyharA=="], + + "@esbuild/linux-loong64": ["@esbuild/linux-loong64@0.25.12", "", { "os": "linux", "cpu": "none" }, "sha512-h///Lr5a9rib/v1GGqXVGzjL4TMvVTv+s1DPoxQdz7l/AYv6LDSxdIwzxkrPW438oUXiDtwM10o9PmwS/6Z0Ng=="], + + "@esbuild/linux-mips64el": ["@esbuild/linux-mips64el@0.25.12", "", { "os": "linux", "cpu": "none" }, "sha512-iyRrM1Pzy9GFMDLsXn1iHUm18nhKnNMWscjmp4+hpafcZjrr2WbT//d20xaGljXDBYHqRcl8HnxbX6uaA/eGVw=="], + + "@esbuild/linux-ppc64": ["@esbuild/linux-ppc64@0.25.12", "", { "os": "linux", "cpu": "ppc64" }, "sha512-9meM/lRXxMi5PSUqEXRCtVjEZBGwB7P/D4yT8UG/mwIdze2aV4Vo6U5gD3+RsoHXKkHCfSxZKzmDssVlRj1QQA=="], + + "@esbuild/linux-riscv64": ["@esbuild/linux-riscv64@0.25.12", "", { "os": "linux", "cpu": "none" }, "sha512-Zr7KR4hgKUpWAwb1f3o5ygT04MzqVrGEGXGLnj15YQDJErYu/BGg+wmFlIDOdJp0PmB0lLvxFIOXZgFRrdjR0w=="], + + "@esbuild/linux-s390x": ["@esbuild/linux-s390x@0.25.12", "", { "os": "linux", "cpu": "s390x" }, "sha512-MsKncOcgTNvdtiISc/jZs/Zf8d0cl/t3gYWX8J9ubBnVOwlk65UIEEvgBORTiljloIWnBzLs4qhzPkJcitIzIg=="], + + "@esbuild/linux-x64": ["@esbuild/linux-x64@0.25.12", "", { "os": "linux", "cpu": "x64" }, "sha512-uqZMTLr/zR/ed4jIGnwSLkaHmPjOjJvnm6TVVitAa08SLS9Z0VM8wIRx7gWbJB5/J54YuIMInDquWyYvQLZkgw=="], + + "@esbuild/netbsd-arm64": ["@esbuild/netbsd-arm64@0.25.12", "", { "os": "none", "cpu": "arm64" }, "sha512-xXwcTq4GhRM7J9A8Gv5boanHhRa/Q9KLVmcyXHCTaM4wKfIpWkdXiMog/KsnxzJ0A1+nD+zoecuzqPmCRyBGjg=="], + + "@esbuild/netbsd-x64": ["@esbuild/netbsd-x64@0.25.12", "", { "os": "none", "cpu": "x64" }, "sha512-Ld5pTlzPy3YwGec4OuHh1aCVCRvOXdH8DgRjfDy/oumVovmuSzWfnSJg+VtakB9Cm0gxNO9BzWkj6mtO1FMXkQ=="], + + "@esbuild/openbsd-arm64": ["@esbuild/openbsd-arm64@0.25.12", "", { "os": "openbsd", "cpu": "arm64" }, "sha512-fF96T6KsBo/pkQI950FARU9apGNTSlZGsv1jZBAlcLL1MLjLNIWPBkj5NlSz8aAzYKg+eNqknrUJ24QBybeR5A=="], + + "@esbuild/openbsd-x64": ["@esbuild/openbsd-x64@0.25.12", "", { "os": "openbsd", "cpu": "x64" }, "sha512-MZyXUkZHjQxUvzK7rN8DJ3SRmrVrke8ZyRusHlP+kuwqTcfWLyqMOE3sScPPyeIXN/mDJIfGXvcMqCgYKekoQw=="], + + "@esbuild/openharmony-arm64": ["@esbuild/openharmony-arm64@0.25.12", "", { "os": "none", "cpu": "arm64" }, "sha512-rm0YWsqUSRrjncSXGA7Zv78Nbnw4XL6/dzr20cyrQf7ZmRcsovpcRBdhD43Nuk3y7XIoW2OxMVvwuRvk9XdASg=="], + + "@esbuild/sunos-x64": ["@esbuild/sunos-x64@0.25.12", "", { "os": "sunos", "cpu": "x64" }, "sha512-3wGSCDyuTHQUzt0nV7bocDy72r2lI33QL3gkDNGkod22EsYl04sMf0qLb8luNKTOmgF/eDEDP5BFNwoBKH441w=="], + + "@esbuild/win32-arm64": ["@esbuild/win32-arm64@0.25.12", "", { "os": "win32", "cpu": "arm64" }, "sha512-rMmLrur64A7+DKlnSuwqUdRKyd3UE7oPJZmnljqEptesKM8wx9J8gx5u0+9Pq0fQQW8vqeKebwNXdfOyP+8Bsg=="], + + "@esbuild/win32-ia32": ["@esbuild/win32-ia32@0.25.12", "", { "os": "win32", "cpu": "ia32" }, "sha512-HkqnmmBoCbCwxUKKNPBixiWDGCpQGVsrQfJoVGYLPT41XWF8lHuE5N6WhVia2n4o5QK5M4tYr21827fNhi4byQ=="], + + "@esbuild/win32-x64": ["@esbuild/win32-x64@0.25.12", "", { "os": "win32", "cpu": "x64" }, "sha512-alJC0uCZpTFrSL0CCDjcgleBXPnCrEAhTBILpeAp7M/OFgoqtAetfBzX0xM00MUsVVPpVjlPuMbREqnZCXaTnA=="], + + "@jridgewell/sourcemap-codec": ["@jridgewell/sourcemap-codec@1.6.0", "", {}, "sha512-T7jf+5zgsZHwNJ4lvQ7/aezbyk0nNX+zJVWpmHA7VYsEx7a7qr5Rg5IbtJFqkgze5Y2sruq1RUY8Q837Od7iFw=="], + + "@rollup/rollup-android-arm-eabi": ["@rollup/rollup-android-arm-eabi@4.68.7", "", { "os": "android", "cpu": "arm" }, "sha512-ZL7MgOeMUiBum1bjzzyBotE3DuHVz+UUxcDVlLL7gpdhDM4RpjG4bZOIly7ensIcXw9jhWl7HTIIQ9KsgjykGQ=="], + + "@rollup/rollup-android-arm64": ["@rollup/rollup-android-arm64@4.68.7", "", { "os": "android", "cpu": "arm64" }, "sha512-cKZ2Hz/xt5DLY/vdUmMXEn3gnjLgwdeB/npHagbdTljLvBE6b/xKcPCcRWTiT0pHeVf8akl5Cb9K7ylRxbtHng=="], + + "@rollup/rollup-android-x64": ["@rollup/rollup-android-x64@4.68.7", "", { "os": "android", "cpu": "x64" }, "sha512-P9vs1uCC2drepKKuiXrhY+r7ry/jtDCrBS8SUCYm2Rr7rVTR9eFH6XVAmD9TdfYFlDgRe5r1eH8tLQVuz+l/VA=="], + + "@rollup/rollup-darwin-arm64": ["@rollup/rollup-darwin-arm64@4.68.7", "", { "os": "darwin", "cpu": "arm64" }, "sha512-Lgu2AV7jbOTNNhkQ/OurNm7Snqu1Ux/3y7k8q47fbpPa3q63aIzKKp1xFzax5KH4pcdUzbnX/riuFsxKflsF+g=="], + + "@rollup/rollup-darwin-x64": ["@rollup/rollup-darwin-x64@4.68.7", "", { "os": "darwin", "cpu": "x64" }, "sha512-wKo6rOzla+/3rN8QBqTgcrsQMfyqwa3y14TvCTotLLib/ACWTxX1zWDTYze90s2RWtYiSfTlavHLmZv0Jsafrw=="], + + "@rollup/rollup-freebsd-arm64": ["@rollup/rollup-freebsd-arm64@4.68.7", "", { "os": "freebsd", "cpu": "arm64" }, "sha512-vAeCwbFyEu/vBt9O/uHCHJSvwtOpTSssnM/PoZgn8rmvAkS+9ixaUfJZ2IP3ltom+rvpuQQEIEqltPY7qhC9lQ=="], + + "@rollup/rollup-freebsd-x64": ["@rollup/rollup-freebsd-x64@4.68.7", "", { "os": "freebsd", "cpu": "x64" }, "sha512-HvjSxOKI+6Si4ytmaoCEpjwDMrH/1s0uWeTAhdE5oXY8/RMI92hCePI/psZuJtY5EHWoT7MfyvTz0HBDZb1ZwQ=="], + + "@rollup/rollup-linux-arm-gnueabihf": ["@rollup/rollup-linux-arm-gnueabihf@4.68.7", "", { "os": "linux", "cpu": "arm", "libc": "glibc" }, "sha512-nz/Eu1sag3w5gPiKLJhAbKa4D9hUUJpDc9XzKXxGNHZqwgT2AbuVS2e4k9CIoLQp5dPhSN9ntiEVuz2jTzu1Gg=="], + + "@rollup/rollup-linux-arm-musleabihf": ["@rollup/rollup-linux-arm-musleabihf@4.68.7", "", { "os": "linux", "cpu": "arm", "libc": "musl" }, "sha512-05CEv2G/kI261A1WQBZL8gx6xXULjPfVnTKAkfnV/0uqHeLo+dNEOeUzMaiK/HDGR0Z1Nn7KJjm/34bNbNcfTA=="], + + "@rollup/rollup-linux-arm64-gnu": ["@rollup/rollup-linux-arm64-gnu@4.68.7", "", { "os": "linux", "cpu": "arm64", "libc": "glibc" }, "sha512-wrqk3EkxQt98lTdiYhjcaWmFHwvKiSgHFi7XmPTSF4X8+uGUTBOAc0CaynEvpUhBgkPRbwASrYoU/5uJPF+LFA=="], + + "@rollup/rollup-linux-arm64-musl": ["@rollup/rollup-linux-arm64-musl@4.68.7", "", { "os": "linux", "cpu": "arm64", "libc": "musl" }, "sha512-DnuEUWvzeSxHxzu5lvrN+I/UzrcQkR/fQ4Bibetdp73Rf7aP0XgFpalSDuHmVWsCLETE+Lrl3GVOqIvFP7rcjw=="], + + "@rollup/rollup-linux-loong64-gnu": ["@rollup/rollup-linux-loong64-gnu@4.68.7", "", { "os": "linux", "cpu": "none", "libc": "glibc" }, "sha512-n0sr2s+rzVw8ntRucOxGhWeJ9lEl9KxCRzF3RmnZLE/tRnfKiloLuK8UqWrKFqVigEAh0IkRkPz5LVaV9/ZfvA=="], + + "@rollup/rollup-linux-loong64-musl": ["@rollup/rollup-linux-loong64-musl@4.68.7", "", { "os": "linux", "cpu": "none", "libc": "musl" }, "sha512-qDVJyMCbh7ekjt1kM9CZsyCFZvv5UW1QTIx3YfJ/gh8LkqpoPNpl9dCeYeOa+bsDOGTWZiMG2riXuoFSRISimQ=="], + + "@rollup/rollup-linux-ppc64-gnu": ["@rollup/rollup-linux-ppc64-gnu@4.68.7", "", { "os": "linux", "cpu": "ppc64", "libc": "glibc" }, "sha512-GiIOHHIzgpMoR5DT1pA1b9qMk5i0Ngg2FRj4D6XFSBC8e/axHuIdB7K/OBozO2RtCVAMnH1rXcuJrGScg+bvzA=="], + + "@rollup/rollup-linux-ppc64-musl": ["@rollup/rollup-linux-ppc64-musl@4.68.7", "", { "os": "linux", "cpu": "ppc64", "libc": "musl" }, "sha512-B132V2fwDl7UGLhvK6s3Ay7eNQ4dmDSDgsBm/Wwbz+Wgnunz0le4R2wzDp6TL5ExMu3MC1auJIrVtk2gOyxbyw=="], + + "@rollup/rollup-linux-riscv64-gnu": ["@rollup/rollup-linux-riscv64-gnu@4.68.7", "", { "os": "linux", "cpu": "none", "libc": "glibc" }, "sha512-3NueHQilbssjxgJMx9hXBV+U5keb3CBzmW5WhoBG3iSLFcmz9U2FVoG4MUYpZoZ+KSNMQPN2AA79dTxlEF0VxQ=="], + + "@rollup/rollup-linux-riscv64-musl": ["@rollup/rollup-linux-riscv64-musl@4.68.7", "", { "os": "linux", "cpu": "none", "libc": "musl" }, "sha512-8XRwbf76oAF1zZzg6OT8EY3swvCptZnLmiqMgO5+STyhTZ9s7rXa+tY8jESZW9IDyKACcVBGqa/RACDaLzRVjQ=="], + + "@rollup/rollup-linux-s390x-gnu": ["@rollup/rollup-linux-s390x-gnu@4.68.7", "", { "os": "linux", "cpu": "s390x", "libc": "glibc" }, "sha512-pvqqfjNdxVLvmovH681K5cPIL9DXj5n1RROaa0vb9JrtHddiScLrkHPRKj5flTKHF1M7xvRy0SS2yTRIc2TO0Q=="], + + "@rollup/rollup-linux-x64-gnu": ["@rollup/rollup-linux-x64-gnu@4.68.7", "", { "os": "linux", "cpu": "x64", "libc": "glibc" }, "sha512-rsTjTf5HAm6F4sI6uUfJf2pc+7AWBKxgc2RveGvwB2OvVa1GezSSCDD1rtXPuFhcg3itPv7iHgcZsq/RwWvJ4Q=="], + + "@rollup/rollup-linux-x64-musl": ["@rollup/rollup-linux-x64-musl@4.68.7", "", { "os": "linux", "cpu": "x64", "libc": "musl" }, "sha512-VNLvsYMD5+zLCi5SohwDdL8PpicC9PnArLwyMJXXUcAduzrM3k9aZT9XiHw+mn5dOWr3UEyfyqJbOvxwJ2fCWQ=="], + + "@rollup/rollup-openbsd-x64": ["@rollup/rollup-openbsd-x64@4.68.7", "", { "os": "openbsd", "cpu": "x64" }, "sha512-7aOjdahkwiECWWOmjAemPd21yeQ18TW59DUiLWttzolMe5tDwHyBhlOfmxRUHOQnepTNkZ2Qwp1T6LxFZ5v7yQ=="], + + "@rollup/rollup-openharmony-arm64": ["@rollup/rollup-openharmony-arm64@4.68.7", "", { "os": "none", "cpu": "arm64" }, "sha512-BnNkTwE4FMCAoz3UYiJ6D6Y3pGozYIYZ2W+onH64uhiTI2iwD3KOaNSlkuHYfupZVemls3YTlvbPnuKwHsraiQ=="], + + "@rollup/rollup-win32-arm64-msvc": ["@rollup/rollup-win32-arm64-msvc@4.68.7", "", { "os": "win32", "cpu": "arm64" }, "sha512-OH8tGWsJcRW6Vn0dmndyWJGdQa46bH2/2/PVfleBGUWuBd5/HVkIvw2UslgBwUZdtV78bJaoCNBmYI5+bcTJ4A=="], + + "@rollup/rollup-win32-ia32-msvc": ["@rollup/rollup-win32-ia32-msvc@4.68.7", "", { "os": "win32", "cpu": "ia32" }, "sha512-SpYx5X9+2JOF3hXe1cRaiFn562h4AMJhfgxkyHyiuh9dJ7PanPm7FTp8GJReSbS9N+TfjRiBbKacVk1g35kKxg=="], + + "@rollup/rollup-win32-x64-gnu": ["@rollup/rollup-win32-x64-gnu@4.68.7", "", { "os": "win32", "cpu": "x64" }, "sha512-0ncKtQ55fqElV9Sk4cZ/4tiXVGlWxaH5PvDOlx1Sx8GuHIpSWgYrTcyrO51JnVFfy7LvAJiffkEg63ZHKwTMag=="], + + "@rollup/rollup-win32-x64-msvc": ["@rollup/rollup-win32-x64-msvc@4.68.7", "", { "os": "win32", "cpu": "x64" }, "sha512-XY9DYHO5UxxVR8G6AErXDlccQmDpvGTLgKHFpvkgsyjwG/PrQuInRjQQfpEzBRuT+bhBtwfS8yDe9sPhVcq/9A=="], + + "@tweenjs/tween.js": ["@tweenjs/tween.js@23.1.3", "", {}, "sha512-vJmvvwFxYuGnF2axRtPYocag6Clbb5YS7kLL+SO/TeVFzHqDIWrNKYtcsPMibjDx9O+bu+psAy9NKfWklassUA=="], + + "@types/chai": ["@types/chai@5.2.3", "", { "dependencies": { "@types/deep-eql": "*", "assertion-error": "^2.0.1" } }, "sha512-Mw558oeA9fFbv65/y4mHtXDs9bPnFMZAL/jxdPFUpOHHIXX91mcgEHbS5Lahr+pwZFR8A7GQleRWeI6cGFC2UA=="], + + "@types/deep-eql": ["@types/deep-eql@4.0.2", "", {}, "sha512-c9h9dVVMigMPc4bwTvC5dxqtqJZwQPePsWjPlpSOnojbor6pGqdk541lfA7AqFQr5pB1BRdq0juY9db81BwyFw=="], + + "@types/estree": ["@types/estree@1.0.10", "", {}, "sha512-lTyOMnOcmRBzdCv6/4zUZCrEhV0xrqQiUZBZtVcbmLHBXKLnN8q89v/wKRF/Q0HbwVsqbIG3o5HDoFl9sduM+g=="], + + "@types/stats.js": ["@types/stats.js@0.17.4", "", {}, "sha512-jIBvWWShCvlBqBNIZt0KAshWpvSjhkwkEu4ZUcASoAvhmrgAUI2t1dXrjSL4xXVLB4FznPrIsX3nKXFl/Dt4vA=="], + + "@types/three": ["@types/three@0.180.0", "", { "dependencies": { "@dimforge/rapier3d-compat": "~0.12.0", "@tweenjs/tween.js": "~23.1.3", "@types/stats.js": "*", "@types/webxr": "*", "@webgpu/types": "*", "fflate": "~0.8.2", "meshoptimizer": "~0.22.0" } }, "sha512-ykFtgCqNnY0IPvDro7h+9ZeLY+qjgUWv+qEvUt84grhenO60Hqd4hScHE7VTB9nOQ/3QM8lkbNE+4vKjEpUxKg=="], + + "@types/webxr": ["@types/webxr@0.5.24", "", {}, "sha512-h8fgEd/DpoS9CBrjEQXR+dIDraopAEfu4wYVNY2tEPwk60stPWhvZMf4Foo5FakuQ7HFZoa8WceaWFervK2Ovg=="], + + "@vitest/expect": ["@vitest/expect@3.2.4", "", { "dependencies": { "@types/chai": "^5.2.2", "@vitest/spy": "3.2.4", "@vitest/utils": "3.2.4", "chai": "^5.2.0", "tinyrainbow": "^2.0.0" } }, "sha512-Io0yyORnB6sikFlt8QW5K7slY4OjqNX9jmJQ02QDda8lyM6B5oNgVWoSoKPac8/kgnCUzuHQKrSLtu/uOqqrig=="], + + "@vitest/mocker": ["@vitest/mocker@3.2.4", "", { "dependencies": { "@vitest/spy": "3.2.4", "estree-walker": "^3.0.3", "magic-string": "^0.30.17" }, "peerDependencies": { "msw": "^2.4.9", "vite": "^5.0.0 || ^6.0.0 || ^7.0.0-0" }, "optionalPeers": ["msw", "vite"] }, "sha512-46ryTE9RZO/rfDd7pEqFl7etuyzekzEhUbTW3BvmeO/BcCMEgq59BKhek3dXDWgAj4oMK6OZi+vRr1wPW6qjEQ=="], + + "@vitest/pretty-format": ["@vitest/pretty-format@3.2.4", "", { "dependencies": { "tinyrainbow": "^2.0.0" } }, "sha512-IVNZik8IVRJRTr9fxlitMKeJeXFFFN0JaB9PHPGQ8NKQbGpfjlTx9zO4RefN8gp7eqjNy8nyK3NZmBzOPeIxtA=="], + + "@vitest/runner": ["@vitest/runner@3.2.4", "", { "dependencies": { "@vitest/utils": "3.2.4", "pathe": "^2.0.3", "strip-literal": "^3.0.0" } }, "sha512-oukfKT9Mk41LreEW09vt45f8wx7DordoWUZMYdY/cyAk7w5TWkTRCNZYF7sX7n2wB7jyGAl74OxgwhPgKaqDMQ=="], + + "@vitest/snapshot": ["@vitest/snapshot@3.2.4", "", { "dependencies": { "@vitest/pretty-format": "3.2.4", "magic-string": "^0.30.17", "pathe": "^2.0.3" } }, "sha512-dEYtS7qQP2CjU27QBC5oUOxLE/v5eLkGqPE0ZKEIDGMs4vKWe7IjgLOeauHsR0D5YuuycGRO5oSRXnwnmA78fQ=="], + + "@vitest/spy": ["@vitest/spy@3.2.4", "", { "dependencies": { "tinyspy": "^4.0.3" } }, "sha512-vAfasCOe6AIK70iP5UD11Ac4siNUNJ9i/9PZ3NKx07sG6sUxeag1LWdNrMWeKKYBLlzuK+Gn65Yd5nyL6ds+nw=="], + + "@vitest/utils": ["@vitest/utils@3.2.4", "", { "dependencies": { "@vitest/pretty-format": "3.2.4", "loupe": "^3.1.4", "tinyrainbow": "^2.0.0" } }, "sha512-fB2V0JFrQSMsCo9HiSq3Ezpdv4iYaXRG1Sx8edX3MwxfyNn83mKiGzOcH+Fkxt4MHxr3y42fQi1oeAInqgX2QA=="], + + "@webgpu/types": ["@webgpu/types@0.1.74", "", {}, "sha512-lgiI4hbuLcI9unnm2cL/tvCaQU45dp0xcLWJh5uB/9MBGvIA4F8XIk7nSiBeg+K4xWGYwgZKn80LmERI5CxoTA=="], + + "assertion-error": ["assertion-error@2.0.1", "", {}, "sha512-Izi8RQcffqCeNVgFigKli1ssklIbpHnCYc6AknXGYoB6grJqyeby7jv12JUQgmTAnIDnbck1uxksT4dzN3PWBA=="], + + "cac": ["cac@6.7.14", "", {}, "sha512-b6Ilus+c3RrdDk+JhLKUAQfzzgLEPy6wcXqS7f/xe1EETvsDP6GORG7SFuOs6cID5YkqchW/LXZbX5bc8j7ZcQ=="], + + "chai": ["chai@5.3.3", "", { "dependencies": { "assertion-error": "^2.0.1", "check-error": "^2.1.1", "deep-eql": "^5.0.1", "loupe": "^3.1.0", "pathval": "^2.0.0" } }, "sha512-4zNhdJD/iOjSH0A05ea+Ke6MU5mmpQcbQsSOkgdaUMJ9zTlDTD/GYlwohmIE2u0gaxHYiVHEn1Fw9mZ/ktJWgw=="], + + "check-error": ["check-error@2.1.3", "", {}, "sha512-PAJdDJusoxnwm1VwW07VWwUN1sl7smmC3OKggvndJFadxxDRyFJBX/ggnu/KE4kQAB7a3Dp8f/YXC1FlUprWmA=="], + + "debug": ["debug@4.4.3", "", { "dependencies": { "ms": "^2.1.3" }, "peerDependencies": { "supports-color": "*" }, "optionalPeers": ["supports-color"] }, "sha512-RGwwWnwQvkVfavKVt22FGLw+xYSdzARwm0ru6DhTVA3umU5hZc28V3kO4stgYryrTlLpuvgI9GiijltAjNbcqA=="], + + "deep-eql": ["deep-eql@5.0.2", "", {}, "sha512-h5k/5U50IJJFpzfL6nO9jaaumfjO/f2NjK/oYB2Djzm4p9L+3T9qWpZqZ2hAbLPuuYq9wrU08WQyBTL5GbPk5Q=="], + + "es-module-lexer": ["es-module-lexer@1.7.0", "", {}, "sha512-jEQoCwk8hyb2AZziIOLhDqpm5+2ww5uIE6lkO/6jcOCusfk6LhMHpXXfBLXTZ7Ydyt0j4VoUQv6uGNYbdW+kBA=="], + + "esbuild": ["esbuild@0.25.12", "", { "optionalDependencies": { "@esbuild/aix-ppc64": "0.25.12", "@esbuild/android-arm": "0.25.12", "@esbuild/android-arm64": "0.25.12", "@esbuild/android-x64": "0.25.12", "@esbuild/darwin-arm64": "0.25.12", "@esbuild/darwin-x64": "0.25.12", "@esbuild/freebsd-arm64": "0.25.12", "@esbuild/freebsd-x64": "0.25.12", "@esbuild/linux-arm": "0.25.12", "@esbuild/linux-arm64": "0.25.12", "@esbuild/linux-ia32": "0.25.12", "@esbuild/linux-loong64": "0.25.12", "@esbuild/linux-mips64el": "0.25.12", "@esbuild/linux-ppc64": "0.25.12", "@esbuild/linux-riscv64": "0.25.12", "@esbuild/linux-s390x": "0.25.12", "@esbuild/linux-x64": "0.25.12", "@esbuild/netbsd-arm64": "0.25.12", "@esbuild/netbsd-x64": "0.25.12", "@esbuild/openbsd-arm64": "0.25.12", "@esbuild/openbsd-x64": "0.25.12", "@esbuild/openharmony-arm64": "0.25.12", "@esbuild/sunos-x64": "0.25.12", "@esbuild/win32-arm64": "0.25.12", "@esbuild/win32-ia32": "0.25.12", "@esbuild/win32-x64": "0.25.12" }, "hasInstallScript": true, "bin": { "esbuild": "bin/esbuild" } }, "sha512-bbPBYYrtZbkt6Os6FiTLCTFxvq4tt3JKall1vRwshA3fdVztsLAatFaZobhkBC8/BrPetoa0oksYoKXoG4ryJg=="], + + "estree-walker": ["estree-walker@3.0.3", "", { "dependencies": { "@types/estree": "^1.0.0" } }, "sha512-7RUKfXgSMMkzt6ZuXmqapOurLGPPfgj6l9uRZ7lRGolvk0y2yocc35LdcxKC5PQZdn2DMqioAQ2NoWcrTKmm6g=="], + + "expect-type": ["expect-type@1.4.0", "", {}, "sha512-KfYbmpRm0VbLjEvVa9yGwCi9GI34xvi7A/HXYWQO65CSD2u3MczUJSuwXKFIxlGsgBQizV9q5J9NHj4VG0n+pA=="], + + "fdir": ["fdir@6.5.0", "", { "peerDependencies": { "picomatch": "^3 || ^4" }, "optionalPeers": ["picomatch"] }, "sha512-tIbYtZbucOs0BRGqPJkshJUYdL+SDH7dVM8gjy+ERp3WAUjLEFJE+02kanyHtwjWOnwrKYBiwAmM0p4kLJAnXg=="], + + "fflate": ["fflate@0.8.3", "", {}, "sha512-tbZNuJrLwGUp3zshBtdy4W+ORxZuIh8a5ilyIEQDC5rY1f3U20JMry0Ll3WBzU58EZKsEuJFXhb5gwv8CsPvgA=="], + + "fsevents": ["fsevents@2.3.3", "", { "os": "darwin", "hasInstallScript": true }, "sha512-5xoDfX+fL7faATnagmWPpbFtwh/R77WmMMqqHGS65C3vvB0YHrgF+B1YmZ3441tMj5n63k0212XNoJwzlhffQw=="], + + "js-tokens": ["js-tokens@9.0.1", "", {}, "sha512-mxa9E9ITFOt0ban3j6L5MpjwegGz6lBQmM1IJkWeBZGcMxto50+eWdjC/52xDbS2vy0k7vIMK0Fe2wfL9OQSpQ=="], + + "loupe": ["loupe@3.2.1", "", {}, "sha512-CdzqowRJCeLU72bHvWqwRBBlLcMEtIvGrlvef74kMnV2AolS9Y8xUv1I0U/MNAWMhBlKIoyuEgoJ0t/bbwHbLQ=="], + + "magic-string": ["magic-string@0.30.21", "", { "dependencies": { "@jridgewell/sourcemap-codec": "^1.5.5" } }, "sha512-vd2F4YUyEXKGcLHoq+TEyCjxueSeHnFxyyjNp80yg0XV4vUhnDer/lvvlqM/arB5bXQN5K2/3oinyCRyx8T2CQ=="], + + "meshoptimizer": ["meshoptimizer@0.22.0", "", {}, "sha512-IebiK79sqIy+E4EgOr+CAw+Ke8hAspXKzBd0JdgEmPHiAwmvEj2S4h1rfvo+o/BnfEYd/jAOg5IeeIjzlzSnDg=="], + + "ms": ["ms@2.1.3", "", {}, "sha512-6FlzubTLZG3J2a/NVCAleEhjzq5oxgHyaCU9yYXvcLsvoVaHJq/s5xXI6/XXP6tz7R9xAOtHnSO/tXtF3WRTlA=="], + + "nanoid": ["nanoid@3.3.20", "", { "bin": { "nanoid": "bin/nanoid.cjs" } }, "sha512-uKdg2G3GNCKQn9byYOpxbGqrT2fGO5KRt5J/8b3pok8rT6qxGWF6hxMyJiEYtAf+FVyYuD9hRaDqX5uPFYJ4ZQ=="], + + "pathe": ["pathe@2.0.3", "", {}, "sha512-WUjGcAqP1gQacoQe+OBJsFA7Ld4DyXuUIjZ5cc75cLHvJ7dtNsTugphxIADwspS+AraAUePCKrSVtPLFj/F88w=="], + + "pathval": ["pathval@2.0.1", "", {}, "sha512-//nshmD55c46FuFw26xV/xFAaB5HF9Xdap7HJBBnrKdAd6/GxDBaNA1870O79+9ueg61cZLSVc+OaFlfmObYVQ=="], + + "picocolors": ["picocolors@1.1.1", "", {}, "sha512-xceH2snhtb5M9liqDsmEw56le376mTZkEX/jEb/RxNFyegNul7eNslCXP9FDj/Lcu0X8KEyMceP2ntpaHrDEVA=="], + + "picomatch": ["picomatch@4.0.7", "", {}, "sha512-qcJu88Q2IWqJsDD529JKMdwGm/dvInW4HvQnRwiH9JtihJvzGOscDtHE3x1pBKeUOTysQ8kVmLnJ2kJu7yhcGA=="], + + "postcss": ["postcss@8.5.33", "", { "dependencies": { "nanoid": "^3.3.20", "picocolors": "^1.1.1", "source-map-js": "^1.2.2" } }, "sha512-RVHEU9/Pp1Fnjr/MpAJsZoADukCKhfIi15OunEYiGktIkYLkPVvC1sioWolGDS7XByMTx9m/IGbro0Js13zhnQ=="], + + "rollup": ["rollup@4.68.7", "", { "dependencies": { "@types/estree": "^1.0.10" }, "optionalDependencies": { "@rollup/rollup-android-arm-eabi": "4.68.7", "@rollup/rollup-android-arm64": "4.68.7", "@rollup/rollup-android-x64": "4.68.7", "@rollup/rollup-darwin-arm64": "4.68.7", "@rollup/rollup-darwin-x64": "4.68.7", "@rollup/rollup-freebsd-arm64": "4.68.7", "@rollup/rollup-freebsd-x64": "4.68.7", "@rollup/rollup-linux-arm-gnueabihf": "4.68.7", "@rollup/rollup-linux-arm-musleabihf": "4.68.7", "@rollup/rollup-linux-arm64-gnu": "4.68.7", "@rollup/rollup-linux-arm64-musl": "4.68.7", "@rollup/rollup-linux-loong64-gnu": "4.68.7", "@rollup/rollup-linux-loong64-musl": "4.68.7", "@rollup/rollup-linux-ppc64-gnu": "4.68.7", "@rollup/rollup-linux-ppc64-musl": "4.68.7", "@rollup/rollup-linux-riscv64-gnu": "4.68.7", "@rollup/rollup-linux-riscv64-musl": "4.68.7", "@rollup/rollup-linux-s390x-gnu": "4.68.7", "@rollup/rollup-linux-x64-gnu": "4.68.7", "@rollup/rollup-linux-x64-musl": "4.68.7", "@rollup/rollup-openbsd-x64": "4.68.7", "@rollup/rollup-openharmony-arm64": "4.68.7", "@rollup/rollup-win32-arm64-msvc": "4.68.7", "@rollup/rollup-win32-ia32-msvc": "4.68.7", "@rollup/rollup-win32-x64-gnu": "4.68.7", "@rollup/rollup-win32-x64-msvc": "4.68.7", "fsevents": "~2.3.2" }, "bin": { "rollup": "dist/bin/rollup" } }, "sha512-CxhzUIc+ocxPAWxHuff+PAluoW1otD6dHqqPK2h2Q38WA1VYk+3gizX6NEg5t2a8yNGQaiHM1R7V+qdwWuvp5Q=="], + + "siginfo": ["siginfo@2.0.0", "", {}, "sha512-ybx0WO1/8bSBLEWXZvEd7gMW3Sn3JFlW3TvX1nREbDLRNQNaeNN8WK0meBwPdAaOI7TtRRRJn/Es1zhrrCHu7g=="], + + "source-map-js": ["source-map-js@1.2.4", "", {}, "sha512-J7ZjMvHd9O1fcT/5V09QWaaSl2BbWx3F6O08spde82Namf9UB0GxRVIPiNbVsdKkoizHiSpTodo3vp2bAy91MA=="], + + "stackback": ["stackback@0.0.2", "", {}, "sha512-1XMJE5fQo1jGH6Y/7ebnwPOBEkIEnT4QF32d5R1+VXdXveM0IBMJt8zfaxX1P3QhVwrYe+576+jkANtSS2mBbw=="], + + "std-env": ["std-env@3.10.0", "", {}, "sha512-5GS12FdOZNliM5mAOxFRg7Ir0pWz8MdpYm6AY6VPkGpbA7ZzmbzNcBJQ0GPvvyWgcY7QAhCgf9Uy89I03faLkg=="], + + "strip-literal": ["strip-literal@3.1.0", "", { "dependencies": { "js-tokens": "^9.0.1" } }, "sha512-8r3mkIM/2+PpjHoOtiAW8Rg3jJLHaV7xPwG+YRGrv6FP0wwk/toTpATxWYOW0BKdWwl82VT2tFYi5DlROa0Mxg=="], + + "three": ["three@0.180.0", "", {}, "sha512-o+qycAMZrh+TsE01GqWUxUIKR1AL0S8pq7zDkYOQw8GqfX8b8VoCKYUoHbhiX5j+7hr8XsuHDVU6+gkQJQKg9w=="], + + "tinybench": ["tinybench@2.9.0", "", {}, "sha512-0+DUvqWMValLmha6lr4kD8iAMK1HzV0/aKnCtWb9v9641TnP/MFb7Pc2bxoxQjTXAErryXVgUOfv2YqNllqGeg=="], + + "tinyexec": ["tinyexec@0.3.2", "", {}, "sha512-KQQR9yN7R5+OSwaK0XQoj22pwHoTlgYqmUscPYoknOoWCWfj/5/ABTMRi69FrKU5ffPVh5QcFikpWJI/P1ocHA=="], + + "tinyglobby": ["tinyglobby@0.2.17", "", { "dependencies": { "fdir": "^6.5.0", "picomatch": "^4.0.4" } }, "sha512-wXR/dYpcqKmfWpEdZjiKJOwCNFndD0DMnrW/cYjVGttEkBfVgcLFHoNrlj47mjOVic9yyNu65alsgF4NQyTa2g=="], + + "tinypool": ["tinypool@1.1.1", "", {}, "sha512-Zba82s87IFq9A9XmjiX5uZA/ARWDrB03OHlq+Vw1fSdt0I+4/Kutwy8BP4Y/y/aORMo61FQ0vIb5j44vSo5Pkg=="], + + "tinyrainbow": ["tinyrainbow@2.0.0", "", {}, "sha512-op4nsTR47R6p0vMUUoYl/a+ljLFVtlfaXkLQmqfLR1qHma1h/ysYk4hEXZ880bf2CYgTskvTa/e196Vd5dDQXw=="], + + "tinyspy": ["tinyspy@4.0.6", "", {}, "sha512-u8KszXvGfU68hVcZpRHKG28T0krMuv2G5nDhiHaMLen/gIuFEgIJhaJuO69qjnXg5paSrbPMFfx3brNuN8eVSg=="], + + "typescript": ["typescript@5.9.3", "", { "bin": { "tsc": "bin/tsc", "tsserver": "bin/tsserver" } }, "sha512-jl1vZzPDinLr9eUt3J/t7V6FgNEw9QjvBPdysz9KfQDD41fQrC2Y4vKQdiaUpFT4bXlb1RHhLpp8wtm6M5TgSw=="], + + "vite": ["vite@7.1.12", "", { "dependencies": { "esbuild": "^0.25.0", "fdir": "^6.5.0", "picomatch": "^4.0.3", "postcss": "^8.5.6", "rollup": "^4.43.0", "tinyglobby": "^0.2.15" }, "optionalDependencies": { "fsevents": "~2.3.3" }, "peerDependencies": { "@types/node": "^20.19.0 || >=22.12.0", "jiti": ">=1.21.0", "less": "^4.0.0", "lightningcss": "^1.21.0", "sass": "^1.70.0", "sass-embedded": "^1.70.0", "stylus": ">=0.54.8", "sugarss": "^5.0.0", "terser": "^5.16.0", "tsx": "^4.8.1", "yaml": "^2.4.2" }, "optionalPeers": ["@types/node", "jiti", "less", "lightningcss", "sass", "sass-embedded", "stylus", "sugarss", "terser", "tsx", "yaml"], "bin": { "vite": "bin/vite.js" } }, "sha512-ZWyE8YXEXqJrrSLvYgrRP7p62OziLW7xI5HYGWFzOvupfAlrLvURSzv/FyGyy0eidogEM3ujU+kUG1zuHgb6Ug=="], + + "vite-node": ["vite-node@3.2.4", "", { "dependencies": { "cac": "^6.7.14", "debug": "^4.4.1", "es-module-lexer": "^1.7.0", "pathe": "^2.0.3", "vite": "^5.0.0 || ^6.0.0 || ^7.0.0-0" }, "bin": { "vite-node": "vite-node.mjs" } }, "sha512-EbKSKh+bh1E1IFxeO0pg1n4dvoOTt0UDiXMd/qn++r98+jPO1xtJilvXldeuQ8giIB5IkpjCgMleHMNEsGH6pg=="], + + "vitest": ["vitest@3.2.4", "", { "dependencies": { "@types/chai": "^5.2.2", "@vitest/expect": "3.2.4", "@vitest/mocker": "3.2.4", "@vitest/pretty-format": "^3.2.4", "@vitest/runner": "3.2.4", "@vitest/snapshot": "3.2.4", "@vitest/spy": "3.2.4", "@vitest/utils": "3.2.4", "chai": "^5.2.0", "debug": "^4.4.1", "expect-type": "^1.2.1", "magic-string": "^0.30.17", "pathe": "^2.0.3", "picomatch": "^4.0.2", "std-env": "^3.9.0", "tinybench": "^2.9.0", "tinyexec": "^0.3.2", "tinyglobby": "^0.2.14", "tinypool": "^1.1.1", "tinyrainbow": "^2.0.0", "vite": "^5.0.0 || ^6.0.0 || ^7.0.0-0", "vite-node": "3.2.4", "why-is-node-running": "^2.3.0" }, "peerDependencies": { "@edge-runtime/vm": "*", "@types/debug": "^4.1.12", "@types/node": "^18.0.0 || ^20.0.0 || >=22.0.0", "@vitest/browser": "3.2.4", "@vitest/ui": "3.2.4", "happy-dom": "*", "jsdom": "*" }, "optionalPeers": ["@edge-runtime/vm", "@types/debug", "@types/node", "@vitest/browser", "@vitest/ui", "happy-dom", "jsdom"], "bin": { "vitest": "vitest.mjs" } }, "sha512-LUCP5ev3GURDysTWiP47wRRUpLKMOfPh+yKTx3kVIEiu5KOMeqzpnYNsKyOoVrULivR8tLcks4+lga33Whn90A=="], + + "why-is-node-running": ["why-is-node-running@2.3.0", "", { "dependencies": { "siginfo": "^2.0.0", "stackback": "0.0.2" }, "bin": { "why-is-node-running": "cli.js" } }, "sha512-hUrmaWBdVDcxvYqnyh09zunKzROWjbZTiNy8dBEjkS7ehEDQibXJ7XvlmtbwuTclUiIyN+CyXQD4Vmko8fNm8w=="], + } +} diff --git a/frontend/package.json b/frontend/package.json new file mode 100644 index 0000000..26b0c91 --- /dev/null +++ b/frontend/package.json @@ -0,0 +1,19 @@ +{ + "name": "solaredge-roof-card", + "private": true, + "type": "module", + "scripts": { + "build": "tsc --noEmit && vite build", + "test": "vitest run", + "typecheck": "tsc --noEmit" + }, + "dependencies": { + "three": "0.180.0" + }, + "devDependencies": { + "@types/three": "0.180.0", + "typescript": "5.9.3", + "vite": "7.1.12", + "vitest": "3.2.4" + } +} diff --git a/frontend/src/geometry.test.ts b/frontend/src/geometry.test.ts new file mode 100644 index 0000000..75a81c4 --- /dev/null +++ b/frontend/src/geometry.test.ts @@ -0,0 +1,30 @@ +import { describe, expect, it } from "vitest"; +import { deriveWalls } from "./geometry"; +import type { RoofConfig } from "./types"; + +describe("deriveWalls", () => { + it("puts walls under the outer edges of a gable roof but not under the ridge", () => { + const west: RoofConfig = { + name: "west", + outline: [ + [0, 0, 9], + [0, 10, 9], + [-4, 10, 5], + [-4, 0, 5], + ], + }; + const east: RoofConfig = { + name: "ost", + outline: [ + [0, 10, 9], + [0, 0, 9], + [4, 0, 5], + [4, 10, 5], + ], + }; + const walls = deriveWalls([west, east]); + expect(walls).toHaveLength(6); + const ridge = walls.filter((w) => w.from[0] === 0 && w.to[0] === 0); + expect(ridge).toHaveLength(0); + }); +}); diff --git a/frontend/src/geometry.ts b/frontend/src/geometry.ts new file mode 100644 index 0000000..103e5ec --- /dev/null +++ b/frontend/src/geometry.ts @@ -0,0 +1,71 @@ +import type { Point3, RoofConfig } from "./types"; + +/** A wall below one roof edge, from the ground up to the edge. */ +export interface Wall { + from: Point3; + to: Point3; +} + +const EDGE_TOLERANCE_M = 0.02; + +function samePlanPoint(a: Point3, b: Point3): boolean { + return Math.abs(a[0] - b[0]) < EDGE_TOLERANCE_M && Math.abs(a[1] - b[1]) < EDGE_TOLERANCE_M; +} + +/** + * Walls of the building: every roof edge that no other roof shares in the + * ground plan is extruded down to the ground. + */ +export function deriveWalls(roofs: readonly RoofConfig[]): Wall[] { + const edges = roofs.map((roof) => + roof.outline.map((point, i) => ({ + from: point, + to: roof.outline[(i + 1) % roof.outline.length]!, + })), + ); + const walls: Wall[] = []; + edges.forEach((roofEdges, roofIndex) => { + for (const edge of roofEdges) { + const shared = edges.some( + (other, otherIndex) => + otherIndex !== roofIndex && + other.some( + (o) => + (samePlanPoint(o.from, edge.from) && samePlanPoint(o.to, edge.to)) || + (samePlanPoint(o.from, edge.to) && samePlanPoint(o.to, edge.from)), + ), + ); + if (!shared) walls.push(edge); + } + }); + return walls; +} + +export interface Bounds { + min: Point3; + max: Point3; +} + +export function bounds(points: readonly Point3[]): Bounds { + const min: Point3 = [Infinity, Infinity, Infinity]; + const max: Point3 = [-Infinity, -Infinity, -Infinity]; + for (const p of points) { + for (let i = 0; i < 3; i++) { + min[i] = Math.min(min[i]!, p[i]!); + max[i] = Math.max(max[i]!, p[i]!); + } + } + return { min, max }; +} + +function distance(a: Point3, b: Point3): number { + return Math.hypot(a[0] - b[0], a[1] - b[1], a[2] - b[2]); +} + +/** Width (lower edge) and height (up-slope edge) of a panel in metres. */ +export function panelSize(corners: readonly [Point3, Point3, Point3, Point3]): { + width: number; + height: number; +} { + return { width: distance(corners[0], corners[1]), height: distance(corners[0], corners[3]) }; +} diff --git a/frontend/src/panel-state.test.ts b/frontend/src/panel-state.test.ts new file mode 100644 index 0000000..2aad515 --- /dev/null +++ b/frontend/src/panel-state.test.ts @@ -0,0 +1,96 @@ +import { describe, expect, it } from "vitest"; +import { + DEFAULT_MAX_POWER, + findPowerEntities, + powerColor, + resolvePanelStates, + textColorFor, +} from "./panel-state"; +import type { HassEntity } from "./types"; + +function sensor( + entityId: string, + state: string, + attributes: Record, +): HassEntity { + return { entity_id: entityId, state, attributes }; +} + +const power = (id: string, state: string, lastMeasurement?: string) => + sensor(`sensor.optimizer_${id.replaceAll(".", "_")}_aktuelle_leistung`, state, { + optimizer_id: id, + device_class: "power", + unit_of_measurement: "W", + last_measurement: lastMeasurement, + }); + +function statesOf(...entities: HassEntity[]): Record { + return Object.fromEntries(entities.map((e) => [e.entity_id, e])); +} + +describe("findPowerEntities", () => { + it("picks the power sensor of each panel, not the energy sensor", () => { + const states = statesOf( + power("1.1.1", "120"), + sensor("sensor.optimizer_1_1_1_tagesenergie", "800", { + optimizer_id: "1.1.1", + device_class: "energy", + }), + ); + expect(findPowerEntities(states, ["1.1.1", "1.1.2"])).toEqual( + new Map([["1.1.1", "sensor.optimizer_1_1_1_aktuelle_leistung"]]), + ); + }); +}); + +describe("resolvePanelStates", () => { + const ids = ["1.1.1", "1.1.2", "1.1.3", "1.1.4"]; + + it("distinguishes a value, 0 W, an unavailable entity and a missing entity", () => { + const states = statesOf( + power("1.1.1", "123.4", "2026-11-19T12:00:00+00:00"), + power("1.1.2", "0", "2026-11-19T12:00:00+00:00"), + power("1.1.3", "unavailable"), + ); + const { panels } = resolvePanelStates(states, findPowerEntities(states, ids), ids); + expect(panels.get("1.1.1")).toMatchObject({ status: "ok", power: 123.4 }); + expect(panels.get("1.1.2")).toMatchObject({ status: "ok", power: 0 }); + expect(panels.get("1.1.3")).toMatchObject({ status: "failed" }); + expect(panels.get("1.1.4")).toEqual({ status: "failed", entityId: undefined }); + }); + + it("reports the newest measurement and fails panels more than 30 minutes behind it", () => { + const states = statesOf( + power("1.1.1", "100", "2026-11-19T12:20:00+00:00"), + power("1.1.2", "100", "2026-11-19T12:00:00+00:00"), + power("1.1.3", "100", "2026-11-19T11:49:00+00:00"), + ); + const panelIds = ["1.1.1", "1.1.2", "1.1.3"]; + const { panels, newestMeasurement } = resolvePanelStates( + states, + findPowerEntities(states, panelIds), + panelIds, + ); + expect(newestMeasurement).toBe(Date.parse("2026-11-19T12:20:00+00:00")); + expect(panels.get("1.1.2")?.status).toBe("ok"); + expect(panels.get("1.1.3")?.status).toBe("failed"); + }); +}); + +describe("powerColor", () => { + it("runs from dark at 0 W to bright at the Skalenmaximum and clamps beyond", () => { + const luminance = ([r, g, b]: number[]) => 0.2126 * r! + 0.7152 * g! + 0.0722 * b!; + const dark = powerColor(0, DEFAULT_MAX_POWER); + const mid = powerColor(230, DEFAULT_MAX_POWER); + const bright = powerColor(460, DEFAULT_MAX_POWER); + expect(luminance(dark)).toBeLessThan(luminance(mid)); + expect(luminance(mid)).toBeLessThan(luminance(bright)); + expect(powerColor(900, DEFAULT_MAX_POWER)).toEqual(bright); + expect(powerColor(-5, DEFAULT_MAX_POWER)).toEqual(dark); + }); + + it("keeps the text readable", () => { + expect(textColorFor(powerColor(0, 460))).toBe("#ffffff"); + expect(textColorFor(powerColor(460, 460))).toBe("#1b1b1f"); + }); +}); diff --git a/frontend/src/panel-state.ts b/frontend/src/panel-state.ts new file mode 100644 index 0000000..a961f1b --- /dev/null +++ b/frontend/src/panel-state.ts @@ -0,0 +1,119 @@ +import type { HassEntity } from "./types"; + +/** A panel whose measurement is this much older than the newest one counts as failed. */ +export const STALE_AFTER_MS = 30 * 60 * 1000; + +export const DEFAULT_MAX_POWER = 460; + +export type PanelState = + | { status: "ok"; entityId: string; power: number; lastMeasurement?: number } + | { status: "failed"; entityId?: string }; + +/** Find the power entity of every panel by its optimizer_id attribute. */ +export function findPowerEntities( + states: Record, + panelIds: readonly string[], +): Map { + const wanted = new Set(panelIds); + const result = new Map(); + for (const entity of Object.values(states)) { + const id = entity.attributes.optimizer_id; + if ( + typeof id === "string" && + wanted.has(id) && + entity.attributes.device_class === "power" && + entity.entity_id.startsWith("sensor.") + ) { + result.set(id, entity.entity_id); + } + } + return result; +} + +function parseTime(value: unknown): number | undefined { + if (typeof value !== "string") return undefined; + const time = Date.parse(value); + return Number.isNaN(time) ? undefined : time; +} + +/** + * Work out every panel's state. + * + * A panel is failed ("ausgefallen") when it has no entity, no numeric value, + * or a measurement more than STALE_AFTER_MS older than the newest panel's. + * 0 W is a valid value (night), not a failure. + */ +export function resolvePanelStates( + states: Record, + entities: ReadonlyMap, + panelIds: readonly string[], +): { panels: Map; newestMeasurement?: number } { + const readings = new Map(); + let newest: number | undefined; + for (const id of panelIds) { + const entityId = entities.get(id); + const entity = entityId ? states[entityId] : undefined; + if (!entityId || !entity) { + readings.set(id, { status: "failed", entityId }); + continue; + } + const power = Number(entity.state); + if (entity.state === "" || !Number.isFinite(power)) { + readings.set(id, { status: "failed", entityId }); + continue; + } + const lastMeasurement = parseTime(entity.attributes.last_measurement); + if (lastMeasurement !== undefined && (newest === undefined || lastMeasurement > newest)) { + newest = lastMeasurement; + } + readings.set(id, { status: "ok", entityId, power, lastMeasurement }); + } + if (newest !== undefined) { + for (const [id, reading] of readings) { + if ( + reading.status === "ok" && + reading.lastMeasurement !== undefined && + newest - reading.lastMeasurement > STALE_AFTER_MS + ) { + readings.set(id, { status: "failed", entityId: reading.entityId }); + } + } + } + return { panels: readings, newestMeasurement: newest }; +} + +type Rgb = [number, number, number]; + +const COLOR_STOPS: Array<[number, Rgb]> = [ + [0, [22, 32, 58]], + [0.5, [44, 104, 214]], + [1, [255, 214, 74]], +]; + +/** Colour for a power value: dark at 0 W, brightest at maxPower and above. */ +export function powerColor(power: number, maxPower: number): Rgb { + const t = Math.min(1, Math.max(0, maxPower > 0 ? power / maxPower : 0)); + for (let i = 1; i < COLOR_STOPS.length; i++) { + const [end, to] = COLOR_STOPS[i]!; + const [start, from] = COLOR_STOPS[i - 1]!; + if (t <= end) { + const f = (t - start) / (end - start); + return [0, 1, 2].map((c) => Math.round(from[c]! + (to[c]! - from[c]!) * f)) as Rgb; + } + } + return COLOR_STOPS[COLOR_STOPS.length - 1]![1]; +} + +/** Text colour that stays readable on the given background. */ +export function textColorFor([r, g, b]: Rgb): string { + const luminance = (0.2126 * r + 0.7152 * g + 0.0722 * b) / 255; + return luminance > 0.55 ? "#1b1b1f" : "#ffffff"; +} + +export function formatPower(power: number): string { + return `${Math.round(power)} W`; +} + +export function colorGradientCss(): string { + return COLOR_STOPS.map(([t, [r, g, b]]) => `rgb(${r},${g},${b}) ${t * 100}%`).join(", "); +} diff --git a/frontend/src/scene.ts b/frontend/src/scene.ts new file mode 100644 index 0000000..ff10afa --- /dev/null +++ b/frontend/src/scene.ts @@ -0,0 +1,311 @@ +import { + AmbientLight, + BufferAttribute, + BufferGeometry, + CanvasTexture, + CircleGeometry, + Color, + DirectionalLight, + DoubleSide, + Mesh, + MeshBasicMaterial, + MeshLambertMaterial, + PerspectiveCamera, + Raycaster, + Scene, + SRGBColorSpace, + Vector2, + Vector3, + WebGLRenderer, +} from "three"; +import { OrbitControls } from "three/examples/jsm/controls/OrbitControls.js"; +import { bounds, deriveWalls, panelSize } from "./geometry"; +import { formatPower, powerColor, textColorFor, type PanelState } from "./panel-state"; +import type { PanelConfig, Point3, RoofConfig } from "./types"; + +/** Model coordinates (x east, y north, z up) to three.js (y up, z south). */ +function toThree([x, y, z]: Point3): Vector3 { + return new Vector3(x, z, -y); +} + +function quadGeometry(points: Vector3[], withUv: boolean): BufferGeometry { + const geometry = new BufferGeometry(); + const positions: number[] = []; + for (let i = 1; i < points.length - 1; i++) { + for (const p of [points[0]!, points[i]!, points[i + 1]!]) positions.push(p.x, p.y, p.z); + } + geometry.setAttribute("position", new BufferAttribute(new Float32Array(positions), 3)); + if (withUv) { + const uv = [0, 0, 1, 0, 1, 1, 0, 0, 1, 1, 0, 1]; + geometry.setAttribute("uv", new BufferAttribute(new Float32Array(uv), 2)); + } + geometry.computeVertexNormals(); + return geometry; +} + +const PIXELS_PER_METRE = 220; + +interface PanelView { + config: PanelConfig; + mesh: Mesh; + canvas: HTMLCanvasElement; + texture: CanvasTexture; + key?: string; +} + +export interface SceneColors { + background: string; + ground: string; + wall: string; + roof: string; +} + +export class RoofScene { + readonly element: HTMLCanvasElement; + private readonly renderer: WebGLRenderer; + private readonly scene = new Scene(); + private readonly camera = new PerspectiveCamera(35, 1, 0.1, 500); + private readonly controls: OrbitControls; + private readonly panels = new Map(); + private readonly target: Vector3; + private readonly homePosition: Vector3; + private renderQueued = false; + private pointerDown?: Vector2; + private readonly materials: { ground: MeshLambertMaterial; wall: MeshLambertMaterial; roof: MeshLambertMaterial }; + + constructor( + roofs: RoofConfig[], + panels: PanelConfig[], + colors: SceneColors, + private readonly onPanelClick: (panelId: string) => void, + ) { + this.renderer = new WebGLRenderer({ antialias: true, alpha: true }); + this.renderer.outputColorSpace = SRGBColorSpace; + this.renderer.setPixelRatio(Math.min(window.devicePixelRatio, 2)); + this.element = this.renderer.domElement; + this.element.style.touchAction = "none"; + + this.scene.add(new AmbientLight(0xffffff, 1.6)); + const sun = new DirectionalLight(0xffffff, 1.8); + sun.position.set(-8, 20, 12); + this.scene.add(sun); + + this.materials = { + ground: new MeshLambertMaterial({ side: DoubleSide }), + wall: new MeshLambertMaterial({ side: DoubleSide }), + roof: new MeshLambertMaterial({ side: DoubleSide }), + }; + this.setColors(colors); + + const all = [...roofs.flatMap((r) => r.outline), ...panels.flatMap((p) => p.corners)]; + const box = bounds(all); + const centre: Point3 = [ + (box.min[0] + box.max[0]) / 2, + (box.min[1] + box.max[1]) / 2, + 0, + ]; + const span = Math.max(box.max[0] - box.min[0], box.max[1] - box.min[1], box.max[2]); + + const ground = new Mesh(new CircleGeometry(span * 1.6, 64), this.materials.ground); + ground.rotation.x = -Math.PI / 2; + ground.position.copy(toThree(centre)); + ground.position.y = -0.01; + this.scene.add(ground); + + for (const roof of roofs) { + this.scene.add(new Mesh(quadGeometry(roof.outline.map(toThree), false), this.materials.roof)); + } + for (const wall of deriveWalls(roofs)) { + const points = [ + toThree([wall.from[0], wall.from[1], 0]), + toThree([wall.to[0], wall.to[1], 0]), + toThree(wall.to), + toThree(wall.from), + ]; + this.scene.add(new Mesh(quadGeometry(points, false), this.materials.wall)); + } + for (const panel of panels) this.addPanel(panel); + + this.target = toThree([centre[0], centre[1], box.max[2] * 0.45]); + const distance = span * 2.3; + // Seen from the south-south-east and from above, like the portal. + this.homePosition = this.target + .clone() + .add(new Vector3(distance * 0.18, distance * 0.78, distance * 0.6)); + this.camera.position.copy(this.homePosition); + + this.controls = new OrbitControls(this.camera, this.element); + this.controls.target.copy(this.target); + this.controls.maxPolarAngle = Math.PI / 2 - 0.05; + this.controls.minDistance = span * 0.6; + this.controls.maxDistance = span * 5; + this.controls.addEventListener("change", () => this.requestRender()); + this.controls.update(); + + this.element.addEventListener("pointerdown", (event) => { + this.pointerDown = new Vector2(event.clientX, event.clientY); + }); + this.element.addEventListener("pointerup", (event) => this.handlePointerUp(event)); + } + + setColors(colors: SceneColors): void { + this.materials.ground.color = new Color(colors.ground); + this.materials.wall.color = new Color(colors.wall); + this.materials.roof.color = new Color(colors.roof); + this.requestRender(); + } + + private addPanel(config: PanelConfig): void { + const { width, height } = panelSize(config.corners); + const canvas = document.createElement("canvas"); + canvas.width = Math.round(width * PIXELS_PER_METRE); + canvas.height = Math.round(height * PIXELS_PER_METRE); + const texture = new CanvasTexture(canvas); + texture.colorSpace = SRGBColorSpace; + texture.anisotropy = 4; + const material = new MeshBasicMaterial({ map: texture, side: DoubleSide }); + const mesh = new Mesh(quadGeometry(config.corners.map(toThree), true), material); + mesh.userData.panelId = config.id; + this.scene.add(mesh); + this.panels.set(config.id, { config, mesh, canvas, texture }); + } + + /** Repaint the panels whose state changed. */ + updatePanels(states: ReadonlyMap, maxPower: number): void { + let changed = false; + for (const [id, view] of this.panels) { + const state = states.get(id) ?? { status: "failed" as const }; + const key = + state.status === "ok" ? `${Math.round(state.power)}|${maxPower}` : "failed"; + if (key === view.key) continue; + view.key = key; + paintPanel(view.canvas, id, state, maxPower); + view.texture.needsUpdate = true; + changed = true; + } + if (changed) this.requestRender(); + } + + resetView(): void { + this.camera.position.copy(this.homePosition); + this.controls.target.copy(this.target); + this.controls.update(); + } + + setSize(width: number, height: number): void { + if (width <= 0 || height <= 0) return; + this.renderer.setSize(width, height, false); + this.camera.aspect = width / height; + this.camera.updateProjectionMatrix(); + this.render(); + } + + requestRender(): void { + if (this.renderQueued) return; + this.renderQueued = true; + requestAnimationFrame(() => { + this.renderQueued = false; + this.render(); + }); + } + + private render(): void { + this.renderer.render(this.scene, this.camera); + } + + private handlePointerUp(event: PointerEvent): void { + const start = this.pointerDown; + this.pointerDown = undefined; + if (!start || start.distanceTo(new Vector2(event.clientX, event.clientY)) > 6) return; + const rect = this.element.getBoundingClientRect(); + const pointer = new Vector2( + ((event.clientX - rect.left) / rect.width) * 2 - 1, + -((event.clientY - rect.top) / rect.height) * 2 + 1, + ); + const raycaster = new Raycaster(); + raycaster.setFromCamera(pointer, this.camera); + const meshes = [...this.panels.values()].map((p) => p.mesh); + const hit = raycaster.intersectObjects(meshes, false)[0]; + const panelId = hit?.object.userData.panelId; + if (typeof panelId === "string") this.onPanelClick(panelId); + } + + dispose(): void { + this.controls.dispose(); + for (const view of this.panels.values()) { + view.texture.dispose(); + view.mesh.geometry.dispose(); + (view.mesh.material as MeshBasicMaterial).dispose(); + } + this.scene.traverse((object) => { + if (object instanceof Mesh) object.geometry.dispose(); + }); + Object.values(this.materials).forEach((m) => m.dispose()); + this.renderer.dispose(); + } +} + +function paintPanel( + canvas: HTMLCanvasElement, + panelId: string, + state: PanelState, + maxPower: number, +): void { + const ctx = canvas.getContext("2d"); + if (!ctx) return; + const { width: w, height: h } = canvas; + const failed = state.status !== "ok"; + const rgb = failed ? ([96, 100, 108] as const) : powerColor(state.power, maxPower); + const text = failed ? "#ffffff" : textColorFor([rgb[0], rgb[1], rgb[2]]); + + ctx.fillStyle = `rgb(${rgb[0]},${rgb[1]},${rgb[2]})`; + ctx.fillRect(0, 0, w, h); + + if (failed) { + ctx.strokeStyle = "rgba(255,255,255,0.18)"; + ctx.lineWidth = Math.max(4, w / 40); + for (let x = -h; x < w; x += w / 6) { + ctx.beginPath(); + ctx.moveTo(x, h); + ctx.lineTo(x + h, 0); + ctx.stroke(); + } + } else { + // Cell grid, like a real module. + ctx.strokeStyle = "rgba(255,255,255,0.12)"; + ctx.lineWidth = 2; + const cols = w > h ? 8 : 4; + const rows = w > h ? 4 : 8; + for (let i = 1; i < cols; i++) { + ctx.beginPath(); + ctx.moveTo((w / cols) * i, 0); + ctx.lineTo((w / cols) * i, h); + ctx.stroke(); + } + for (let i = 1; i < rows; i++) { + ctx.beginPath(); + ctx.moveTo(0, (h / rows) * i); + ctx.lineTo(w, (h / rows) * i); + ctx.stroke(); + } + } + + const border = Math.max(6, Math.min(w, h) / 22); + ctx.strokeStyle = failed ? "#e5484d" : "rgba(10,14,24,0.85)"; + ctx.lineWidth = border; + ctx.strokeRect(border / 2, border / 2, w - border, h - border); + + // The canvas top maps to the panel's upper (up-slope) edge, so text reads + // upright when looking up the roof. + const value = failed ? "–" : formatPower(state.power); + const base = Math.min(w, h); + ctx.fillStyle = text; + ctx.textAlign = "center"; + ctx.textBaseline = "middle"; + ctx.font = `700 ${Math.round(base * 0.3)}px system-ui, sans-serif`; + ctx.fillText(value, w / 2, h * 0.44, w * 0.9); + ctx.font = `500 ${Math.round(base * 0.16)}px system-ui, sans-serif`; + ctx.globalAlpha = 0.85; + ctx.fillText(panelId, w / 2, h * 0.78, w * 0.9); + ctx.globalAlpha = 1; +} diff --git a/frontend/src/solaredge-roof-card.ts b/frontend/src/solaredge-roof-card.ts new file mode 100644 index 0000000..1c08aeb --- /dev/null +++ b/frontend/src/solaredge-roof-card.ts @@ -0,0 +1,192 @@ +import { + colorGradientCss, + DEFAULT_MAX_POWER, + findPowerEntities, + resolvePanelStates, +} from "./panel-state"; +import { RoofScene, type SceneColors } from "./scene"; +import type { Hass, RoofCardConfig } from "./types"; + +const CARD_TYPE = "solaredge-roof-card"; +const RESET_ICON = + "M12,4C14.1,4 16.1,4.8 17.6,6.3C20.7,9.4 20.7,14.5 17.6,17.6C15.8,19.5 13.3,20.2 10.9,19.9L11.4,17.9C13.1,18.1 14.9,17.5 16.2,16.2C18.5,13.9 18.5,10.1 16.2,7.7C15.1,6.6 13.5,6 12,6V10.6L7,5.6L12,0.6V4M6.3,17.6C3.7,15 3.3,11 5.1,7.9L6.6,9.4C5.5,11.6 5.9,14.4 7.8,16.2C8.3,16.7 8.9,17.1 9.6,17.4L9,19.4C8,19 7.1,18.4 6.3,17.6Z"; + +class SolarEdgeRoofCard extends HTMLElement { + private config?: RoofCardConfig; + private _hass?: Hass; + private scene?: RoofScene; + private resizeObserver?: ResizeObserver; + private entities = new Map(); + private entityCount = -1; + private readonly root: ShadowRoot; + private stage?: HTMLDivElement; + private status?: HTMLSpanElement; + private legendMax?: HTMLSpanElement; + + constructor() { + super(); + this.root = this.attachShadow({ mode: "open" }); + } + + static getStubConfig(): Partial { + return { layout: { roofs: [], panels: [] } }; + } + + setConfig(config: RoofCardConfig): void { + if (!config?.layout || !Array.isArray(config.layout.panels) || !Array.isArray(config.layout.roofs)) { + throw new Error("layout.roofs und layout.panels fehlen"); + } + if (config.max_power !== undefined && !(Number(config.max_power) > 0)) { + throw new Error("max_power muss größer als 0 sein"); + } + this.config = config; + this.entityCount = -1; + this.teardownScene(); + this.renderShell(); + if (this.isConnected) this.setupScene(); + } + + set hass(hass: Hass) { + this._hass = hass; + this.update(); + } + + getCardSize(): number { + return 8; + } + + getGridOptions(): Record { + return { columns: 12, min_columns: 6, min_rows: 6 }; + } + + connectedCallback(): void { + if (this.config && !this.scene) this.setupScene(); + } + + disconnectedCallback(): void { + this.teardownScene(); + } + + private get maxPower(): number { + return Number(this.config?.max_power ?? DEFAULT_MAX_POWER); + } + + private renderShell(): void { + const title = this.config?.title ?? "Dach"; + this.root.innerHTML = ` + + +
+

+ + +
+
+
+ 0 W + ausgefallen +
+
`; + this.root.querySelector("h2")!.textContent = title; + this.stage = this.root.querySelector(".stage")!; + this.status = this.root.querySelector(".status")!; + this.legendMax = this.root.querySelector(".max")!; + this.legendMax.textContent = `${this.maxPower} W`; + this.root.querySelector("button")!.addEventListener("click", () => this.scene?.resetView()); + } + + private sceneColors(): SceneColors { + const style = getComputedStyle(this); + const dark = this._hass && (this._hass as { themes?: { darkMode?: boolean } }).themes?.darkMode; + return { + background: style.getPropertyValue("--card-background-color") || "#fff", + ground: dark ? "#2a2f2a" : "#cfd6c8", + wall: dark ? "#8a8d92" : "#e4e2dc", + roof: dark ? "#4b4f56" : "#7b7f86", + }; + } + + private setupScene(): void { + if (!this.config || !this.stage) return; + const { roofs, panels } = this.config.layout; + this.scene = new RoofScene(roofs, panels, this.sceneColors(), (panelId) => + this.openMoreInfo(panelId), + ); + this.stage.append(this.scene.element); + this.resizeObserver = new ResizeObserver(() => { + if (!this.stage || !this.scene) return; + this.scene.setSize(this.stage.clientWidth, this.stage.clientHeight); + }); + this.resizeObserver.observe(this.stage); + this.update(); + } + + private teardownScene(): void { + this.resizeObserver?.disconnect(); + this.resizeObserver = undefined; + this.scene?.element.remove(); + this.scene?.dispose(); + this.scene = undefined; + } + + private update(): void { + const hass = this._hass; + const config = this.config; + if (!hass || !config) return; + const panelIds = config.layout.panels.map((p) => p.id); + const stateCount = Object.keys(hass.states).length; + if (stateCount !== this.entityCount) { + this.entities = findPowerEntities(hass.states, panelIds); + this.entityCount = stateCount; + } + const { panels, newestMeasurement } = resolvePanelStates(hass.states, this.entities, panelIds); + this.scene?.updatePanels(panels, this.maxPower); + if (this.status) { + const language = hass.locale?.language ?? hass.language ?? "de"; + this.status.textContent = + newestMeasurement === undefined + ? "Stand: –" + : `Stand: ${new Date(newestMeasurement).toLocaleTimeString(language, { + hour: "2-digit", + minute: "2-digit", + })}`; + } + } + + private openMoreInfo(panelId: string): void { + const entityId = this.entities.get(panelId); + if (!entityId) return; + this.dispatchEvent( + new CustomEvent("hass-more-info", { detail: { entityId }, bubbles: true, composed: true }), + ); + } +} + +if (!customElements.get(CARD_TYPE)) { + customElements.define(CARD_TYPE, SolarEdgeRoofCard); + const cards = ((window as unknown as { customCards?: unknown[] }).customCards ??= []); + cards.push({ + type: CARD_TYPE, + name: "SolarEdge Dach", + description: "3D-Dachansicht mit der aktuellen Leistung jedes Panels", + }); +} diff --git a/frontend/src/types.ts b/frontend/src/types.ts new file mode 100644 index 0000000..f1e7110 --- /dev/null +++ b/frontend/src/types.ts @@ -0,0 +1,40 @@ +/** A point in metres: x = east, y = north, z = up. */ +export type Point3 = [number, number, number]; + +export interface RoofConfig { + /** Name of the Dachfläche, e.g. "west1". */ + name: string; + /** Outline of the roof surface in drawing order. */ + outline: Point3[]; +} + +export interface PanelConfig { + /** Panel-Position, e.g. "1.2.7". */ + id: string; + roof?: string; + /** Lower left, lower right, upper right, upper left (upper = up-slope). */ + corners: [Point3, Point3, Point3, Point3]; +} + +export interface RoofCardConfig { + type: string; + title?: string; + /** Skalenmaximum in W: power at which a panel reaches the brightest colour. */ + max_power?: number; + layout: { + roofs: RoofConfig[]; + panels: PanelConfig[]; + }; +} + +export interface HassEntity { + entity_id: string; + state: string; + attributes: Record; +} + +export interface Hass { + states: Record; + locale?: { language?: string }; + language?: string; +} diff --git a/frontend/tsconfig.json b/frontend/tsconfig.json new file mode 100644 index 0000000..d2a75ef --- /dev/null +++ b/frontend/tsconfig.json @@ -0,0 +1,13 @@ +{ + "compilerOptions": { + "target": "ES2022", + "module": "ESNext", + "moduleResolution": "bundler", + "lib": ["ES2022", "DOM", "DOM.Iterable"], + "strict": true, + "noUncheckedIndexedAccess": true, + "skipLibCheck": true, + "types": [] + }, + "include": ["src", "vite.config.ts"] +} diff --git a/frontend/vite.config.ts b/frontend/vite.config.ts new file mode 100644 index 0000000..e56ab72 --- /dev/null +++ b/frontend/vite.config.ts @@ -0,0 +1,19 @@ +import { defineConfig } from "vite"; + +export default defineConfig({ + build: { + lib: { + entry: "src/solaredge-roof-card.ts", + formats: ["es"], + fileName: () => "solaredge-roof-card.js", + }, + outDir: "../custom_components/solaredge_optimizers/frontend", + emptyOutDir: true, + target: "es2022", + minify: true, + sourcemap: false, + }, + test: { + environment: "node", + }, +}); diff --git a/pyproject.toml b/pyproject.toml index 462a431..6c670e7 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -1,6 +1,6 @@ [project] name = "ha-solaredge-optimizers" -version = "0.4.0" +version = "0.5.0" description = "Home Assistant custom integration for SolarEdge optimizer data" readme = "README.md" requires-python = ">=3.14.2" diff --git a/scripts/convert_portal_layout.py b/scripts/convert_portal_layout.py new file mode 100644 index 0000000..6be479c --- /dev/null +++ b/scripts/convert_portal_layout.py @@ -0,0 +1,392 @@ +"""Convert the SolarEdge portal's site model into a solaredge-roof-card layout. + +The SolarEdge Monitoring portal renders its 3D site view from two documents: + +* ``GET /services/layout/physical/site/{siteId}`` (the *physical layout*), which + lists the strings with their optimizers in display order and links to +* the *site model* (``awsJsonModelDownloadLink``), which holds roof polygons, + vertex heights and module groups in metres (x = east, y = north, z = up). + +This script reads both files once and prints the ``layout`` block for the card +configuration. Nothing in Home Assistant depends on the portal afterwards. + +Usage:: + + python scripts/convert_portal_layout.py physical.json model.json \ + [--areas areas.json] > layout.yaml + +``areas.json`` uses the same format as the integration's area mapping +(``{"west1": ["1.1.1", ...]}``) and names the roofs after the areas of the +panels on them. +""" + +from __future__ import annotations + +import argparse +import json +import math +import sys +from collections import Counter +from dataclasses import dataclass +from typing import Any + +MODULE_OFFSET_M = 0.05 +"""Height of a panel above its roof surface, so the two never z-fight.""" + +FLAT_ROOF_SLOPE = 0.02 +"""Roofs with a smaller slope (rise per metre) count as flat.""" + +type Point2 = tuple[float, float] +type Point3 = tuple[float, float, float] + + +@dataclass(frozen=True) +class Plane: + """Roof plane z = a*x + b*y + c.""" + + a: float + b: float + c: float + + def z(self, x: float, y: float) -> float: + """Return the plane height at (x, y).""" + return self.a * x + self.b * y + self.c + + +@dataclass(frozen=True) +class Panel: + """One panel with its corners in the card's coordinate system.""" + + panel_id: str + roof_id: str + corners: tuple[Point3, Point3, Point3, Point3] + """Lower left, lower right, upper right, upper left (upper = up-slope).""" + + +def decode_module_handle(handle: int) -> tuple[int, int]: + """Return (row, column) of a module handle id. + + The low 32 bits are the module group id, followed by an 11-bit signed row + and an 11-bit signed column. + """ + upper = handle >> 32 + row = upper & 0x7FF + column = (upper >> 11) & 0x7FF + if row >= 1024: + row -= 2048 + if column >= 1024: + column -= 2048 + return row, column + + +def polygon_outline(model: dict[str, Any], polygon_id: str) -> list[Point3]: + """Return the polygon's vertices in edge order.""" + vertices = model["vertices"] + edges = model["edges"] + pairs = [ + (edges[edge_id]["vertexAId"], edges[edge_id]["vertexBId"]) + for edge_id in model["polygons"][polygon_id]["edgeIds"] + ] + loop = [pairs[0][0], pairs[0][1]] + remaining = pairs[1:] + while remaining: + edge = next((pair for pair in remaining if loop[-1] in pair), None) + if edge is None: + msg = f"Polygon {polygon_id} is not a closed loop" + raise ValueError(msg) + remaining.remove(edge) + loop.append(edge[1] if edge[0] == loop[-1] else edge[0]) + if loop[0] == loop[-1]: + loop.pop() + return [ + ( + vertices[vertex_id]["position"]["x"], + vertices[vertex_id]["position"]["y"], + vertices[vertex_id]["heightWithoutPolygonGroups"], + ) + for vertex_id in loop + ] + + +def fit_plane(points: list[Point3]) -> Plane: + """Least-squares plane through the points.""" + n = len(points) + sx = sum(p[0] for p in points) + sy = sum(p[1] for p in points) + sz = sum(p[2] for p in points) + sxx = sum(p[0] * p[0] for p in points) + syy = sum(p[1] * p[1] for p in points) + sxy = sum(p[0] * p[1] for p in points) + sxz = sum(p[0] * p[2] for p in points) + syz = sum(p[1] * p[2] for p in points) + a, b, c = _solve3( + [[sxx, sxy, sx], [sxy, syy, sy], [sx, sy, float(n)]], [sxz, syz, sz] + ) + return Plane(a, b, c) + + +def _solve3(matrix: list[list[float]], rhs: list[float]) -> list[float]: + rows = [row[:] + [value] for row, value in zip(matrix, rhs, strict=True)] + for col in range(3): + pivot = max(range(col, 3), key=lambda r: abs(rows[r][col])) + rows[col], rows[pivot] = rows[pivot], rows[col] + for r in range(3): + if r != col: + factor = rows[r][col] / rows[col][col] + rows[r] = [ + x - factor * y for x, y in zip(rows[r], rows[col], strict=True) + ] + return [rows[i][3] / rows[i][i] for i in range(3)] + + +def point_in_polygon(point: Point2, outline: list[Point3], tolerance: float) -> bool: + """Return whether the point lies inside or within tolerance of the outline.""" + x, y = point + inside = False + edges = list(zip(outline, outline[1:] + outline[:1], strict=True)) + for (x1, y1, _), (x2, y2, _) in edges: + if (y1 > y) != (y2 > y) and x < (x2 - x1) * (y - y1) / (y2 - y1) + x1: + inside = not inside + if inside: + return True + for (x1, y1, _), (x2, y2, _) in edges: + dx, dy = x2 - x1, y2 - y1 + t = max(0.0, min(1.0, ((x - x1) * dx + (y - y1) * dy) / (dx * dx + dy * dy))) + if math.hypot(x - x1 - t * dx, y - y1 - t * dy) <= tolerance: + return True + return False + + +def module_group_panels( + group: dict[str, Any], + details: dict[str, Any], + module_size: tuple[float, float], + row_sign: int, + rotation: float, +) -> list[tuple[int, list[Point2], Point2]]: + """Place the modules of one group on the ground plan. + + Returns (handle, plan corners, up-slope unit vector) per module. Columns run + along the eave, rows up the slope; the group position is the outer corner of + module (0, 0). The up-slope vector is the direction in which the module + rises, taken from its azimuth. + """ + azimuth = details["azimuth"] + tilt = details["tilt"] + up = (-math.sin(azimuth), -math.cos(azimuth)) + along = (-math.cos(azimuth), math.sin(azimuth)) + length, width = module_size + if group["orientation"] == "PORTRAIT": + cell_w, cell_h = width, length + else: + cell_w, cell_h = length, width + # The portal measures columns along -along, so its rotation runs the other way. + cos_r, sin_r = math.cos(rotation), -math.sin(rotation) + cos_t = math.cos(tilt) + origin = (group["position"]["x"], group["position"]["y"]) + + def to_plan(u: float, v: float) -> Point2: + u, v = u * cos_r - v * sin_r, u * sin_r + v * cos_r + v *= cos_t + return ( + origin[0] + u * along[0] + v * up[0], + origin[1] + u * along[1] + v * up[1], + ) + + result = [] + for handle in details["moduleHandleIds"]: + row, column = decode_module_handle(handle) + u0 = column * (cell_w + group["columnSpacing"]) + v0 = row_sign * row * (cell_h + group["rowSpacing"]) + v_low = v0 if row_sign > 0 else v0 - cell_h + corners = [ + to_plan(u0, v_low), + to_plan(u0 + cell_w, v_low), + to_plan(u0 + cell_w, v_low + cell_h), + to_plan(u0, v_low + cell_h), + ] + result.append((handle, corners, up)) + return result + + +def _order_corners(corners: list[Point2], up: Point2) -> list[Point2]: + """Order corners lower-left, lower-right, upper-right, upper-left. + + Seen from above with up-slope pointing up, "right" is up rotated clockwise. + """ + right = (up[1], -up[0]) + cx = sum(p[0] for p in corners) / 4 + cy = sum(p[1] for p in corners) / 4 + + def key(p: Point2) -> tuple[bool, bool]: + dx, dy = p[0] - cx, p[1] - cy + return (dx * up[0] + dy * up[1] > 0, dx * right[0] + dy * right[1] > 0) + + by_key = {key(p): p for p in corners} + return [ + by_key[(False, False)], + by_key[(False, True)], + by_key[(True, True)], + by_key[(True, False)], + ] + + +def convert( + physical: dict[str, Any], + site_model: dict[str, Any], + areas: dict[str, list[str]] | None = None, +) -> dict[str, Any]: + """Build the card layout from the portal documents.""" + model = site_model["modelData"] + group_details = site_model["moduleGroupDetails"] + module_model = next(iter(model["moduleModels"].values())) + module_size = (module_model["length"] / 1000, module_model["width"] / 1000) + + devices = physical["physicalDevicesMap"] + serial_to_panel_id: dict[str, str] = {} + strings = devices["strings"].values() + inverters = devices["inverters"] + for string in strings: + inverter_seq = inverters[string["inverterId"]]["sequenceNumber"] + for position, optimizer_key in enumerate(string["optimizerIds"], start=1): + serial = devices["optimizers"][str(optimizer_key)]["serialNumber"] + serial_to_panel_id[serial] = ( + f"{inverter_seq}.{string['sequenceNumber']}.{position}" + ) + handle_to_panel_id = { + int(optimizer["moduleIds"][0]): serial_to_panel_id[optimizer["serialNumber"]] + for optimizer in model["optimizers"].values() + if optimizer["moduleIds"] and optimizer["serialNumber"] in serial_to_panel_id + } + + outlines = {pid: polygon_outline(model, pid) for pid in model["polygons"]} + planes = {pid: fit_plane(points) for pid, points in outlines.items()} + + panels: list[Panel] = [] + for group_id, details in group_details.items(): + group = model["moduleGroups"][group_id] + polygon_id = group["polygonId"] + outline = outlines[polygon_id] + # The portal flips the row direction for some groups (seen on a rotated + # group on a flat roof). Pick the direction that keeps the modules on + # their roof. + plane = planes[polygon_id] + # On a flat roof the module azimuth already fixes the grid direction and + # facetRotation is an absolute angle that would rotate it a second time. + flat = math.hypot(plane.a, plane.b) < FLAT_ROOF_SLOPE + rotation = 0.0 if flat else group["facetRotation"] + candidates = [ + module_group_panels(group, details, module_size, sign, rotation) + for sign in (1, -1) + ] + placed = max( + candidates, + key=lambda modules: sum( + point_in_polygon(corner, outline, 0.05) + for _, corners, _ in modules + for corner in corners + ), + ) + module_tilt = math.tan(details["tilt"]) + for handle, corners, up in placed: + panel_id = handle_to_panel_id.get(handle) + if panel_id is None: + continue + ordered = _order_corners(corners, up) + cx = sum(p[0] for p in ordered) / 4 + cy = sum(p[1] for p in ordered) / 4 + base = plane.z(cx, cy) + MODULE_OFFSET_M + corners3 = tuple( + ( + p[0], + p[1], + base + ((p[0] - cx) * up[0] + (p[1] - cy) * up[1]) * module_tilt, + ) + for p in ordered + ) + panels.append(Panel(panel_id, polygon_id, corners3)) + + roof_names = _roof_names(outlines, panels, areas or {}) + panels.sort( + key=lambda panel: tuple(int(part) for part in panel.panel_id.split(".")) + ) + return { + "module_power": module_model["stcPower"], + "roofs": [ + {"name": roof_names[pid], "outline": [_round3(p) for p in outline]} + for pid, outline in outlines.items() + ], + "panels": [ + { + "id": panel.panel_id, + "roof": roof_names[panel.roof_id], + "corners": [_round3(p) for p in panel.corners], + } + for panel in panels + ], + } + + +def _roof_names( + outlines: dict[str, list[Point3]], + panels: list[Panel], + areas: dict[str, list[str]], +) -> dict[str, str]: + panel_area = { + panel_id: area for area, panel_ids in areas.items() for panel_id in panel_ids + } + names: dict[str, str] = {} + for index, polygon_id in enumerate(outlines, start=1): + votes = Counter( + panel_area[panel.panel_id] + for panel in panels + if panel.roof_id == polygon_id and panel.panel_id in panel_area + ) + names[polygon_id] = votes.most_common(1)[0][0] if votes else f"dach{index}" + return names + + +def _round3(point: Point3) -> list[float]: + return [round(value, 3) for value in point] + + +def to_yaml(layout: dict[str, Any]) -> str: + """Render the layout as a compact YAML block for the card configuration.""" + lines = [ + "type: custom:solaredge-roof-card", + f"max_power: {layout['module_power']:g}", + "layout:", + " roofs:", + ] + for roof in layout["roofs"]: + lines.append(f" - name: {json.dumps(roof['name'], ensure_ascii=False)}") + lines.append(f" outline: {json.dumps(roof['outline'])}") + lines.append(" panels:") + for panel in layout["panels"]: + lines.append(f' - id: "{panel["id"]}"') + lines.append(f" roof: {json.dumps(panel['roof'], ensure_ascii=False)}") + lines.append(f" corners: {json.dumps(panel['corners'])}") + return "\n".join(lines) + "\n" + + +def main(argv: list[str] | None = None) -> int: + """Run the converter.""" + parser = argparse.ArgumentParser(description=__doc__.splitlines()[0]) + parser.add_argument("physical", help="physical layout response (JSON)") + parser.add_argument("model", help="site model from awsJsonModelDownloadLink") + parser.add_argument("--areas", help="area mapping JSON used to name roofs") + args = parser.parse_args(argv) + with open(args.physical, encoding="utf-8") as file: + physical = json.load(file) + with open(args.model, encoding="utf-8") as file: + site_model = json.load(file) + areas = None + if args.areas: + with open(args.areas, encoding="utf-8") as file: + areas = json.load(file) + sys.stdout.write(to_yaml(convert(physical, site_model, areas))) + return 0 + + +if __name__ == "__main__": + raise SystemExit(main()) diff --git a/tests/test_convert_portal_layout.py b/tests/test_convert_portal_layout.py new file mode 100644 index 0000000..00c7cfa --- /dev/null +++ b/tests/test_convert_portal_layout.py @@ -0,0 +1,107 @@ +"""Tests for the portal layout converter.""" + +from __future__ import annotations + +import math +import sys +from pathlib import Path + +sys.path.insert(0, str(Path(__file__).parents[1] / "scripts")) + +from convert_portal_layout import ( # noqa: E402 + convert, + decode_module_handle, + point_in_polygon, +) + +GROUP_ID = 2686254341 + + +def handle(row: int, column: int, group: int = GROUP_ID) -> int: + """Encode a module handle like the portal does.""" + return (((column & 0x7FF) << 11) | (row & 0x7FF)) << 32 | group + + +def test_decode_module_handle() -> None: + """Decode signed row and column from a module handle.""" + assert decode_module_handle(GROUP_ID) == (0, 0) + assert decode_module_handle(handle(3, 2)) == (3, 2) + assert decode_module_handle(handle(-1, -2)) == (-1, -2) + + +def _vertex(x: float, y: float, z: float) -> dict: + return {"position": {"x": x, "y": y}, "heightWithoutPolygonGroups": z} + + +def _site() -> tuple[dict, dict]: + """East-facing roof, 30 degrees, eave at x=4 (z=3), ridge at x=0.""" + tilt = math.radians(30) + ridge = 3 + 4 * math.tan(tilt) + model = { + "vertices": { + "1": _vertex(0, 0, ridge), + "2": _vertex(4, 0, 3), + "3": _vertex(4, 6, 3), + "4": _vertex(0, 6, ridge), + }, + "edges": { + "a": {"vertexAId": "1", "vertexBId": "2"}, + "b": {"vertexAId": "2", "vertexBId": "3"}, + "c": {"vertexAId": "3", "vertexBId": "4"}, + "d": {"vertexAId": "4", "vertexBId": "1"}, + }, + "polygons": {"p": {"edgeIds": ["a", "b", "c", "d"]}}, + "moduleGroups": { + str(GROUP_ID): { + "polygonId": "p", + "facetRotation": 0.0, + "rowSpacing": 0.03, + "columnSpacing": 0.03, + "position": {"x": 3.8, "y": 0.2}, + "orientation": "LANDSCAPE", + } + }, + "moduleModels": {"1": {"stcPower": 460.0, "length": 1762.0, "width": 1134.0}}, + "optimizers": { + "o1": {"serialNumber": "A", "moduleIds": [str(handle(0, 0))]}, + "o2": {"serialNumber": "B", "moduleIds": [str(handle(0, 1))]}, + }, + } + site_model = { + "modelData": model, + "moduleGroupDetails": { + str(GROUP_ID): { + "azimuth": math.radians(90), + "tilt": tilt, + "moduleHandleIds": [handle(0, 0), handle(0, 1)], + } + }, + } + physical = { + "physicalDevicesMap": { + "inverters": {"i": {"sequenceNumber": 1}}, + "strings": { + "s": {"sequenceNumber": 1, "inverterId": "i", "optimizerIds": [1, 2]} + }, + "optimizers": {"1": {"serialNumber": "A"}, "2": {"serialNumber": "B"}}, + } + } + return physical, site_model + + +def test_convert_places_panels_on_their_roof() -> None: + """Panels get their Panel-Position, lie on the roof and rise up the slope.""" + physical, site_model = _site() + layout = convert(physical, site_model, {"ost": ["1.1.1", "1.1.2"]}) + + assert layout["module_power"] == 460.0 + assert [roof["name"] for roof in layout["roofs"]] == ["ost"] + assert [panel["id"] for panel in layout["panels"]] == ["1.1.1", "1.1.2"] + outline = [tuple(p) for p in layout["roofs"][0]["outline"]] + for panel in layout["panels"]: + lower_left, _, _, upper_left = panel["corners"] + assert upper_left[2] > lower_left[2] + for x, y, z in panel["corners"]: + assert point_in_polygon((x, y), outline, 0.01) + roof_z = 3 + (4 - x) * math.tan(math.radians(30)) + assert math.isclose(z, roof_z + 0.05, abs_tol=0.01) diff --git a/tests/test_frontend.py b/tests/test_frontend.py new file mode 100644 index 0000000..c9f5cf9 --- /dev/null +++ b/tests/test_frontend.py @@ -0,0 +1,33 @@ +"""Tests for serving the solaredge-roof-card.""" + +from __future__ import annotations + +from unittest.mock import AsyncMock, MagicMock, patch + +from homeassistant.core import HomeAssistant + +from custom_components.solaredge_optimizers import frontend + + +async def test_card_is_served_and_loaded(hass: HomeAssistant) -> None: + """Register the bundle as static path and as extra frontend module.""" + hass.http = MagicMock(async_register_static_paths=AsyncMock()) + hass.config.components.add("frontend") + with patch.object(frontend, "add_extra_js_url") as add_url: + await frontend.async_register_card(hass) + + (paths,), _ = hass.http.async_register_static_paths.call_args + assert paths[0].url_path == "/solaredge_optimizers/solaredge-roof-card.js" + assert paths[0].path.endswith("frontend/solaredge-roof-card.js") + (_, url), _ = add_url.call_args + assert url.startswith("/solaredge_optimizers/solaredge-roof-card.js?v=") + + +async def test_card_is_skipped_without_frontend(hass: HomeAssistant) -> None: + """Do nothing when Home Assistant runs without frontend.""" + hass.http = MagicMock(async_register_static_paths=AsyncMock()) + with patch.object(frontend, "add_extra_js_url") as add_url: + await frontend.async_register_card(hass) + + hass.http.async_register_static_paths.assert_not_called() + add_url.assert_not_called() diff --git a/uv.lock b/uv.lock index 02e54cb..b8a9a21 100644 --- a/uv.lock +++ b/uv.lock @@ -1,5 +1,5 @@ version = 1 -revision = 3 +revision = 5 requires-python = ">=3.14.2" [[package]] @@ -943,7 +943,7 @@ wheels = [ [[package]] name = "ha-solaredge-optimizers" -version = "0.4.0" +version = "0.5.0" source = { virtual = "." } [package.dev-dependencies]