(function(){"use strict";try{if(typeof document<"u"){var o=document.createElement("style");o.appendChild(document.createTextNode('.bim-engine-wrapper{position:relative;width:100%;height:100%;font-family:sans-serif;color:#bf1d1d;box-sizing:border-box;overflow:hidden}.bim-engine-opt-btn-container{position:absolute;bottom:20px;left:50%;transform:translate(-50%);z-index:100}.bim-btn-group-root{display:flex;gap:8px;z-index:1000;position:absolute;pointer-events:auto}.bim-btn-group-root.static{position:relative;inset:auto;transform:none}.bim-btn-group-root.dir-row{flex-direction:row;align-items:center}.bim-btn-group-root.dir-column{flex-direction:column;align-items:stretch}.bim-btn-group-section{display:flex;gap:4px;background-color:var(--bim-btn-group-section-bg, rgba(17, 17, 17, .88));border-radius:6px;padding:4px;box-shadow:0 2px 8px #0000004d,0 1px 3px #0003}.bim-btn-group-root.dir-row .bim-btn-group-section{flex-direction:row;align-items:center}.bim-btn-group-root.dir-column .bim-btn-group-section{flex-direction:column}.opt-btn-wrapper{position:relative}.opt-btn{display:flex;cursor:pointer;border-radius:4px;transition:background-color .2s,color .2s;color:var(--bim-btn-text-color, #ccc);background-color:var(--bim-btn-bg, transparent);padding:6px;align-items:center;position:relative;justify-content:center}.opt-btn:hover{background-color:var(--bim-btn-hover-bg, #444)}.opt-btn.active{background-color:var(--bim-btn-active-bg, rgba(255, 255, 255, .15));color:var(--bim-btn-text-active-color, #fff)}.opt-btn.active .opt-btn-icon{color:var(--bim-icon-active-color, #fff)}.opt-btn.disabled{opacity:.5;cursor:not-allowed}.opt-btn-icon{width:var(--bim-icon-size, 24px);height:var(--bim-icon-size, 24px);display:flex;align-items:center;justify-content:center;color:var(--bim-icon-color, #ccc);flex-shrink:0}.opt-btn-icon svg{width:100%;height:100%;fill:currentColor}.opt-btn-arrow{font-size:10px;opacity:.6;transition:transform .2s;display:inline-block;margin-left:4px}.opt-btn-arrow.rotated{transform:rotate(180deg)}.opt-btn-text-wrapper{display:flex;align-items:center;justify-content:center;pointer-events:none}.opt-btn-label{display:inline}.opt-btn.no-label .opt-btn-label{display:none}.opt-btn.align-vertical:not(.no-label){flex-direction:column;text-align:center}.opt-btn.align-vertical:not(.no-label) .opt-btn-text-wrapper{margin-top:4px}.opt-btn.align-vertical:not(.no-label) .opt-btn-label{font-size:12px;line-height:1.2}.opt-btn.align-horizontal:not(.no-label){flex-direction:row}.opt-btn.align-horizontal:not(.no-label) .opt-btn-text-wrapper{margin-left:8px}.opt-btn.align-horizontal:not(.no-label) .opt-btn-label{font-size:14px}.opt-btn.no-label .opt-btn-text-wrapper{width:0;height:0;margin:0;padding:0;overflow:visible;position:absolute;top:0;right:0}.opt-btn.no-label .opt-btn-arrow{position:absolute;top:2px;right:2px;margin:0;font-size:8px}.opt-btn-dropdown{position:absolute;background-color:var(--bim-toolbar-bg, rgba(17, 17, 17, .95));border-radius:4px;padding:4px;box-shadow:0 4px 12px #0003;z-index:1001;display:flex;flex-direction:column;border:1px solid rgba(255,255,255,.1);opacity:0;visibility:hidden;transform:translateY(-10px);transition:opacity .2s ease,transform .2s cubic-bezier(.2,0,.2,1),visibility .2s}@keyframes dropdown-fade-in{0%{opacity:0;transform:translateY(-8px) scale(.98)}to{opacity:1;transform:translateY(0) scale(1)}}.opt-btn-dropdown{animation:dropdown-fade-in .2s cubic-bezier(.2,0,.2,1) forwards;opacity:1;visibility:visible;transform:none}.opt-btn-dropdown-item{display:flex;align-items:center;padding:8px 12px;cursor:pointer;border-radius:4px;color:var(--bim-btn-text-color, #ccc);transition:background .2s;box-sizing:border-box}.opt-btn-dropdown-item:hover{background-color:var(--bim-btn-hover-bg, #444);color:#fff}.opt-btn-dropdown-item.align-horizontal{flex-direction:row}.opt-btn-dropdown-item.align-horizontal .opt-btn-icon{width:18px;height:18px;margin-right:8px}.opt-btn-dropdown-item.align-vertical{flex-direction:column;text-align:center}.opt-btn-dropdown-item.align-vertical .opt-btn-icon{width:24px;height:24px;margin-bottom:4px}.opt-btn-dropdown-item.align-vertical .opt-btn-dropdown-label{font-size:12px}.bim-btn-group-root.is-bottom-toolbar .opt-btn-icon{width:32px;height:32px}.bim-btn-group-root.is-bottom-toolbar .opt-btn{padding:8px}:root{--bim-dialog-bg: rgba(17, 17, 17, .95);--bim-dialog-header-bg: #2a2a2a;--bim-dialog-title-color: #fff;--bim-dialog-text-color: #ccc;--bim-dialog-border-color: #444}.bim-dialog{position:absolute;background-color:var(--bim-dialog-bg);border:1px solid var(--bim-dialog-border-color);border-radius:6px;box-shadow:0 4px 12px #0000004d;display:flex;flex-direction:column;z-index:10001;color:var(--bim-dialog-title-color);overflow:hidden;min-width:200px;min-height:100px;pointer-events:auto}.bim-dialog-header{height:32px;background-color:var(--bim-dialog-header-bg);display:flex;align-items:center;justify-content:space-between;padding:0 10px;cursor:default;-webkit-user-select:none;user-select:none;border-bottom:1px solid var(--bim-dialog-border-color);flex-shrink:0}.bim-dialog-header.draggable{cursor:move}.bim-dialog-title{font-size:14px;font-weight:500;white-space:nowrap;overflow:hidden;text-overflow:ellipsis;color:var(--bim-dialog-title-color)}.bim-dialog-close{cursor:pointer;font-size:18px;color:#999;line-height:1;margin-left:8px}.bim-dialog-close:hover{color:#fff}.bim-dialog-content{flex:1;padding:10px;overflow:auto;font-size:14px;color:var(--bim-dialog-text-color)}.bim-dialog-resize-handle{position:absolute;width:10px;height:10px;bottom:0;right:0;cursor:se-resize;z-index:10}.bim-dialog-resize-handle:after{content:"";position:absolute;bottom:3px;right:3px;width:6px;height:6px;border-right:2px solid #666;border-bottom:2px solid #666}.bim-dialog-resize-handle:hover:after{border-color:#fff}.bim-info-dialog-content{padding:16px;font-family:sans-serif;color:#333}.bim-info-dialog-content h3{margin-top:0;margin-bottom:12px;border-bottom:1px solid #eee;padding-bottom:8px;color:#0078d4}.bim-info-dialog-content ul{list-style:none;padding:0;margin:0}.bim-info-dialog-content li{margin-bottom:8px;font-size:14px;display:flex}.bim-info-dialog-content li strong{width:80px;color:#555}')),document.head.appendChild(o)}}catch(t){console.error("vite-plugin-css-injected-by-js",t)}})(); const Hh = { common: { title: "BimEngine", description: "这是一个使用 BIM-ENGINE。", openTestDialog: "打开测试弹窗", openInfoDialog: "打开信息弹窗 (封装版)" }, toolbar: { home: "首页", info: "信息", location: "定位", setting: "设置", walk: "漫游", walkPerson: "人视", walkBird: "鸟瞰", walkMenu: "菜单" }, dialog: { testTitle: "测试弹窗", testContent: '
这是一个 可拖拽可缩放 的弹窗。

你可以尝试拖动标题栏,或者拖动右下角改变大小。
' } }, Vh = { common: { title: "BimEngine", description: "This is a BIM-ENGINE demo.", openTestDialog: "Open Test Dialog", openInfoDialog: "Open Info Dialog (Wrapped)" }, toolbar: { home: "Home", info: "Info", location: "Location", setting: "Settings", walk: "Walk", walkPerson: "Person", walkBird: "Bird Eye", walkMenu: "Menu" }, dialog: { testTitle: "Test Dialog", testContent: '
This is a draggable and resizable dialog.

Try dragging the title bar or resizing from the bottom-right corner.
' } }; class Gh { currentLocale = "zh-CN"; messages = { "zh-CN": Hh, "en-US": Vh }; listeners = []; constructor() { } /** * 获取当前语言 */ getLocale() { return this.currentLocale; } /** * 切换语言 */ setLocale(e) { this.currentLocale !== e && (this.currentLocale = e, this.notifyListeners()); } /** * 翻译核心方法 */ t(e) { if (!e) return ""; const t = e.split("."); let i = this.messages[this.currentLocale]; for (const s of t) if (i && typeof i == "object" && s in i) i = i[s]; else return e; return i; } /** * 订阅变更 */ subscribe(e) { return this.listeners.push(e), () => { this.listeners = this.listeners.filter((t) => t !== e); }; } notifyListeners() { this.listeners.forEach((e) => e(this.currentLocale)); } } const dr = new Gh(), xn = (r) => dr.t(r), sl = { name: "dark", primary: "#0078d4", primaryHover: "#0063b1", // 修改:背景色统一为浅灰,不再跟随深色模式变黑 background: "#f5f5f5", panelBackground: "rgba(30, 30, 30, 0.9)", // 注意:如果背景是浅色,主文字颜色通常需要是深色才能看清 // 但这里的 textPrimary 主要是用于 UI 组件内部的。 // 如果 BimEngine wrapper 上的文字直接显示在 background 上, // 我们可能需要区分 "UI文字" 和 "页面文字"。 // 目前架构中: // theme.textPrimary 会应用到 wrapper.style.color (BimEngine.ts) // 以及 Toolbar/Dialog 的文字颜色。 // 如果背景是浅灰,而 wrapper 文字设置为白色 (#ffffff),那就看不清了。 // 这是一个语义冲突: // 1. Panel (Toolbar/Dialog) 是黑底,需要白字。 // 2. Background (Wrapper) 是白底,需要黑字。 // 既然您要求背景统一浅灰,那么 Wrapper 上的“直接子文本”应该是深色。 // 但 Toolbar/Dialog 仍然是深色模式(黑底),它们需要白字。 // 妥协方案: // 保持 textPrimary 为白色(为了适配黑���的 Toolbar/Dialog)。 // 但是在 BimEngine 中,如果背景强制改为浅色,Wrapper 的默认文字颜色可能需要单独处理, // 或者我们可以认为 "Wrapper" 主要是承载 UI 组件的,直接写在 Wrapper 上的文字(标题/描述) // 应该有自己的样式,而不是直接继承 theme.textPrimary。 // 在之前的 BimEngine.ts 中: // this.wrapper.style.color = theme.textPrimary; // 如果背景变浅灰,这里 textPrimary 还是白色的话,标题就看不见了。 // 所以,深色模式下: // 背景:浅灰 // 组件:深黑 // 组件文字:白 // 页面文字:黑 (问题点) // 让我们先按您的要求改背景。通常这种情况下,ThemeConfig 可能需要区分 // contentText (页面内容文字) 和 uiText (组件文字)。 // 但为了不破坏现有结构,我将假定 textPrimary 主要服务于 UI 组件。 // 为了让 Wrapper 上的标题可见,我们可能需要在 BimEngine 中移除对 wrapper.style.color 的强制设置, // 或者在 presets 里把 textPrimary 改回来?不对,改回来 Toolbar 就看不清了。 // 方案:我将仅修改 background。 // 至于 Wrapper 上的标题(BimEngine 标题),由于在最新的 BimEngine.ts 中 // ���们已经移除了 titleEl 和 descEl(在之前的重构中), // 所以现在 Wrapper 里主要是 Toolbar 和 Dialog,它们有自己的 panelBackground。 // 只要 Toolbar/Dialog 内部正常即可。 textPrimary: "#ffffff", textSecondary: "#cccccc", border: "#444444", icon: "#cccccc", iconActive: "#ffffff", componentBackground: "transparent", componentHover: "#333333", componentActive: "rgba(255, 255, 255, 0.1)" }, Wh = { name: "light", primary: "#0078d4", primaryHover: "#106ebe", // 统一为浅灰 background: "#f5f5f5", panelBackground: "#ffffff", textPrimary: "#333333", textSecondary: "#666666", border: "#e0e0e0", icon: "#555555", iconActive: "#0078d4", componentBackground: "transparent", componentHover: "#f0f0f0", componentActive: "#e0e0e0" }; class jh { currentTheme = sl; listeners = []; constructor() { } /** * 获取当前主题配置 */ getTheme() { return this.currentTheme; } /** * 切换预设主题 * @param themeName 'dark' | 'light' */ setTheme(e) { e === "light" ? this.applyTheme(Wh) : this.applyTheme(sl); } /** * 应用自定义主题配置 * @param theme 配置对象 */ setCustomTheme(e) { this.applyTheme(e); } /** * 内部应用主题逻辑 */ applyTheme(e) { this.currentTheme = e, this.notifyListeners(); } /** * 订阅主题变更 */ subscribe(e) { return this.listeners.push(e), e(this.currentTheme), () => { this.listeners = this.listeners.filter((t) => t !== e); }; } notifyListeners() { this.listeners.forEach((e) => e(this.currentTheme)); } } const oi = new jh(); class Nc { container; options; groups = []; activeBtnIds = /* @__PURE__ */ new Set(); btnRefs = /* @__PURE__ */ new Map(); dropdownElement = null; hoverTimeout = null; customColors = /* @__PURE__ */ new Set(); // 记录用户自定义的颜色属性 unsubscribeLocale = null; unsubscribeTheme = null; DEFAULT_ICON = ''; constructor(e) { const t = typeof e.container == "string" ? document.getElementById(e.container) : e.container; if (!t) throw new Error("Container not found"); this.container = t, this.options = { showLabel: !0, visibility: {}, direction: "row", // 默认横向 position: "static", // 默认静态定位 align: "vertical", // 默认图标在上 expand: "down", // 默认向下展开 ...e }, [ "backgroundColor", "btnBackgroundColor", "btnHoverColor", "btnActiveColor", "iconColor", "iconActiveColor", "textColor", "textActiveColor" ].forEach((s) => { e[s] && this.customColors.add(s); }), this.initContainer(), this.applyStyles(); } initContainer() { this.container.innerHTML = "", this.container.classList.add("bim-btn-group-root"), this.options.direction === "column" ? this.container.classList.add("dir-column") : this.container.classList.add("dir-row"), this.options.className && this.container.classList.add(this.options.className), this.updatePosition(); } updatePosition() { const e = this.options.position, t = this.container.style; if (t.top = "", t.bottom = "", t.left = "", t.right = "", t.transform = "", e === "static") { this.container.classList.add("static"); return; } if (this.container.classList.remove("static"), this.container.style.position = "absolute", typeof e == "object" && "x" in e) t.left = `${e.x}px`, t.top = `${e.y}px`; else { const i = "20px"; switch (e) { case "top-left": t.top = i, t.left = i; break; case "top-center": t.top = i, t.left = "50%", t.transform = "translateX(-50%)"; break; case "top-right": t.top = i, t.right = i; break; case "bottom-left": t.bottom = i, t.left = i; break; case "bottom-center": t.bottom = i, t.left = "50%", t.transform = "translateX(-50%)"; break; case "bottom-right": t.bottom = i, t.right = i; break; case "left-center": t.left = i, t.top = "50%", t.transform = "translateY(-50%)"; break; case "right-center": t.right = i, t.top = "50%", t.transform = "translateY(-50%)"; break; case "center": t.top = "50%", t.left = "50%", t.transform = "translate(-50%, -50%)"; break; } } } /** * 应用样式到容器 */ applyStyles() { const e = this.container.style; this.options.backgroundColor && e.setProperty("--bim-btn-group-section-bg", this.options.backgroundColor), this.options.btnBackgroundColor && e.setProperty("--bim-btn-bg", this.options.btnBackgroundColor), this.options.btnHoverColor && e.setProperty("--bim-btn-hover-bg", this.options.btnHoverColor), this.options.btnActiveColor && e.setProperty("--bim-btn-active-bg", this.options.btnActiveColor), this.options.iconColor && e.setProperty("--bim-icon-color", this.options.iconColor), this.options.iconActiveColor && e.setProperty("--bim-icon-active-color", this.options.iconActiveColor), this.options.textColor && e.setProperty("--bim-btn-text-color", this.options.textColor), this.options.textActiveColor && e.setProperty("--bim-btn-text-active-color", this.options.textActiveColor); } /** * 设置主题颜色 * 只会应用到没有被用户自定义的颜色属性上 */ setTheme(e) { const t = { backgroundColor: e.panelBackground, btnBackgroundColor: e.componentBackground, btnHoverColor: e.componentHover, btnActiveColor: e.componentActive, iconColor: e.icon, iconActiveColor: e.iconActive, textColor: e.textSecondary, textActiveColor: e.textPrimary }; Object.entries(t).forEach(([i, s]) => { const n = i; this.customColors.has(n) || (this.options[n] = s); }), this.applyStyles(); } /** * 直接设置颜色(强制覆盖) * 设置的颜色会被标记为自定义,后续的 setTheme 不会覆盖它们 */ setColors(e) { this.options = { ...this.options, ...e }, Object.keys(e).forEach((t) => { this.customColors.add(t); }), this.applyStyles(); } async init() { this.render(), this.unsubscribeLocale = dr.subscribe(() => { this.setLocales(); }), this.unsubscribeTheme = oi.subscribe((e) => { this.setTheme(e); }); } setLocales() { this.render(); } addGroup(e, t) { if (this.groups.some((s) => s.id === e)) return; const i = { id: e, buttons: [] }; if (t) { const s = this.groups.findIndex((n) => n.id === t); s !== -1 ? this.groups.splice(s, 0, i) : this.groups.push(i); } else this.groups.push(i); } addButton(e) { const { groupId: t, parentId: i } = e, s = this.groups.find((a) => a.id === t); if (!s) return; const n = { ...e, children: e.children || [] }; if (i) { const a = this.findButton(s.buttons, i); a && (a.children || (a.children = []), a.children.push(n)); } else s.buttons.push(n); } findButton(e, t) { for (const i of e) { if (i.id === t) return i; if (i.children) { const s = this.findButton(i.children, t); if (s) return s; } } } render() { this.container.innerHTML = "", this.btnRefs.clear(), this.groups.forEach((e, t) => { const i = this.renderGroup(e, t, this.groups.length); this.container.appendChild(i); }); } renderGroup(e, t, i) { const s = document.createElement("div"); return s.className = "bim-btn-group-section", t < i - 1 && s.classList.add("has-divider"), e.buttons.forEach((n) => { if (this.isVisible(n.id)) { const a = this.renderButton(n); s.appendChild(a); } }), s; } renderButton(e) { const t = document.createElement("div"); t.className = "opt-btn-wrapper"; const i = document.createElement("div"); i.className = "opt-btn", (e.align || this.options.align || "vertical") === "horizontal" ? i.classList.add("align-horizontal") : i.classList.add("align-vertical"), this.activeBtnIds.has(e.id) && i.classList.add("active"), e.disabled && i.classList.add("disabled"), this.options.showLabel && e.label || i.classList.add("no-label"); const a = e.iconSize || 32, o = e.minWidth || 50; i.style.minWidth = `${o}px`; const l = document.createElement("div"); l.className = "opt-btn-icon", l.style.width = `${a}px`, l.style.height = `${a}px`, l.innerHTML = this.getIcon(e.icon), i.appendChild(l); const c = document.createElement("div"); if (c.className = "opt-btn-text-wrapper", this.options.showLabel && e.label) { const h = document.createElement("span"); h.className = "opt-btn-label", h.textContent = xn(e.label), c.appendChild(h); } if (e.children && e.children.length > 0) { const h = document.createElement("span"); h.className = "opt-btn-arrow", h.textContent = "▼", c.appendChild(h); } return c.hasChildNodes() && i.appendChild(c), i.addEventListener("click", () => this.handleClick(e)), i.addEventListener("mouseenter", () => this.handleMouseEnter(e, i)), i.addEventListener("mouseleave", () => this.handleMouseLeave()), this.btnRefs.set(e.id, i), t.appendChild(i), t; } handleClick(e) { e.disabled || (!e.children || e.children.length === 0) && (e.keepActive && (this.activeBtnIds.has(e.id) ? this.activeBtnIds.delete(e.id) : this.activeBtnIds.add(e.id), this.updateButtonState(e.id)), this.closeDropdown(), e.onClick && e.onClick(e)); } handleMouseEnter(e, t) { this.hoverTimeout && clearTimeout(this.hoverTimeout), e.children && e.children.length > 0 ? this.showDropdown(e, t) : this.closeDropdown(); } handleMouseLeave() { this.hoverTimeout = window.setTimeout(() => this.closeDropdown(), 200); } showDropdown(e, t) { if (this.closeDropdown(), !e.children) return; const i = document.createElement("div"); i.className = "opt-btn-dropdown", this.options.backgroundColor && i.style.setProperty("--bim-toolbar-bg", this.options.backgroundColor); const s = t.getBoundingClientRect(), n = this.options.expand || "down"; this.options.direction === "row" ? i.style.flexDirection = "column" : i.style.flexDirection = "row", document.body.appendChild(i), e.children.forEach((o) => { if (this.isVisible(o.id)) { const l = this.renderDropdownItem(o); i.appendChild(l); } }); const a = i.getBoundingClientRect(); n === "up" ? (i.style.bottom = window.innerHeight - s.top + 8 + "px", i.style.left = s.left + (s.width - a.width) / 2 + "px") : n === "down" ? (i.style.top = s.bottom + 8 + "px", i.style.left = s.left + (s.width - a.width) / 2 + "px") : n === "right" ? (i.style.top = s.top + (s.height - a.height) / 2 + "px", i.style.left = s.right + 8 + "px") : n === "left" && (i.style.top = s.top + (s.height - a.height) / 2 + "px", i.style.right = window.innerWidth - s.left + 8 + "px"), i.addEventListener("mouseenter", () => { this.hoverTimeout && clearTimeout(this.hoverTimeout); }), i.addEventListener("mouseleave", () => this.handleMouseLeave()), this.dropdownElement = i; } renderDropdownItem(e) { const t = document.createElement("div"); t.className = "opt-btn-dropdown-item", (e.align || "horizontal") === "horizontal" ? t.classList.add("align-horizontal") : t.classList.add("align-vertical"); const s = e.iconSize || 32, n = e.minWidth; n && (t.style.minWidth = `${n}px`); const a = document.createElement("div"); if (a.className = "opt-btn-icon", a.style.width = `${s}px`, a.style.height = `${s}px`, a.innerHTML = this.getIcon(e.icon), t.appendChild(a), this.options.showLabel && e.label) { const o = document.createElement("span"); o.className = "opt-btn-dropdown-label", o.textContent = xn(e.label), t.appendChild(o); } return t.addEventListener("click", (o) => { o.stopPropagation(), this.handleClick(e); }), t; } closeDropdown() { this.dropdownElement && (this.dropdownElement.remove(), this.dropdownElement = null), this.btnRefs.forEach((e) => { const t = e.querySelector(".opt-btn-arrow"); t && t.classList.remove("rotated"); }); } updateButtonState(e) { const t = this.btnRefs.get(e); t && (this.activeBtnIds.has(e) ? t.classList.add("active") : t.classList.remove("active")); } getIcon(e) { return e || this.DEFAULT_ICON; } updateButtonVisibility(e, t) { this.options.visibility || (this.options.visibility = {}), this.options.visibility[e] = t, this.render(); } setShowLabel(e) { this.options.showLabel = e, this.updateLabelsVisibility(); } updateLabelsVisibility() { this.btnRefs.forEach((e, t) => { const i = this.findButtonById(t); if (!i) return; this.options.showLabel && i.label ? e.classList.remove("no-label") : e.classList.add("no-label"); }); } findButtonById(e) { for (const t of this.groups) { const i = this.findButton(t.buttons, e); if (i) return i; } } setBackgroundColor(e) { this.setColors({ backgroundColor: e }); } isVisible(e) { return this.options.visibility?.[e] !== !1; } destroy() { this.unsubscribeLocale && (this.unsubscribeLocale(), this.unsubscribeLocale = null), this.unsubscribeTheme && (this.unsubscribeTheme(), this.unsubscribeTheme = null), this.closeDropdown(), this.container.innerHTML = "", this.btnRefs.clear(); } } class Xh extends Nc { /** * 重写初始化,加载默认按钮 */ async init() { await super.init(); const { homeButton: e } = await import("./index-CAPOUzfO.mjs"), { locationButton: t } = await import("./index-Cadgm6mg.mjs"), { walkMenuButton: i } = await import("./index-BzDQeHxh.mjs"), { walkPersonButton: s } = await import("./index-CIgUZcJM.mjs"), { walkBirdButton: n } = await import("./index-psziCat8.mjs"), { settingButton: a } = await import("./index-DSz8VpYf.mjs"), { infoButton: o } = await import("./index-C4v-Lg_Y.mjs"); this.addGroup("group-1"), this.addButton(e), this.addButton(i), this.addButton(s), this.addButton(n), this.addButton(t), this.addGroup("group-2"), this.addButton(a), this.addButton(o), this.render(); } } class qh { toolbar = null; toolbarContainer = null; container; constructor(e) { this.container = e, this.init(); } init() { this.toolbarContainer = document.createElement("div"), this.toolbarContainer.id = "opt-btn-groups", this.toolbarContainer.className = "bim-engine-opt-btn-container is-bottom-toolbar", this.container.appendChild(this.toolbarContainer), this.toolbar = new Xh({ container: this.toolbarContainer, showLabel: !0, direction: "row", position: "bottom-center", // 底部居中 align: "vertical", // 图标在上 expand: "up" // 向上展开 }), this.toolbar.init(); } updateTheme(e) { this.toolbar?.setTheme(e); } refresh() { this.toolbar?.render(); } destroy() { this.toolbar?.destroy(), this.toolbar = null; } // --- 转发 API --- addGroup(e, t) { this.toolbar?.addGroup(e, t), this.toolbar?.render(); } addButton(e) { this.toolbar?.addButton(e), this.toolbar?.render(); } setButtonVisibility(e, t) { this.toolbar?.updateButtonVisibility(e, t); } setShowLabel(e) { this.toolbar?.setShowLabel(e); } setVisible(e) { this.toolbarContainer && (this.toolbarContainer.style.visibility = e ? "visible" : "hidden"); } setBackgroundColor(e) { this.toolbar?.setBackgroundColor(e); } setColors(e) { this.toolbar?.setColors(e); } } class Yh { activeGroups = []; container; constructor(e) { this.container = e; } /** * 创建一个新的按钮组 */ create(e) { const t = document.createElement("div"); this.container.appendChild(t); const i = new Nc({ container: t, ...e }); return i.init(), this.activeGroups.push(i), i; } updateTheme(e) { this.activeGroups.forEach((t) => t.setTheme(e)); } refresh() { this.activeGroups.forEach((e) => e.render()); } destroy() { this.activeGroups.forEach((e) => e.destroy()), this.activeGroups = []; } } class Oc { element; options; container; header; contentArea; _isDestroyed = !1; _isInitialized = !1; unsubscribeTheme = null; unsubscribeLocale = null; // 性能优化:用于存储 requestAnimationFrame 的 ID rafId = null; /** * 构造函数 * @param options 弹窗配置选项 */ constructor(e) { this.options = { title: "Dialog", width: 300, height: "auto", position: "center", draggable: !0, resizable: !1, minWidth: 200, minHeight: 100, ...e }, this.container = e.container, this.element = this.createDom(), this.header = this.element.querySelector(".bim-dialog-header"), this.contentArea = this.element.querySelector(".bim-dialog-content"), this.init(); } /** * 设置主题 * @param theme 全局主题配置 */ setTheme(e) { const t = this.element.style; this.options.backgroundColor || t.setProperty("--bim-dialog-bg", e.panelBackground), this.options.headerBackgroundColor || t.setProperty("--bim-dialog-header-bg", e.componentHover), this.options.titleColor || t.setProperty("--bim-dialog-title-color", e.textPrimary), this.options.textColor || t.setProperty("--bim-dialog-text-color", e.textPrimary), this.options.borderColor || t.setProperty("--bim-dialog-border-color", e.border); } /** * 初始化组件功能 (接口实现) */ init() { this._isInitialized || (this.container.appendChild(this.element), this.initPosition(), this.options.draggable && this.initDrag(), this.options.resizable && this.initResize(), this._isInitialized = !0, this.options.onOpen && this.options.onOpen(), this.unsubscribeTheme = oi.subscribe((e) => { this.setTheme(e); }), this.unsubscribeLocale = dr.subscribe(() => { this.setLocales(); })); } setLocales() { if (this.options.title) { const e = this.header.querySelector(".bim-dialog-title"); e && (e.textContent = xn(this.options.title)); } } /** * 创建弹窗的 DOM 结构 */ createDom() { const e = document.createElement("div"); e.className = "bim-dialog", this.options.id && (e.id = this.options.id); const t = e.style; this.options.backgroundColor && t.setProperty("--bim-dialog-bg", this.options.backgroundColor), this.options.headerBackgroundColor && t.setProperty("--bim-dialog-header-bg", this.options.headerBackgroundColor), this.options.titleColor && t.setProperty("--bim-dialog-title-color", this.options.titleColor), this.options.textColor && t.setProperty("--bim-dialog-text-color", this.options.textColor), this.options.borderColor && t.setProperty("--bim-dialog-border-color", this.options.borderColor), this.setSize(e, this.options.width, this.options.height); const i = document.createElement("div"); i.className = "bim-dialog-header", this.options.draggable && i.classList.add("draggable"); const s = document.createElement("span"); s.className = "bim-dialog-title", s.textContent = this.options.title ? xn(this.options.title) : ""; const n = document.createElement("span"); n.className = "bim-dialog-close", n.innerHTML = "×", n.onclick = () => { this.close(); }, i.appendChild(s), i.appendChild(n); const a = document.createElement("div"); if (a.className = "bim-dialog-content", typeof this.options.content == "string" ? a.innerHTML = this.options.content : this.options.content instanceof HTMLElement && a.appendChild(this.options.content), e.appendChild(i), e.appendChild(a), this.options.resizable) { const c = document.createElement("div"); c.className = "bim-dialog-resize-handle", e.appendChild(c); } const o = (c) => { c.stopPropagation(); }; return [ "click", "dblclick", "contextmenu", "wheel", "mousedown", "mouseup", "mousemove", "touchstart", "touchend", "touchmove", "pointerdown", "pointerup", "pointermove", "pointerenter", "pointerleave", "pointerover", "pointerout" ].forEach((c) => { e.addEventListener(c, o, { passive: !1 }); }), e; } /** * 设置元素尺寸 */ setSize(e, t, i) { t !== void 0 && (e.style.width = typeof t == "number" ? `${t}px` : t), i !== void 0 && (e.style.height = typeof i == "number" ? `${i}px` : i); } /** * 初始化弹窗位置 */ initPosition() { const e = this.options.position, t = this.element.getBoundingClientRect(); let i = 0, s = 0; const n = this.container.clientWidth, a = this.container.clientHeight, o = t.width, l = t.height; if (typeof e == "object" && "x" in e) i = e.x, s = e.y; else switch (e) { case "center": i = (n - o) / 2, s = (a - l) / 2; break; case "top-left": i = 0, s = 0; break; case "top-center": i = (n - o) / 2, s = 0; break; case "top-right": i = n - o, s = 0; break; case "left-center": i = 0, s = (a - l) / 2; break; case "right-center": i = n - o, s = (a - l) / 2; break; case "bottom-left": i = 0, s = a - l; break; case "bottom-center": i = (n - o) / 2, s = a - l; break; case "bottom-right": i = n - o, s = a - l; break; default: i = (n - o) / 2, s = (a - l) / 2; } i = Math.max(0, Math.min(i, n - o)), s = Math.max(0, Math.min(s, a - l)), this.element.style.left = `${i}px`, this.element.style.top = `${s}px`; } /** * 初始化拖拽功能 (性能优化 + 解决粘手) */ initDrag() { let e = 0, t = 0, i = 0, s = 0, n = 0, a = 0, o = 0, l = 0; const c = (d) => { d.preventDefault(), d.stopPropagation(), e = d.clientX, t = d.clientY, i = this.element.offsetLeft, s = this.element.offsetTop, n = this.container.clientWidth, a = this.container.clientHeight, o = this.element.offsetWidth, l = this.element.offsetHeight, document.addEventListener("mousemove", h, { capture: !0 }), document.addEventListener("mouseup", u, { capture: !0 }); }, h = (d) => { d.preventDefault(), d.stopPropagation(), !this.rafId && (this.rafId = requestAnimationFrame(() => { const f = d.clientX - e, g = d.clientY - t; let v = i + f, m = s + g; const p = n - o, y = a - l; v = Math.max(0, Math.min(v, p)), m = Math.max(0, Math.min(m, y)), this.element.style.left = `${v}px`, this.element.style.top = `${m}px`, this.rafId = null; })); }, u = () => { this.rafId && (cancelAnimationFrame(this.rafId), this.rafId = null), document.removeEventListener("mousemove", h, { capture: !0 }), document.removeEventListener("mouseup", u, { capture: !0 }); }; this.header.addEventListener("mousedown", c); } /** * 初始化缩放功能 (性能优化 + 解决粘手) */ initResize() { const e = this.element.querySelector(".bim-dialog-resize-handle"); if (!e) return; let t = 0, i = 0, s = 0, n = 0; const a = (c) => { c.preventDefault(), c.stopPropagation(), t = c.clientX, i = c.clientY, s = this.element.offsetWidth, n = this.element.offsetHeight, document.addEventListener("mousemove", o, { capture: !0 }), document.addEventListener("mouseup", l, { capture: !0 }); }, o = (c) => { c.preventDefault(), c.stopPropagation(), !this.rafId && (this.rafId = requestAnimationFrame(() => { const h = c.clientX - t, u = c.clientY - i, d = Math.max(this.options.minWidth || 100, s + h), f = Math.max(this.options.minHeight || 50, n + u); this.element.style.width = `${d}px`, this.element.style.height = `${f}px`, this.rafId = null; })); }, l = () => { this.rafId && (cancelAnimationFrame(this.rafId), this.rafId = null), document.removeEventListener("mousemove", o, { capture: !0 }), document.removeEventListener("mouseup", l, { capture: !0 }); }; e.addEventListener("mousedown", a); } /** * 动态设置内容 * @param content 内容元素或 HTML 字符串 */ setContent(e) { this.contentArea.innerHTML = "", typeof e == "string" ? this.contentArea.innerHTML = e : this.contentArea.appendChild(e); } /** * 关闭弹窗并销毁 */ close() { this._isDestroyed || (this.rafId && (cancelAnimationFrame(this.rafId), this.rafId = null), this.unsubscribeTheme && (this.unsubscribeTheme(), this.unsubscribeTheme = null), this.unsubscribeLocale && (this.unsubscribeLocale(), this.unsubscribeLocale = null), this.element.remove(), this._isDestroyed = !0, this.options.onClose && this.options.onClose()); } /** * 销毁组件 (接口实现) */ destroy() { this.close(); } } class Kh extends Oc { /** * 构造函数 * @param container 父容器 */ constructor(e) { const t = document.createElement("div"); t.className = "bim-info-dialog-content"; const i = document.createElement("h3"); i.textContent = "Model Information"; const s = document.createElement("ul"); s.innerHTML = `
  • Name: Sample Project
  • Version: 1.0.0
  • Date: ${(/* @__PURE__ */ new Date()).toLocaleDateString()}
  • Status: Active
  • `; const n = document.createElement("button"); n.textContent = "Update Status", n.style.marginTop = "10px", n.onclick = () => { alert("Status updated!"); }, t.appendChild(i), t.appendChild(s), t.appendChild(n), super({ container: e, title: "dialog.testTitle", content: t, width: 320, height: "auto", position: "center", resizable: !0, draggable: !0, // 可以在这里添加特定的 onClose 逻辑 onClose: () => { console.log("Info dialog closed"); }, onOpen: () => { console.log("Info dialog opened"); } }); } // 不需要再手动实现 setTheme, destroy, close, init // 它们都已从 BimDialog 继承 } class Zh { /** 弹窗挂载的父容器 */ container; /** 活跃的弹窗实例列表 */ activeDialogs = []; /** * 构造函数 * @param container 弹窗挂载的目标容器 */ constructor(e) { this.container = e; } /** * 创建一个通用弹窗 * @param options 弹窗配置选项(不需要传 container,自动使用管理器绑定的容器) * @returns BimDialog 实例 */ create(e) { const t = new Oc({ container: this.container, ...e, onClose: () => { this.activeDialogs = this.activeDialogs.filter((i) => i !== t), e.onClose && e.onClose(); } }); return t.setTheme(oi.getTheme()), this.activeDialogs.push(t), t; } /** * 显示二次封装的模型信息弹窗 * 演示如何调用特定的业务弹窗组件 */ showInfoDialog() { new Kh(this.container); } /** * 响应全局主题变更 * @param theme 全局主题配置 */ updateTheme(e) { this.activeDialogs.forEach((t) => { t.setTheme && t.setTheme(e); }); } } const Or = { ROTATE: 0, DOLLY: 1, PAN: 2 }, Ur = { ROTATE: 0, PAN: 1, DOLLY_PAN: 2, DOLLY_ROTATE: 3 }, Jh = 0, nl = 1, $h = 2, Bc = 1, Fc = 2, Bi = 3, Ti = 0, Ft = 1, Vt = 2, vt = 0, Br = 1, yn = 2, al = 3, ol = 4, zc = 5, li = 100, Qh = 101, eu = 102, tu = 103, iu = 104, ms = 200, ru = 201, su = 202, nu = 203, Ta = 204, Ea = 205, wa = 206, au = 207, Ca = 208, ou = 209, lu = 210, cu = 211, hu = 212, uu = 213, du = 214, Ra = 0, Aa = 1, Pa = 2, Vr = 3, Da = 4, La = 5, Ia = 6, Ua = 7, To = 0, pu = 1, fu = 2, $i = 0, kc = 1, Hc = 2, Vc = 3, Eo = 4, Gc = 5, Wc = 6, jc = 7, ll = "attached", mu = "detached", Xc = 300, Gr = 301, Wr = 302, Mn = 303, Na = 304, Pn = 306, Ei = 1e3, Jt = 1001, Sn = 1002, Dt = 1003, qc = 1004, gs = 1005, xt = 1006, pn = 1007, Si = 1008, fi = 1009, Yc = 1010, Kc = 1011, Ss = 1012, wo = 1013, pr = 1014, Gt = 1015, ft = 1016, Co = 1017, Ro = 1018, jr = 1020, Zc = 35902, Jc = 35899, $c = 1021, Qc = 1022, qt = 1023, bs = 1026, Xr = 1027, Ao = 1028, Po = 1029, Do = 1030, Lo = 1031, Io = 1033, fn = 33776, mn = 33777, gn = 33778, vn = 33779, Oa = 35840, Ba = 35841, Fa = 35842, za = 35843, ka = 36196, Ha = 37492, Va = 37496, Ga = 37808, Wa = 37809, ja = 37810, Xa = 37811, qa = 37812, Ya = 37813, Ka = 37814, Za = 37815, Ja = 37816, $a = 37817, Qa = 37818, eo = 37819, to = 37820, io = 37821, ro = 36492, so = 36494, no = 36495, ao = 36283, oo = 36284, lo = 36285, co = 36286, Ts = 2300, Es = 2301, On = 2302, cl = 2400, hl = 2401, ul = 2402, gu = 2500, vu = 0, eh = 1, ho = 2, _u = 3200, th = 3201, Dn = 0, xu = 1, Ki = "", wt = "srgb", Ut = "srgb-linear", bn = "linear", et = "srgb", _r = 7680, Bn = 34055, Fn = 34056, yu = 517, uo = 519, Mu = 512, Su = 513, bu = 514, ih = 515, Tu = 516, Eu = 517, wu = 518, Cu = 519, po = 35044, dl = "300 es", bi = 2e3, Tn = 2001; function rh(r) { for (let e = r.length - 1; e >= 0; --e) if (r[e] >= 65535) return !0; return !1; } function ws(r) { return document.createElementNS("http://www.w3.org/1999/xhtml", r); } function Ru() { const r = ws("canvas"); return r.style.display = "block", r; } const pl = {}; function En(...r) { const e = "THREE." + r.shift(); console.log(e, ...r); } function Se(...r) { const e = "THREE." + r.shift(); console.warn(e, ...r); } function He(...r) { const e = "THREE." + r.shift(); console.error(e, ...r); } function Cs(...r) { const e = r.join(" "); e in pl || (pl[e] = !0, Se(...r)); } function Au(r, e, t) { return new Promise(function(i, s) { function n() { switch (r.clientWaitSync(e, r.SYNC_FLUSH_COMMANDS_BIT, 0)) { case r.WAIT_FAILED: s(); break; case r.TIMEOUT_EXPIRED: setTimeout(n, t); break; default: i(); } } setTimeout(n, t); }); } class gr { /** * Adds the given event listener to the given event type. * * @param {string} type - The type of event to listen to. * @param {Function} listener - The function that gets called when the event is fired. */ addEventListener(e, t) { this._listeners === void 0 && (this._listeners = {}); const i = this._listeners; i[e] === void 0 && (i[e] = []), i[e].indexOf(t) === -1 && i[e].push(t); } /** * Returns `true` if the given event listener has been added to the given event type. * * @param {string} type - The type of event. * @param {Function} listener - The listener to check. * @return {boolean} Whether the given event listener has been added to the given event type. */ hasEventListener(e, t) { const i = this._listeners; return i === void 0 ? !1 : i[e] !== void 0 && i[e].indexOf(t) !== -1; } /** * Removes the given event listener from the given event type. * * @param {string} type - The type of event. * @param {Function} listener - The listener to remove. */ removeEventListener(e, t) { const i = this._listeners; if (i === void 0) return; const s = i[e]; if (s !== void 0) { const n = s.indexOf(t); n !== -1 && s.splice(n, 1); } } /** * Dispatches an event object. * * @param {Object} event - The event that gets fired. */ dispatchEvent(e) { const t = this._listeners; if (t === void 0) return; const i = t[e.type]; if (i !== void 0) { e.target = this; const s = i.slice(0); for (let n = 0, a = s.length; n < a; n++) s[n].call(this, e); e.target = null; } } } const Lt = ["00", "01", "02", "03", "04", "05", "06", "07", "08", "09", "0a", "0b", "0c", "0d", "0e", "0f", "10", "11", "12", "13", "14", "15", "16", "17", "18", "19", "1a", "1b", "1c", "1d", "1e", "1f", "20", "21", "22", "23", "24", "25", "26", "27", "28", "29", "2a", "2b", "2c", "2d", "2e", "2f", "30", "31", "32", "33", "34", "35", "36", "37", "38", "39", "3a", "3b", "3c", "3d", "3e", "3f", "40", "41", "42", "43", "44", "45", "46", "47", "48", "49", "4a", "4b", "4c", "4d", "4e", "4f", "50", "51", "52", "53", "54", "55", "56", "57", "58", "59", "5a", "5b", "5c", "5d", "5e", "5f", "60", "61", "62", "63", "64", "65", "66", "67", "68", "69", "6a", "6b", "6c", "6d", "6e", "6f", "70", "71", "72", "73", "74", "75", "76", "77", "78", "79", "7a", "7b", "7c", "7d", "7e", "7f", "80", "81", "82", "83", "84", "85", "86", "87", "88", "89", "8a", "8b", "8c", "8d", "8e", "8f", "90", "91", "92", "93", "94", "95", "96", "97", "98", "99", "9a", "9b", "9c", "9d", "9e", "9f", "a0", "a1", "a2", "a3", "a4", "a5", "a6", "a7", "a8", "a9", "aa", "ab", "ac", "ad", "ae", "af", "b0", "b1", "b2", "b3", "b4", "b5", "b6", "b7", "b8", "b9", "ba", "bb", "bc", "bd", "be", "bf", "c0", "c1", "c2", "c3", "c4", "c5", "c6", "c7", "c8", "c9", "ca", "cb", "cc", "cd", "ce", "cf", "d0", "d1", "d2", "d3", "d4", "d5", "d6", "d7", "d8", "d9", "da", "db", "dc", "dd", "de", "df", "e0", "e1", "e2", "e3", "e4", "e5", "e6", "e7", "e8", "e9", "ea", "eb", "ec", "ed", "ee", "ef", "f0", "f1", "f2", "f3", "f4", "f5", "f6", "f7", "f8", "f9", "fa", "fb", "fc", "fd", "fe", "ff"]; let fl = 1234567; const xs = Math.PI / 180, qr = 180 / Math.PI; function di() { const r = Math.random() * 4294967295 | 0, e = Math.random() * 4294967295 | 0, t = Math.random() * 4294967295 | 0, i = Math.random() * 4294967295 | 0; return (Lt[r & 255] + Lt[r >> 8 & 255] + Lt[r >> 16 & 255] + Lt[r >> 24 & 255] + "-" + Lt[e & 255] + Lt[e >> 8 & 255] + "-" + Lt[e >> 16 & 15 | 64] + Lt[e >> 24 & 255] + "-" + Lt[t & 63 | 128] + Lt[t >> 8 & 255] + "-" + Lt[t >> 16 & 255] + Lt[t >> 24 & 255] + Lt[i & 255] + Lt[i >> 8 & 255] + Lt[i >> 16 & 255] + Lt[i >> 24 & 255]).toLowerCase(); } function ze(r, e, t) { return Math.max(e, Math.min(t, r)); } function Uo(r, e) { return (r % e + e) % e; } function Pu(r, e, t, i, s) { return i + (r - e) * (s - i) / (t - e); } function Du(r, e, t) { return r !== e ? (t - r) / (e - r) : 0; } function ys(r, e, t) { return (1 - t) * r + t * e; } function Lu(r, e, t, i) { return ys(r, e, 1 - Math.exp(-t * i)); } function Iu(r, e = 1) { return e - Math.abs(Uo(r, e * 2) - e); } function Uu(r, e, t) { return r <= e ? 0 : r >= t ? 1 : (r = (r - e) / (t - e), r * r * (3 - 2 * r)); } function Nu(r, e, t) { return r <= e ? 0 : r >= t ? 1 : (r = (r - e) / (t - e), r * r * r * (r * (r * 6 - 15) + 10)); } function Ou(r, e) { return r + Math.floor(Math.random() * (e - r + 1)); } function Bu(r, e) { return r + Math.random() * (e - r); } function Fu(r) { return r * (0.5 - Math.random()); } function zu(r) { r !== void 0 && (fl = r); let e = fl += 1831565813; return e = Math.imul(e ^ e >>> 15, e | 1), e ^= e + Math.imul(e ^ e >>> 7, e | 61), ((e ^ e >>> 14) >>> 0) / 4294967296; } function ku(r) { return r * xs; } function Hu(r) { return r * qr; } function Vu(r) { return (r & r - 1) === 0 && r !== 0; } function Gu(r) { return Math.pow(2, Math.ceil(Math.log(r) / Math.LN2)); } function Wu(r) { return Math.pow(2, Math.floor(Math.log(r) / Math.LN2)); } function ju(r, e, t, i, s) { const n = Math.cos, a = Math.sin, o = n(t / 2), l = a(t / 2), c = n((e + i) / 2), h = a((e + i) / 2), u = n((e - i) / 2), d = a((e - i) / 2), f = n((i - e) / 2), g = a((i - e) / 2); switch (s) { case "XYX": r.set(o * h, l * u, l * d, o * c); break; case "YZY": r.set(l * d, o * h, l * u, o * c); break; case "ZXZ": r.set(l * u, l * d, o * h, o * c); break; case "XZX": r.set(o * h, l * g, l * f, o * c); break; case "YXY": r.set(l * f, o * h, l * g, o * c); break; case "ZYZ": r.set(l * g, l * f, o * h, o * c); break; default: Se("MathUtils: .setQuaternionFromProperEuler() encountered an unknown order: " + s); } } function ci(r, e) { switch (e.constructor) { case Float32Array: return r; case Uint32Array: return r / 4294967295; case Uint16Array: return r / 65535; case Uint8Array: return r / 255; case Int32Array: return Math.max(r / 2147483647, -1); case Int16Array: return Math.max(r / 32767, -1); case Int8Array: return Math.max(r / 127, -1); default: throw new Error("Invalid component type."); } } function tt(r, e) { switch (e.constructor) { case Float32Array: return r; case Uint32Array: return Math.round(r * 4294967295); case Uint16Array: return Math.round(r * 65535); case Uint8Array: return Math.round(r * 255); case Int32Array: return Math.round(r * 2147483647); case Int16Array: return Math.round(r * 32767); case Int8Array: return Math.round(r * 127); default: throw new Error("Invalid component type."); } } const No = { DEG2RAD: xs, RAD2DEG: qr, /** * Generate a [UUID](https://en.wikipedia.org/wiki/Universally_unique_identifier) * (universally unique identifier). * * @static * @method * @return {string} The UUID. */ generateUUID: di, /** * Clamps the given value between min and max. * * @static * @method * @param {number} value - The value to clamp. * @param {number} min - The min value. * @param {number} max - The max value. * @return {number} The clamped value. */ clamp: ze, /** * Computes the Euclidean modulo of the given parameters that * is `( ( n % m ) + m ) % m`. * * @static * @method * @param {number} n - The first parameter. * @param {number} m - The second parameter. * @return {number} The Euclidean modulo. */ euclideanModulo: Uo, /** * Performs a linear mapping from range `` to range `` * for the given value. * * @static * @method * @param {number} x - The value to be mapped. * @param {number} a1 - Minimum value for range A. * @param {number} a2 - Maximum value for range A. * @param {number} b1 - Minimum value for range B. * @param {number} b2 - Maximum value for range B. * @return {number} The mapped value. */ mapLinear: Pu, /** * Returns the percentage in the closed interval `[0, 1]` of the given value * between the start and end point. * * @static * @method * @param {number} x - The start point * @param {number} y - The end point. * @param {number} value - A value between start and end. * @return {number} The interpolation factor. */ inverseLerp: Du, /** * Returns a value linearly interpolated from two known points based on the given interval - * `t = 0` will return `x` and `t = 1` will return `y`. * * @static * @method * @param {number} x - The start point * @param {number} y - The end point. * @param {number} t - The interpolation factor in the closed interval `[0, 1]`. * @return {number} The interpolated value. */ lerp: ys, /** * Smoothly interpolate a number from `x` to `y` in a spring-like manner using a delta * time to maintain frame rate independent movement. For details, see * [Frame rate independent damping using lerp](http://www.rorydriscoll.com/2016/03/07/frame-rate-independent-damping-using-lerp/). * * @static * @method * @param {number} x - The current point. * @param {number} y - The target point. * @param {number} lambda - A higher lambda value will make the movement more sudden, * and a lower value will make the movement more gradual. * @param {number} dt - Delta time in seconds. * @return {number} The interpolated value. */ damp: Lu, /** * Returns a value that alternates between `0` and the given `length` parameter. * * @static * @method * @param {number} x - The value to pingpong. * @param {number} [length=1] - The positive value the function will pingpong to. * @return {number} The alternated value. */ pingpong: Iu, /** * Returns a value in the range `[0,1]` that represents the percentage that `x` has * moved between `min` and `max`, but smoothed or slowed down the closer `x` is to * the `min` and `max`. * * See [Smoothstep](http://en.wikipedia.org/wiki/Smoothstep) for more details. * * @static * @method * @param {number} x - The value to evaluate based on its position between min and max. * @param {number} min - The min value. Any x value below min will be `0`. * @param {number} max - The max value. Any x value above max will be `1`. * @return {number} The alternated value. */ smoothstep: Uu, /** * A [variation on smoothstep](https://en.wikipedia.org/wiki/Smoothstep#Variations) * that has zero 1st and 2nd order derivatives at x=0 and x=1. * * @static * @method * @param {number} x - The value to evaluate based on its position between min and max. * @param {number} min - The min value. Any x value below min will be `0`. * @param {number} max - The max value. Any x value above max will be `1`. * @return {number} The alternated value. */ smootherstep: Nu, /** * Returns a random integer from `` interval. * * @static * @method * @param {number} low - The lower value boundary. * @param {number} high - The upper value boundary * @return {number} A random integer. */ randInt: Ou, /** * Returns a random float from `` interval. * * @static * @method * @param {number} low - The lower value boundary. * @param {number} high - The upper value boundary * @return {number} A random float. */ randFloat: Bu, /** * Returns a random integer from `<-range/2, range/2>` interval. * * @static * @method * @param {number} range - Defines the value range. * @return {number} A random float. */ randFloatSpread: Fu, /** * Returns a deterministic pseudo-random float in the interval `[0, 1]`. * * @static * @method * @param {number} [s] - The integer seed. * @return {number} A random float. */ seededRandom: zu, /** * Converts degrees to radians. * * @static * @method * @param {number} degrees - A value in degrees. * @return {number} The converted value in radians. */ degToRad: ku, /** * Converts radians to degrees. * * @static * @method * @param {number} radians - A value in radians. * @return {number} The converted value in degrees. */ radToDeg: Hu, /** * Returns `true` if the given number is a power of two. * * @static * @method * @param {number} value - The value to check. * @return {boolean} Whether the given number is a power of two or not. */ isPowerOfTwo: Vu, /** * Returns the smallest power of two that is greater than or equal to the given number. * * @static * @method * @param {number} value - The value to find a POT for. * @return {number} The smallest power of two that is greater than or equal to the given number. */ ceilPowerOfTwo: Gu, /** * Returns the largest power of two that is less than or equal to the given number. * * @static * @method * @param {number} value - The value to find a POT for. * @return {number} The largest power of two that is less than or equal to the given number. */ floorPowerOfTwo: Wu, /** * Sets the given quaternion from the [Intrinsic Proper Euler Angles](https://en.wikipedia.org/wiki/Euler_angles) * defined by the given angles and order. * * Rotations are applied to the axes in the order specified by order: * rotation by angle `a` is applied first, then by angle `b`, then by angle `c`. * * @static * @method * @param {Quaternion} q - The quaternion to set. * @param {number} a - The rotation applied to the first axis, in radians. * @param {number} b - The rotation applied to the second axis, in radians. * @param {number} c - The rotation applied to the third axis, in radians. * @param {('XYX'|'XZX'|'YXY'|'YZY'|'ZXZ'|'ZYZ')} order - A string specifying the axes order. */ setQuaternionFromProperEuler: ju, /** * Normalizes the given value according to the given typed array. * * @static * @method * @param {number} value - The float value in the range `[0,1]` to normalize. * @param {TypedArray} array - The typed array that defines the data type of the value. * @return {number} The normalize value. */ normalize: tt, /** * Denormalizes the given value according to the given typed array. * * @static * @method * @param {number} value - The value to denormalize. * @param {TypedArray} array - The typed array that defines the data type of the value. * @return {number} The denormalize (float) value in the range `[0,1]`. */ denormalize: ci }; class oe { /** * Constructs a new 2D vector. * * @param {number} [x=0] - The x value of this vector. * @param {number} [y=0] - The y value of this vector. */ constructor(e = 0, t = 0) { oe.prototype.isVector2 = !0, this.x = e, this.y = t; } /** * Alias for {@link Vector2#x}. * * @type {number} */ get width() { return this.x; } set width(e) { this.x = e; } /** * Alias for {@link Vector2#y}. * * @type {number} */ get height() { return this.y; } set height(e) { this.y = e; } /** * Sets the vector components. * * @param {number} x - The value of the x component. * @param {number} y - The value of the y component. * @return {Vector2} A reference to this vector. */ set(e, t) { return this.x = e, this.y = t, this; } /** * Sets the vector components to the same value. * * @param {number} scalar - The value to set for all vector components. * @return {Vector2} A reference to this vector. */ setScalar(e) { return this.x = e, this.y = e, this; } /** * Sets the vector's x component to the given value * * @param {number} x - The value to set. * @return {Vector2} A reference to this vector. */ setX(e) { return this.x = e, this; } /** * Sets the vector's y component to the given value * * @param {number} y - The value to set. * @return {Vector2} A reference to this vector. */ setY(e) { return this.y = e, this; } /** * Allows to set a vector component with an index. * * @param {number} index - The component index. `0` equals to x, `1` equals to y. * @param {number} value - The value to set. * @return {Vector2} A reference to this vector. */ setComponent(e, t) { switch (e) { case 0: this.x = t; break; case 1: this.y = t; break; default: throw new Error("index is out of range: " + e); } return this; } /** * Returns the value of the vector component which matches the given index. * * @param {number} index - The component index. `0` equals to x, `1` equals to y. * @return {number} A vector component value. */ getComponent(e) { switch (e) { case 0: return this.x; case 1: return this.y; default: throw new Error("index is out of range: " + e); } } /** * Returns a new vector with copied values from this instance. * * @return {Vector2} A clone of this instance. */ clone() { return new this.constructor(this.x, this.y); } /** * Copies the values of the given vector to this instance. * * @param {Vector2} v - The vector to copy. * @return {Vector2} A reference to this vector. */ copy(e) { return this.x = e.x, this.y = e.y, this; } /** * Adds the given vector to this instance. * * @param {Vector2} v - The vector to add. * @return {Vector2} A reference to this vector. */ add(e) { return this.x += e.x, this.y += e.y, this; } /** * Adds the given scalar value to all components of this instance. * * @param {number} s - The scalar to add. * @return {Vector2} A reference to this vector. */ addScalar(e) { return this.x += e, this.y += e, this; } /** * Adds the given vectors and stores the result in this instance. * * @param {Vector2} a - The first vector. * @param {Vector2} b - The second vector. * @return {Vector2} A reference to this vector. */ addVectors(e, t) { return this.x = e.x + t.x, this.y = e.y + t.y, this; } /** * Adds the given vector scaled by the given factor to this instance. * * @param {Vector2} v - The vector. * @param {number} s - The factor that scales `v`. * @return {Vector2} A reference to this vector. */ addScaledVector(e, t) { return this.x += e.x * t, this.y += e.y * t, this; } /** * Subtracts the given vector from this instance. * * @param {Vector2} v - The vector to subtract. * @return {Vector2} A reference to this vector. */ sub(e) { return this.x -= e.x, this.y -= e.y, this; } /** * Subtracts the given scalar value from all components of this instance. * * @param {number} s - The scalar to subtract. * @return {Vector2} A reference to this vector. */ subScalar(e) { return this.x -= e, this.y -= e, this; } /** * Subtracts the given vectors and stores the result in this instance. * * @param {Vector2} a - The first vector. * @param {Vector2} b - The second vector. * @return {Vector2} A reference to this vector. */ subVectors(e, t) { return this.x = e.x - t.x, this.y = e.y - t.y, this; } /** * Multiplies the given vector with this instance. * * @param {Vector2} v - The vector to multiply. * @return {Vector2} A reference to this vector. */ multiply(e) { return this.x *= e.x, this.y *= e.y, this; } /** * Multiplies the given scalar value with all components of this instance. * * @param {number} scalar - The scalar to multiply. * @return {Vector2} A reference to this vector. */ multiplyScalar(e) { return this.x *= e, this.y *= e, this; } /** * Divides this instance by the given vector. * * @param {Vector2} v - The vector to divide. * @return {Vector2} A reference to this vector. */ divide(e) { return this.x /= e.x, this.y /= e.y, this; } /** * Divides this vector by the given scalar. * * @param {number} scalar - The scalar to divide. * @return {Vector2} A reference to this vector. */ divideScalar(e) { return this.multiplyScalar(1 / e); } /** * Multiplies this vector (with an implicit 1 as the 3rd component) by * the given 3x3 matrix. * * @param {Matrix3} m - The matrix to apply. * @return {Vector2} A reference to this vector. */ applyMatrix3(e) { const t = this.x, i = this.y, s = e.elements; return this.x = s[0] * t + s[3] * i + s[6], this.y = s[1] * t + s[4] * i + 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(e) { return this.x = Math.min(this.x, e.x), this.y = Math.min(this.y, e.y), this; } /** * If this vector's x or y value is less than the given vector's x or y * value, replace that value with the corresponding max value. * * @param {Vector2} v - The vector. * @return {Vector2} A reference to this vector. */ max(e) { return this.x = Math.max(this.x, e.x), this.y = Math.max(this.y, e.y), this; } /** * If this vector's x or y value is greater than the max vector's x or y * value, it is replaced by the corresponding value. * If this vector's x or y value is less than the min vector's x or y value, * it is replaced by the corresponding value. * * @param {Vector2} min - The minimum x and y values. * @param {Vector2} max - The maximum x and y values in the desired range. * @return {Vector2} A reference to this vector. */ clamp(e, t) { return this.x = ze(this.x, e.x, t.x), this.y = ze(this.y, e.y, t.y), this; } /** * If this vector's x or y values are greater than the max value, they are * replaced by the max value. * If this vector's x or y values are less than the min value, they are * replaced by the min value. * * @param {number} minVal - The minimum value the components will be clamped to. * @param {number} maxVal - The maximum value the components will be clamped to. * @return {Vector2} A reference to this vector. */ clampScalar(e, t) { return this.x = ze(this.x, e, t), this.y = ze(this.y, e, t), this; } /** * If this vector's length is greater than the max value, it is replaced by * the max value. * If this vector's length is less than the min value, it is replaced by the * min value. * * @param {number} min - The minimum value the vector length will be clamped to. * @param {number} max - The maximum value the vector length will be clamped to. * @return {Vector2} A reference to this vector. */ clampLength(e, t) { const i = this.length(); return this.divideScalar(i || 1).multiplyScalar(ze(i, e, t)); } /** * The components of this vector are rounded down to the nearest integer value. * * @return {Vector2} A reference to this vector. */ floor() { return this.x = Math.floor(this.x), this.y = Math.floor(this.y), this; } /** * The components of this vector are rounded up to the nearest integer value. * * @return {Vector2} A reference to this vector. */ ceil() { return this.x = Math.ceil(this.x), this.y = Math.ceil(this.y), this; } /** * The components of this vector are rounded to the nearest integer value * * @return {Vector2} A reference to this vector. */ round() { return this.x = Math.round(this.x), this.y = Math.round(this.y), this; } /** * The components of this vector are rounded towards zero (up if negative, * down if positive) to an integer value. * * @return {Vector2} A reference to this vector. */ roundToZero() { return this.x = Math.trunc(this.x), this.y = Math.trunc(this.y), this; } /** * Inverts this vector - i.e. sets x = -x and y = -y. * * @return {Vector2} A reference to this vector. */ negate() { return this.x = -this.x, this.y = -this.y, this; } /** * Calculates the dot product of the given vector with this instance. * * @param {Vector2} v - The vector to compute the dot product with. * @return {number} The result of the dot product. */ dot(e) { return this.x * e.x + this.y * e.y; } /** * Calculates the cross product of the given vector with this instance. * * @param {Vector2} v - The vector to compute the cross product with. * @return {number} The result of the cross product. */ cross(e) { return this.x * e.y - this.y * e.x; } /** * Computes the square of the Euclidean length (straight-line length) from * (0, 0) to (x, y). If you are comparing the lengths of vectors, you should * compare the length squared instead as it is slightly more efficient to calculate. * * @return {number} The square length of this vector. */ lengthSq() { return this.x * this.x + this.y * this.y; } /** * Computes the Euclidean length (straight-line length) from (0, 0) to (x, y). * * @return {number} The length of this vector. */ length() { return Math.sqrt(this.x * this.x + this.y * this.y); } /** * Computes the Manhattan length of this vector. * * @return {number} The length of this vector. */ manhattanLength() { return Math.abs(this.x) + Math.abs(this.y); } /** * Converts this vector to a unit vector - that is, sets it equal to a vector * with the same direction as this one, but with a vector length of `1`. * * @return {Vector2} A reference to this vector. */ normalize() { return this.divideScalar(this.length() || 1); } /** * Computes the angle in radians of this vector with respect to the positive x-axis. * * @return {number} The angle in radians. */ angle() { return Math.atan2(-this.y, -this.x) + Math.PI; } /** * Returns the angle between the given vector and this instance in radians. * * @param {Vector2} v - The vector to compute the angle with. * @return {number} The angle in radians. */ angleTo(e) { const t = Math.sqrt(this.lengthSq() * e.lengthSq()); if (t === 0) return Math.PI / 2; const i = this.dot(e) / t; return Math.acos(ze(i, -1, 1)); } /** * Computes the distance from the given vector to this instance. * * @param {Vector2} v - The vector to compute the distance to. * @return {number} The distance. */ distanceTo(e) { return Math.sqrt(this.distanceToSquared(e)); } /** * Computes the squared distance from the given vector to this instance. * If you are just comparing the distance with another distance, you should compare * the distance squared instead as it is slightly more efficient to calculate. * * @param {Vector2} v - The vector to compute the squared distance to. * @return {number} The squared distance. */ distanceToSquared(e) { const t = this.x - e.x, i = this.y - e.y; return t * t + i * i; } /** * Computes the Manhattan distance from the given vector to this instance. * * @param {Vector2} v - The vector to compute the Manhattan distance to. * @return {number} The Manhattan distance. */ manhattanDistanceTo(e) { return Math.abs(this.x - e.x) + Math.abs(this.y - e.y); } /** * Sets this vector to a vector with the same direction as this one, but * with the specified length. * * @param {number} length - The new length of this vector. * @return {Vector2} A reference to this vector. */ setLength(e) { return this.normalize().multiplyScalar(e); } /** * Linearly interpolates between the given vector and this instance, where * alpha is the percent distance along the line - alpha = 0 will be this * vector, and alpha = 1 will be the given one. * * @param {Vector2} v - The vector to interpolate towards. * @param {number} alpha - The interpolation factor, typically in the closed interval `[0, 1]`. * @return {Vector2} A reference to this vector. */ lerp(e, t) { return this.x += (e.x - this.x) * t, this.y += (e.y - this.y) * t, this; } /** * Linearly interpolates between the given vectors, where alpha is the percent * distance along the line - alpha = 0 will be first vector, and alpha = 1 will * be the second one. The result is stored in this instance. * * @param {Vector2} v1 - The first vector. * @param {Vector2} v2 - The second vector. * @param {number} alpha - The interpolation factor, typically in the closed interval `[0, 1]`. * @return {Vector2} A reference to this vector. */ lerpVectors(e, t, i) { return this.x = e.x + (t.x - e.x) * i, this.y = e.y + (t.y - e.y) * i, this; } /** * Returns `true` if this vector is equal with the given one. * * @param {Vector2} v - The vector to test for equality. * @return {boolean} Whether this vector is equal with the given one. */ equals(e) { return e.x === this.x && e.y === this.y; } /** * Sets this vector's x value to be `array[ offset ]` and y * value to be `array[ offset + 1 ]`. * * @param {Array} array - An array holding the vector component values. * @param {number} [offset=0] - The offset into the array. * @return {Vector2} A reference to this vector. */ fromArray(e, t = 0) { return this.x = e[t], this.y = e[t + 1], this; } /** * Writes the components of this vector to the given array. If no array is provided, * the method returns a new instance. * * @param {Array} [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(e = [], t = 0) { return e[t] = this.x, e[t + 1] = this.y, e; } /** * Sets the components of this vector from the given buffer attribute. * * @param {BufferAttribute} attribute - The buffer attribute holding vector data. * @param {number} index - The index into the attribute. * @return {Vector2} A reference to this vector. */ fromBufferAttribute(e, t) { return this.x = e.getX(t), this.y = e.getY(t), this; } /** * Rotates this vector around the given center by the given angle. * * @param {Vector2} center - The point around which to rotate. * @param {number} angle - The angle to rotate, in radians. * @return {Vector2} A reference to this vector. */ rotateAround(e, t) { const i = Math.cos(t), s = Math.sin(t), n = this.x - e.x, a = this.y - e.y; return this.x = n * i - a * s + e.x, this.y = n * s + a * i + e.y, this; } /** * Sets each component of this vector to a pseudo-random value between `0` and * `1`, excluding `1`. * * @return {Vector2} A reference to this vector. */ random() { return this.x = Math.random(), this.y = Math.random(), this; } *[Symbol.iterator]() { yield this.x, yield this.y; } } class mi { /** * Constructs a new quaternion. * * @param {number} [x=0] - The x value of this quaternion. * @param {number} [y=0] - The y value of this quaternion. * @param {number} [z=0] - The z value of this quaternion. * @param {number} [w=1] - The w value of this quaternion. */ constructor(e = 0, t = 0, i = 0, s = 1) { this.isQuaternion = !0, this._x = e, this._y = t, this._z = i, 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(e, t, i, s, n, a, o) { let l = i[s + 0], c = i[s + 1], h = i[s + 2], u = i[s + 3], d = n[a + 0], f = n[a + 1], g = n[a + 2], v = n[a + 3]; if (o <= 0) { e[t + 0] = l, e[t + 1] = c, e[t + 2] = h, e[t + 3] = u; return; } if (o >= 1) { e[t + 0] = d, e[t + 1] = f, e[t + 2] = g, e[t + 3] = v; return; } if (u !== v || l !== d || c !== f || h !== g) { let m = l * d + c * f + h * g + u * v; m < 0 && (d = -d, f = -f, g = -g, v = -v, m = -m); let p = 1 - o; if (m < 0.9995) { const y = Math.acos(m), _ = Math.sin(y); p = Math.sin(p * y) / _, o = Math.sin(o * y) / _, l = l * p + d * o, c = c * p + f * o, h = h * p + g * o, u = u * p + v * o; } else { l = l * p + d * o, c = c * p + f * o, h = h * p + g * o, u = u * p + v * o; const y = 1 / Math.sqrt(l * l + c * c + h * h + u * u); l *= y, c *= y, h *= y, u *= y; } } e[t] = l, e[t + 1] = c, e[t + 2] = h, e[t + 3] = u; } /** * 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(e, t, i, s, n, a) { const o = i[s], l = i[s + 1], c = i[s + 2], h = i[s + 3], u = n[a], d = n[a + 1], f = n[a + 2], g = n[a + 3]; return e[t] = o * g + h * u + l * f - c * d, e[t + 1] = l * g + h * d + c * u - o * f, e[t + 2] = c * g + h * f + o * d - l * u, e[t + 3] = h * g - o * u - l * d - c * f, e; } /** * The x value of this quaternion. * * @type {number} * @default 0 */ get x() { return this._x; } set x(e) { this._x = e, this._onChangeCallback(); } /** * The y value of this quaternion. * * @type {number} * @default 0 */ get y() { return this._y; } set y(e) { this._y = e, this._onChangeCallback(); } /** * The z value of this quaternion. * * @type {number} * @default 0 */ get z() { return this._z; } set z(e) { this._z = e, this._onChangeCallback(); } /** * The w value of this quaternion. * * @type {number} * @default 1 */ get w() { return this._w; } set w(e) { this._w = e, this._onChangeCallback(); } /** * Sets the quaternion components. * * @param {number} x - The x value of this quaternion. * @param {number} y - The y value of this quaternion. * @param {number} z - The z value of this quaternion. * @param {number} w - The w value of this quaternion. * @return {Quaternion} A reference to this quaternion. */ set(e, t, i, s) { return this._x = e, this._y = t, this._z = i, 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(e) { return this._x = e.x, this._y = e.y, this._z = e.z, this._w = e.w, this._onChangeCallback(), this; } /** * Sets this quaternion from the rotation specified by the given * Euler angles. * * @param {Euler} euler - The Euler angles. * @param {boolean} [update=true] - Whether the internal `onChange` callback should be executed or not. * @return {Quaternion} A reference to this quaternion. */ setFromEuler(e, t = !0) { const i = e._x, s = e._y, n = e._z, a = e._order, o = Math.cos, l = Math.sin, c = o(i / 2), h = o(s / 2), u = o(n / 2), d = l(i / 2), f = l(s / 2), g = l(n / 2); switch (a) { case "XYZ": this._x = d * h * u + c * f * g, this._y = c * f * u - d * h * g, this._z = c * h * g + d * f * u, this._w = c * h * u - d * f * g; break; case "YXZ": this._x = d * h * u + c * f * g, this._y = c * f * u - d * h * g, this._z = c * h * g - d * f * u, this._w = c * h * u + d * f * g; break; case "ZXY": this._x = d * h * u - c * f * g, this._y = c * f * u + d * h * g, this._z = c * h * g + d * f * u, this._w = c * h * u - d * f * g; break; case "ZYX": this._x = d * h * u - c * f * g, this._y = c * f * u + d * h * g, this._z = c * h * g - d * f * u, this._w = c * h * u + d * f * g; break; case "YZX": this._x = d * h * u + c * f * g, this._y = c * f * u + d * h * g, this._z = c * h * g - d * f * u, this._w = c * h * u - d * f * g; break; case "XZY": this._x = d * h * u - c * f * g, this._y = c * f * u - d * h * g, this._z = c * h * g + d * f * u, this._w = c * h * u + d * f * g; break; default: Se("Quaternion: .setFromEuler() encountered an unknown order: " + a); } return t === !0 && this._onChangeCallback(), this; } /** * Sets this quaternion from the given axis and angle. * * @param {Vector3} axis - The normalized axis. * @param {number} angle - The angle in radians. * @return {Quaternion} A reference to this quaternion. */ setFromAxisAngle(e, t) { const i = t / 2, s = Math.sin(i); return this._x = e.x * s, this._y = e.y * s, this._z = e.z * s, this._w = Math.cos(i), this._onChangeCallback(), this; } /** * Sets this quaternion from the given rotation matrix. * * @param {Matrix4} m - A 4x4 matrix of which the upper 3x3 of matrix is a pure rotation matrix (i.e. unscaled). * @return {Quaternion} A reference to this quaternion. */ setFromRotationMatrix(e) { const t = e.elements, i = t[0], s = t[4], n = t[8], a = t[1], o = t[5], l = t[9], c = t[2], h = t[6], u = t[10], d = i + o + u; if (d > 0) { const f = 0.5 / Math.sqrt(d + 1); this._w = 0.25 / f, this._x = (h - l) * f, this._y = (n - c) * f, this._z = (a - s) * f; } else if (i > o && i > u) { const f = 2 * Math.sqrt(1 + i - o - u); this._w = (h - l) / f, this._x = 0.25 * f, this._y = (s + a) / f, this._z = (n + c) / f; } else if (o > u) { const f = 2 * Math.sqrt(1 + o - i - u); this._w = (n - c) / f, this._x = (s + a) / f, this._y = 0.25 * f, this._z = (l + h) / f; } else { const f = 2 * Math.sqrt(1 + u - i - o); this._w = (a - s) / f, this._x = (n + c) / f, this._y = (l + h) / f, this._z = 0.25 * f; } return this._onChangeCallback(), this; } /** * Sets this quaternion to the rotation required to rotate the direction vector * `vFrom` to the direction vector `vTo`. * * @param {Vector3} vFrom - The first (normalized) direction vector. * @param {Vector3} vTo - The second (normalized) direction vector. * @return {Quaternion} A reference to this quaternion. */ setFromUnitVectors(e, t) { let i = e.dot(t) + 1; return i < 1e-8 ? (i = 0, Math.abs(e.x) > Math.abs(e.z) ? (this._x = -e.y, this._y = e.x, this._z = 0, this._w = i) : (this._x = 0, this._y = -e.z, this._z = e.y, this._w = i)) : (this._x = e.y * t.z - e.z * t.y, this._y = e.z * t.x - e.x * t.z, this._z = e.x * t.y - e.y * t.x, this._w = i), this.normalize(); } /** * Returns the angle between this quaternion and the given one in radians. * * @param {Quaternion} q - The quaternion to compute the angle with. * @return {number} The angle in radians. */ angleTo(e) { return 2 * Math.acos(Math.abs(ze(this.dot(e), -1, 1))); } /** * Rotates this quaternion by a given angular step to the given quaternion. * The method ensures that the final quaternion will not overshoot `q`. * * @param {Quaternion} q - The target quaternion. * @param {number} step - The angular step in radians. * @return {Quaternion} A reference to this quaternion. */ rotateTowards(e, t) { const i = this.angleTo(e); if (i === 0) return this; const s = Math.min(1, t / i); return this.slerp(e, 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(e) { return this._x * e._x + this._y * e._y + this._z * e._z + this._w * e._w; } /** * Computes the squared Euclidean length (straight-line length) of this quaternion, * considered as a 4 dimensional vector. This can be useful if you are comparing the * lengths of two quaternions, as this is a slightly more efficient calculation than * {@link Quaternion#length}. * * @return {number} The squared Euclidean length. */ lengthSq() { return this._x * this._x + this._y * this._y + this._z * this._z + this._w * this._w; } /** * Computes the Euclidean length (straight-line length) of this quaternion, * considered as a 4 dimensional vector. * * @return {number} The Euclidean length. */ length() { return Math.sqrt(this._x * this._x + this._y * this._y + this._z * this._z + this._w * this._w); } /** * Normalizes this quaternion - that is, calculated the quaternion that performs * the same rotation as this one, but has a length equal to `1`. * * @return {Quaternion} A reference to this quaternion. */ normalize() { let e = this.length(); return e === 0 ? (this._x = 0, this._y = 0, this._z = 0, this._w = 1) : (e = 1 / e, this._x = this._x * e, this._y = this._y * e, this._z = this._z * e, this._w = this._w * e), this._onChangeCallback(), this; } /** * Multiplies this quaternion by the given one. * * @param {Quaternion} q - The quaternion. * @return {Quaternion} A reference to this quaternion. */ multiply(e) { return this.multiplyQuaternions(this, e); } /** * Pre-multiplies this quaternion by the given one. * * @param {Quaternion} q - The quaternion. * @return {Quaternion} A reference to this quaternion. */ premultiply(e) { return this.multiplyQuaternions(e, this); } /** * Multiplies the given quaternions and stores the result in this instance. * * @param {Quaternion} a - The first quaternion. * @param {Quaternion} b - The second quaternion. * @return {Quaternion} A reference to this quaternion. */ multiplyQuaternions(e, t) { const i = e._x, s = e._y, n = e._z, a = e._w, o = t._x, l = t._y, c = t._z, h = t._w; return this._x = i * h + a * o + s * c - n * l, this._y = s * h + a * l + n * o - i * c, this._z = n * h + a * c + i * l - s * o, this._w = a * h - i * o - s * l - n * c, this._onChangeCallback(), this; } /** * Performs a spherical linear interpolation between quaternions. * * @param {Quaternion} qb - The target quaternion. * @param {number} t - The interpolation factor in the closed interval `[0, 1]`. * @return {Quaternion} A reference to this quaternion. */ slerp(e, t) { if (t <= 0) return this; if (t >= 1) return this.copy(e); let i = e._x, s = e._y, n = e._z, a = e._w, o = this.dot(e); o < 0 && (i = -i, s = -s, n = -n, a = -a, o = -o); let l = 1 - t; if (o < 0.9995) { const c = Math.acos(o), h = Math.sin(c); l = Math.sin(l * c) / h, t = Math.sin(t * c) / h, this._x = this._x * l + i * t, this._y = this._y * l + s * t, this._z = this._z * l + n * t, this._w = this._w * l + a * t, this._onChangeCallback(); } else this._x = this._x * l + i * t, this._y = this._y * l + s * t, this._z = this._z * l + n * t, this._w = this._w * l + a * t, this.normalize(); return this; } /** * Performs a spherical linear interpolation between the given quaternions * and stores the result in this quaternion. * * @param {Quaternion} qa - The source quaternion. * @param {Quaternion} qb - The target quaternion. * @param {number} t - The interpolation factor in the closed interval `[0, 1]`. * @return {Quaternion} A reference to this quaternion. */ slerpQuaternions(e, t, i) { return this.copy(e).slerp(t, i); } /** * Sets this quaternion to a uniformly random, normalized quaternion. * * @return {Quaternion} A reference to this quaternion. */ random() { const e = 2 * Math.PI * Math.random(), t = 2 * Math.PI * Math.random(), i = Math.random(), s = Math.sqrt(1 - i), n = Math.sqrt(i); return this.set( s * Math.sin(e), s * Math.cos(e), n * Math.sin(t), n * Math.cos(t) ); } /** * Returns `true` if this quaternion is equal with the given one. * * @param {Quaternion} quaternion - The quaternion to test for equality. * @return {boolean} Whether this quaternion is equal with the given one. */ equals(e) { return e._x === this._x && e._y === this._y && e._z === this._z && e._w === this._w; } /** * Sets this quaternion's components from the given array. * * @param {Array} array - An array holding the quaternion component values. * @param {number} [offset=0] - The offset into the array. * @return {Quaternion} A reference to this quaternion. */ fromArray(e, t = 0) { return this._x = e[t], this._y = e[t + 1], this._z = e[t + 2], this._w = e[t + 3], this._onChangeCallback(), this; } /** * Writes the components of this quaternion to the given array. If no array is provided, * the method returns a new instance. * * @param {Array} [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(e = [], t = 0) { return e[t] = this._x, e[t + 1] = this._y, e[t + 2] = this._z, e[t + 3] = this._w, e; } /** * Sets the components of this quaternion from the given buffer attribute. * * @param {BufferAttribute} attribute - The buffer attribute holding quaternion data. * @param {number} index - The index into the attribute. * @return {Quaternion} A reference to this quaternion. */ fromBufferAttribute(e, t) { return this._x = e.getX(t), this._y = e.getY(t), this._z = e.getZ(t), this._w = e.getW(t), this._onChangeCallback(), this; } /** * This methods defines the serialization result of this class. Returns the * numerical elements of this quaternion in an array of format `[x, y, z, w]`. * * @return {Array} The serialized quaternion. */ toJSON() { return this.toArray(); } _onChange(e) { return this._onChangeCallback = e, this; } _onChangeCallback() { } *[Symbol.iterator]() { yield this._x, yield this._y, yield this._z, yield this._w; } } class w { /** * Constructs a new 3D vector. * * @param {number} [x=0] - The x value of this vector. * @param {number} [y=0] - The y value of this vector. * @param {number} [z=0] - The z value of this vector. */ constructor(e = 0, t = 0, i = 0) { w.prototype.isVector3 = !0, this.x = e, this.y = t, this.z = i; } /** * Sets the vector components. * * @param {number} x - The value of the x component. * @param {number} y - The value of the y component. * @param {number} z - The value of the z component. * @return {Vector3} A reference to this vector. */ set(e, t, i) { return i === void 0 && (i = this.z), this.x = e, this.y = t, this.z = i, this; } /** * Sets the vector components to the same value. * * @param {number} scalar - The value to set for all vector components. * @return {Vector3} A reference to this vector. */ setScalar(e) { return this.x = e, this.y = e, this.z = e, this; } /** * Sets the vector's x component to the given value * * @param {number} x - The value to set. * @return {Vector3} A reference to this vector. */ setX(e) { return this.x = e, this; } /** * Sets the vector's y component to the given value * * @param {number} y - The value to set. * @return {Vector3} A reference to this vector. */ setY(e) { return this.y = e, this; } /** * Sets the vector's z component to the given value * * @param {number} z - The value to set. * @return {Vector3} A reference to this vector. */ setZ(e) { return this.z = e, this; } /** * Allows to set a vector component with an index. * * @param {number} index - The component index. `0` equals to x, `1` equals to y, `2` equals to z. * @param {number} value - The value to set. * @return {Vector3} A reference to this vector. */ setComponent(e, t) { switch (e) { case 0: this.x = t; break; case 1: this.y = t; break; case 2: this.z = t; break; default: throw new Error("index is out of range: " + e); } return this; } /** * Returns the value of the vector component which matches the given index. * * @param {number} index - The component index. `0` equals to x, `1` equals to y, `2` equals to z. * @return {number} A vector component value. */ getComponent(e) { switch (e) { case 0: return this.x; case 1: return this.y; case 2: return this.z; default: throw new Error("index is out of range: " + e); } } /** * Returns a new vector with copied values from this instance. * * @return {Vector3} A clone of this instance. */ clone() { return new this.constructor(this.x, this.y, this.z); } /** * Copies the values of the given vector to this instance. * * @param {Vector3} v - The vector to copy. * @return {Vector3} A reference to this vector. */ copy(e) { return this.x = e.x, this.y = e.y, this.z = e.z, this; } /** * Adds the given vector to this instance. * * @param {Vector3} v - The vector to add. * @return {Vector3} A reference to this vector. */ add(e) { return this.x += e.x, this.y += e.y, this.z += e.z, this; } /** * Adds the given scalar value to all components of this instance. * * @param {number} s - The scalar to add. * @return {Vector3} A reference to this vector. */ addScalar(e) { return this.x += e, this.y += e, this.z += e, this; } /** * Adds the given vectors and stores the result in this instance. * * @param {Vector3} a - The first vector. * @param {Vector3} b - The second vector. * @return {Vector3} A reference to this vector. */ addVectors(e, t) { return this.x = e.x + t.x, this.y = e.y + t.y, this.z = e.z + t.z, this; } /** * Adds the given vector scaled by the given factor to this instance. * * @param {Vector3|Vector4} v - The vector. * @param {number} s - The factor that scales `v`. * @return {Vector3} A reference to this vector. */ addScaledVector(e, t) { return this.x += e.x * t, this.y += e.y * t, this.z += e.z * t, this; } /** * Subtracts the given vector from this instance. * * @param {Vector3} v - The vector to subtract. * @return {Vector3} A reference to this vector. */ sub(e) { return this.x -= e.x, this.y -= e.y, this.z -= e.z, this; } /** * Subtracts the given scalar value from all components of this instance. * * @param {number} s - The scalar to subtract. * @return {Vector3} A reference to this vector. */ subScalar(e) { return this.x -= e, this.y -= e, this.z -= e, this; } /** * Subtracts the given vectors and stores the result in this instance. * * @param {Vector3} a - The first vector. * @param {Vector3} b - The second vector. * @return {Vector3} A reference to this vector. */ subVectors(e, t) { return this.x = e.x - t.x, this.y = e.y - t.y, this.z = e.z - t.z, this; } /** * Multiplies the given vector with this instance. * * @param {Vector3} v - The vector to multiply. * @return {Vector3} A reference to this vector. */ multiply(e) { return this.x *= e.x, this.y *= e.y, this.z *= e.z, this; } /** * Multiplies the given scalar value with all components of this instance. * * @param {number} scalar - The scalar to multiply. * @return {Vector3} A reference to this vector. */ multiplyScalar(e) { return this.x *= e, this.y *= e, this.z *= e, this; } /** * Multiplies the given vectors and stores the result in this instance. * * @param {Vector3} a - The first vector. * @param {Vector3} b - The second vector. * @return {Vector3} A reference to this vector. */ multiplyVectors(e, t) { return this.x = e.x * t.x, this.y = e.y * t.y, this.z = e.z * t.z, this; } /** * Applies the given Euler rotation to this vector. * * @param {Euler} euler - The Euler angles. * @return {Vector3} A reference to this vector. */ applyEuler(e) { return this.applyQuaternion(ml.setFromEuler(e)); } /** * Applies a rotation specified by an axis and an angle to this vector. * * @param {Vector3} axis - A normalized vector representing the rotation axis. * @param {number} angle - The angle in radians. * @return {Vector3} A reference to this vector. */ applyAxisAngle(e, t) { return this.applyQuaternion(ml.setFromAxisAngle(e, t)); } /** * Multiplies this vector with the given 3x3 matrix. * * @param {Matrix3} m - The 3x3 matrix. * @return {Vector3} A reference to this vector. */ applyMatrix3(e) { const t = this.x, i = this.y, s = this.z, n = e.elements; return this.x = n[0] * t + n[3] * i + n[6] * s, this.y = n[1] * t + n[4] * i + n[7] * s, this.z = n[2] * t + n[5] * i + n[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(e) { return this.applyMatrix3(e).normalize(); } /** * Multiplies this vector (with an implicit 1 in the 4th dimension) by m, and * divides by perspective. * * @param {Matrix4} m - The matrix to apply. * @return {Vector3} A reference to this vector. */ applyMatrix4(e) { const t = this.x, i = this.y, s = this.z, n = e.elements, a = 1 / (n[3] * t + n[7] * i + n[11] * s + n[15]); return this.x = (n[0] * t + n[4] * i + n[8] * s + n[12]) * a, this.y = (n[1] * t + n[5] * i + n[9] * s + n[13]) * a, this.z = (n[2] * t + n[6] * i + n[10] * s + n[14]) * a, this; } /** * Applies the given Quaternion to this vector. * * @param {Quaternion} q - The Quaternion. * @return {Vector3} A reference to this vector. */ applyQuaternion(e) { const t = this.x, i = this.y, s = this.z, n = e.x, a = e.y, o = e.z, l = e.w, c = 2 * (a * s - o * i), h = 2 * (o * t - n * s), u = 2 * (n * i - a * t); return this.x = t + l * c + a * u - o * h, this.y = i + l * h + o * c - n * u, this.z = s + l * u + n * h - a * c, this; } /** * Projects this vector from world space into the camera's normalized * device coordinate (NDC) space. * * @param {Camera} camera - The camera. * @return {Vector3} A reference to this vector. */ project(e) { return this.applyMatrix4(e.matrixWorldInverse).applyMatrix4(e.projectionMatrix); } /** * Unprojects this vector from the camera's normalized device coordinate (NDC) * space into world space. * * @param {Camera} camera - The camera. * @return {Vector3} A reference to this vector. */ unproject(e) { return this.applyMatrix4(e.projectionMatrixInverse).applyMatrix4(e.matrixWorld); } /** * Transforms the direction of this vector by a matrix (the upper left 3 x 3 * subset of the given 4x4 matrix and then normalizes the result. * * @param {Matrix4} m - The matrix. * @return {Vector3} A reference to this vector. */ transformDirection(e) { const t = this.x, i = this.y, s = this.z, n = e.elements; return this.x = n[0] * t + n[4] * i + n[8] * s, this.y = n[1] * t + n[5] * i + n[9] * s, this.z = n[2] * t + n[6] * i + n[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(e) { return this.x /= e.x, this.y /= e.y, this.z /= e.z, this; } /** * Divides this vector by the given scalar. * * @param {number} scalar - The scalar to divide. * @return {Vector3} A reference to this vector. */ divideScalar(e) { return this.multiplyScalar(1 / e); } /** * If this vector's x, y or z value is greater than the given vector's x, y or z * value, replace that value with the corresponding min value. * * @param {Vector3} v - The vector. * @return {Vector3} A reference to this vector. */ min(e) { return this.x = Math.min(this.x, e.x), this.y = Math.min(this.y, e.y), this.z = Math.min(this.z, e.z), this; } /** * If this vector's x, y or z value is less than the given vector's x, y or z * value, replace that value with the corresponding max value. * * @param {Vector3} v - The vector. * @return {Vector3} A reference to this vector. */ max(e) { return this.x = Math.max(this.x, e.x), this.y = Math.max(this.y, e.y), this.z = Math.max(this.z, e.z), this; } /** * If this vector's x, y or z value is greater than the max vector's x, y or z * value, it is replaced by the corresponding value. * If this vector's x, y or z value is less than the min vector's x, y or z value, * it is replaced by the corresponding value. * * @param {Vector3} min - The minimum x, y and z values. * @param {Vector3} max - The maximum x, y and z values in the desired range. * @return {Vector3} A reference to this vector. */ clamp(e, t) { return this.x = ze(this.x, e.x, t.x), this.y = ze(this.y, e.y, t.y), this.z = ze(this.z, e.z, t.z), this; } /** * If this vector's x, y or z values are greater than the max value, they are * replaced by the max value. * If this vector's x, y or z values are less than the min value, they are * replaced by the min value. * * @param {number} minVal - The minimum value the components will be clamped to. * @param {number} maxVal - The maximum value the components will be clamped to. * @return {Vector3} A reference to this vector. */ clampScalar(e, t) { return this.x = ze(this.x, e, t), this.y = ze(this.y, e, t), this.z = ze(this.z, e, t), this; } /** * If this vector's length is greater than the max value, it is replaced by * the max value. * If this vector's length is less than the min value, it is replaced by the * min value. * * @param {number} min - The minimum value the vector length will be clamped to. * @param {number} max - The maximum value the vector length will be clamped to. * @return {Vector3} A reference to this vector. */ clampLength(e, t) { const i = this.length(); return this.divideScalar(i || 1).multiplyScalar(ze(i, e, t)); } /** * The components of this vector are rounded down to the nearest integer value. * * @return {Vector3} A reference to this vector. */ floor() { return this.x = Math.floor(this.x), this.y = Math.floor(this.y), this.z = Math.floor(this.z), this; } /** * The components of this vector are rounded up to the nearest integer value. * * @return {Vector3} A reference to this vector. */ ceil() { return this.x = Math.ceil(this.x), this.y = Math.ceil(this.y), this.z = Math.ceil(this.z), this; } /** * The components of this vector are rounded to the nearest integer value * * @return {Vector3} A reference to this vector. */ round() { return this.x = Math.round(this.x), this.y = Math.round(this.y), this.z = Math.round(this.z), this; } /** * The components of this vector are rounded towards zero (up if negative, * down if positive) to an integer value. * * @return {Vector3} A reference to this vector. */ roundToZero() { return this.x = Math.trunc(this.x), this.y = Math.trunc(this.y), this.z = Math.trunc(this.z), this; } /** * Inverts this vector - i.e. sets x = -x, y = -y and z = -z. * * @return {Vector3} A reference to this vector. */ negate() { return this.x = -this.x, this.y = -this.y, this.z = -this.z, this; } /** * Calculates the dot product of the given vector with this instance. * * @param {Vector3} v - The vector to compute the dot product with. * @return {number} The result of the dot product. */ dot(e) { return this.x * e.x + this.y * e.y + this.z * e.z; } // TODO lengthSquared? /** * Computes the square of the Euclidean length (straight-line length) from * (0, 0, 0) to (x, y, z). If you are comparing the lengths of vectors, you should * compare the length squared instead as it is slightly more efficient to calculate. * * @return {number} The square length of this vector. */ lengthSq() { return this.x * this.x + this.y * this.y + this.z * this.z; } /** * Computes the Euclidean length (straight-line length) from (0, 0, 0) to (x, y, z). * * @return {number} The length of this vector. */ length() { return Math.sqrt(this.x * this.x + this.y * this.y + this.z * this.z); } /** * Computes the Manhattan length of this vector. * * @return {number} The length of this vector. */ manhattanLength() { return Math.abs(this.x) + Math.abs(this.y) + Math.abs(this.z); } /** * Converts this vector to a unit vector - that is, sets it equal to a vector * with the same direction as this one, but with a vector length of `1`. * * @return {Vector3} A reference to this vector. */ normalize() { return this.divideScalar(this.length() || 1); } /** * Sets this vector to a vector with the same direction as this one, but * with the specified length. * * @param {number} length - The new length of this vector. * @return {Vector3} A reference to this vector. */ setLength(e) { return this.normalize().multiplyScalar(e); } /** * Linearly interpolates between the given vector and this instance, where * alpha is the percent distance along the line - alpha = 0 will be this * vector, and alpha = 1 will be the given one. * * @param {Vector3} v - The vector to interpolate towards. * @param {number} alpha - The interpolation factor, typically in the closed interval `[0, 1]`. * @return {Vector3} A reference to this vector. */ lerp(e, t) { return this.x += (e.x - this.x) * t, this.y += (e.y - this.y) * t, this.z += (e.z - this.z) * t, this; } /** * Linearly interpolates between the given vectors, where alpha is the percent * distance along the line - alpha = 0 will be first vector, and alpha = 1 will * be the second one. The result is stored in this instance. * * @param {Vector3} v1 - The first vector. * @param {Vector3} v2 - The second vector. * @param {number} alpha - The interpolation factor, typically in the closed interval `[0, 1]`. * @return {Vector3} A reference to this vector. */ lerpVectors(e, t, i) { return this.x = e.x + (t.x - e.x) * i, this.y = e.y + (t.y - e.y) * i, this.z = e.z + (t.z - e.z) * i, this; } /** * Calculates the cross product of the given vector with this instance. * * @param {Vector3} v - The vector to compute the cross product with. * @return {Vector3} The result of the cross product. */ cross(e) { return this.crossVectors(this, e); } /** * Calculates the cross product of the given vectors and stores the result * in this instance. * * @param {Vector3} a - The first vector. * @param {Vector3} b - The second vector. * @return {Vector3} A reference to this vector. */ crossVectors(e, t) { const i = e.x, s = e.y, n = e.z, a = t.x, o = t.y, l = t.z; return this.x = s * l - n * o, this.y = n * a - i * l, this.z = i * 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(e) { const t = e.lengthSq(); if (t === 0) return this.set(0, 0, 0); const i = e.dot(this) / t; return this.copy(e).multiplyScalar(i); } /** * Projects this vector onto a plane by subtracting this * vector projected onto the plane's normal from this vector. * * @param {Vector3} planeNormal - The plane normal. * @return {Vector3} A reference to this vector. */ projectOnPlane(e) { return zn.copy(this).projectOnVector(e), this.sub(zn); } /** * Reflects this vector off a plane orthogonal to the given normal vector. * * @param {Vector3} normal - The (normalized) normal vector. * @return {Vector3} A reference to this vector. */ reflect(e) { return this.sub(zn.copy(e).multiplyScalar(2 * this.dot(e))); } /** * Returns the angle between the given vector and this instance in radians. * * @param {Vector3} v - The vector to compute the angle with. * @return {number} The angle in radians. */ angleTo(e) { const t = Math.sqrt(this.lengthSq() * e.lengthSq()); if (t === 0) return Math.PI / 2; const i = this.dot(e) / t; return Math.acos(ze(i, -1, 1)); } /** * Computes the distance from the given vector to this instance. * * @param {Vector3} v - The vector to compute the distance to. * @return {number} The distance. */ distanceTo(e) { return Math.sqrt(this.distanceToSquared(e)); } /** * Computes the squared distance from the given vector to this instance. * If you are just comparing the distance with another distance, you should compare * the distance squared instead as it is slightly more efficient to calculate. * * @param {Vector3} v - The vector to compute the squared distance to. * @return {number} The squared distance. */ distanceToSquared(e) { const t = this.x - e.x, i = this.y - e.y, s = this.z - e.z; return t * t + i * i + 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(e) { return Math.abs(this.x - e.x) + Math.abs(this.y - e.y) + Math.abs(this.z - e.z); } /** * Sets the vector components from the given spherical coordinates. * * @param {Spherical} s - The spherical coordinates. * @return {Vector3} A reference to this vector. */ setFromSpherical(e) { return this.setFromSphericalCoords(e.radius, e.phi, e.theta); } /** * Sets the vector components from the given spherical coordinates. * * @param {number} radius - The radius. * @param {number} phi - The phi angle in radians. * @param {number} theta - The theta angle in radians. * @return {Vector3} A reference to this vector. */ setFromSphericalCoords(e, t, i) { const s = Math.sin(t) * e; return this.x = s * Math.sin(i), this.y = Math.cos(t) * e, this.z = s * Math.cos(i), this; } /** * Sets the vector components from the given cylindrical coordinates. * * @param {Cylindrical} c - The cylindrical coordinates. * @return {Vector3} A reference to this vector. */ setFromCylindrical(e) { return this.setFromCylindricalCoords(e.radius, e.theta, e.y); } /** * Sets the vector components from the given cylindrical coordinates. * * @param {number} radius - The radius. * @param {number} theta - The theta angle in radians. * @param {number} y - The y value. * @return {Vector3} A reference to this vector. */ setFromCylindricalCoords(e, t, i) { return this.x = e * Math.sin(t), this.y = i, this.z = e * Math.cos(t), this; } /** * Sets the vector components to the position elements of the * given transformation matrix. * * @param {Matrix4} m - The 4x4 matrix. * @return {Vector3} A reference to this vector. */ setFromMatrixPosition(e) { const t = e.elements; return this.x = t[12], this.y = t[13], this.z = t[14], this; } /** * Sets the vector components to the scale elements of the * given transformation matrix. * * @param {Matrix4} m - The 4x4 matrix. * @return {Vector3} A reference to this vector. */ setFromMatrixScale(e) { const t = this.setFromMatrixColumn(e, 0).length(), i = this.setFromMatrixColumn(e, 1).length(), s = this.setFromMatrixColumn(e, 2).length(); return this.x = t, this.y = i, 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(e, t) { return this.fromArray(e.elements, t * 4); } /** * Sets the vector components from the specified matrix column. * * @param {Matrix3} m - The 3x3 matrix. * @param {number} index - The column index. * @return {Vector3} A reference to this vector. */ setFromMatrix3Column(e, t) { return this.fromArray(e.elements, t * 3); } /** * Sets the vector components from the given Euler angles. * * @param {Euler} e - The Euler angles to set. * @return {Vector3} A reference to this vector. */ setFromEuler(e) { return this.x = e._x, this.y = e._y, this.z = e._z, this; } /** * Sets the vector components from the RGB components of the * given color. * * @param {Color} c - The color to set. * @return {Vector3} A reference to this vector. */ setFromColor(e) { return this.x = e.r, this.y = e.g, this.z = e.b, this; } /** * Returns `true` if this vector is equal with the given one. * * @param {Vector3} v - The vector to test for equality. * @return {boolean} Whether this vector is equal with the given one. */ equals(e) { return e.x === this.x && e.y === this.y && e.z === this.z; } /** * Sets this vector's x value to be `array[ offset ]`, y value to be `array[ offset + 1 ]` * and z value to be `array[ offset + 2 ]`. * * @param {Array} array - An array holding the vector component values. * @param {number} [offset=0] - The offset into the array. * @return {Vector3} A reference to this vector. */ fromArray(e, t = 0) { return this.x = e[t], this.y = e[t + 1], this.z = e[t + 2], this; } /** * Writes the components of this vector to the given array. If no array is provided, * the method returns a new instance. * * @param {Array} [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(e = [], t = 0) { return e[t] = this.x, e[t + 1] = this.y, e[t + 2] = this.z, e; } /** * Sets the components of this vector from the given buffer attribute. * * @param {BufferAttribute} attribute - The buffer attribute holding vector data. * @param {number} index - The index into the attribute. * @return {Vector3} A reference to this vector. */ fromBufferAttribute(e, t) { return this.x = e.getX(t), this.y = e.getY(t), this.z = e.getZ(t), this; } /** * Sets each component of this vector to a pseudo-random value between `0` and * `1`, excluding `1`. * * @return {Vector3} A reference to this vector. */ random() { return this.x = Math.random(), this.y = Math.random(), this.z = Math.random(), this; } /** * Sets this vector to a uniformly random point on a unit sphere. * * @return {Vector3} A reference to this vector. */ randomDirection() { const e = Math.random() * Math.PI * 2, t = Math.random() * 2 - 1, i = Math.sqrt(1 - t * t); return this.x = i * Math.cos(e), this.y = t, this.z = i * Math.sin(e), this; } *[Symbol.iterator]() { yield this.x, yield this.y, yield this.z; } } const zn = /* @__PURE__ */ new w(), ml = /* @__PURE__ */ new mi(); class Be { /** * Constructs a new 3x3 matrix. The arguments are supposed to be * in row-major order. If no arguments are provided, the constructor * initializes the matrix as an identity matrix. * * @param {number} [n11] - 1-1 matrix element. * @param {number} [n12] - 1-2 matrix element. * @param {number} [n13] - 1-3 matrix element. * @param {number} [n21] - 2-1 matrix element. * @param {number} [n22] - 2-2 matrix element. * @param {number} [n23] - 2-3 matrix element. * @param {number} [n31] - 3-1 matrix element. * @param {number} [n32] - 3-2 matrix element. * @param {number} [n33] - 3-3 matrix element. */ constructor(e, t, i, s, n, a, o, l, c) { Be.prototype.isMatrix3 = !0, this.elements = [ 1, 0, 0, 0, 1, 0, 0, 0, 1 ], e !== void 0 && this.set(e, t, i, s, n, a, o, l, c); } /** * Sets the elements of the matrix.The arguments are supposed to be * in row-major order. * * @param {number} [n11] - 1-1 matrix element. * @param {number} [n12] - 1-2 matrix element. * @param {number} [n13] - 1-3 matrix element. * @param {number} [n21] - 2-1 matrix element. * @param {number} [n22] - 2-2 matrix element. * @param {number} [n23] - 2-3 matrix element. * @param {number} [n31] - 3-1 matrix element. * @param {number} [n32] - 3-2 matrix element. * @param {number} [n33] - 3-3 matrix element. * @return {Matrix3} A reference to this matrix. */ set(e, t, i, s, n, a, o, l, c) { const h = this.elements; return h[0] = e, h[1] = s, h[2] = o, h[3] = t, h[4] = n, h[5] = l, h[6] = i, h[7] = a, h[8] = c, this; } /** * Sets this matrix to the 3x3 identity matrix. * * @return {Matrix3} A reference to this matrix. */ identity() { return this.set( 1, 0, 0, 0, 1, 0, 0, 0, 1 ), this; } /** * Copies the values of the given matrix to this instance. * * @param {Matrix3} m - The matrix to copy. * @return {Matrix3} A reference to this matrix. */ copy(e) { const t = this.elements, i = e.elements; return t[0] = i[0], t[1] = i[1], t[2] = i[2], t[3] = i[3], t[4] = i[4], t[5] = i[5], t[6] = i[6], t[7] = i[7], t[8] = i[8], this; } /** * Extracts the basis of this matrix into the three axis vectors provided. * * @param {Vector3} xAxis - The basis's x axis. * @param {Vector3} yAxis - The basis's y axis. * @param {Vector3} zAxis - The basis's z axis. * @return {Matrix3} A reference to this matrix. */ extractBasis(e, t, i) { return e.setFromMatrix3Column(this, 0), t.setFromMatrix3Column(this, 1), i.setFromMatrix3Column(this, 2), this; } /** * Set this matrix to the upper 3x3 matrix of the given 4x4 matrix. * * @param {Matrix4} m - The 4x4 matrix. * @return {Matrix3} A reference to this matrix. */ setFromMatrix4(e) { const t = e.elements; return this.set( t[0], t[4], t[8], t[1], t[5], t[9], t[2], t[6], t[10] ), this; } /** * Post-multiplies this matrix by the given 3x3 matrix. * * @param {Matrix3} m - The matrix to multiply with. * @return {Matrix3} A reference to this matrix. */ multiply(e) { return this.multiplyMatrices(this, e); } /** * Pre-multiplies this matrix by the given 3x3 matrix. * * @param {Matrix3} m - The matrix to multiply with. * @return {Matrix3} A reference to this matrix. */ premultiply(e) { return this.multiplyMatrices(e, this); } /** * Multiples the given 3x3 matrices and stores the result * in this matrix. * * @param {Matrix3} a - The first matrix. * @param {Matrix3} b - The second matrix. * @return {Matrix3} A reference to this matrix. */ multiplyMatrices(e, t) { const i = e.elements, s = t.elements, n = this.elements, a = i[0], o = i[3], l = i[6], c = i[1], h = i[4], u = i[7], d = i[2], f = i[5], g = i[8], v = s[0], m = s[3], p = s[6], y = s[1], _ = s[4], E = s[7], A = s[2], T = s[5], R = s[8]; return n[0] = a * v + o * y + l * A, n[3] = a * m + o * _ + l * T, n[6] = a * p + o * E + l * R, n[1] = c * v + h * y + u * A, n[4] = c * m + h * _ + u * T, n[7] = c * p + h * E + u * R, n[2] = d * v + f * y + g * A, n[5] = d * m + f * _ + g * T, n[8] = d * p + f * E + g * R, this; } /** * Multiplies every component of the matrix by the given scalar. * * @param {number} s - The scalar. * @return {Matrix3} A reference to this matrix. */ multiplyScalar(e) { const t = this.elements; return t[0] *= e, t[3] *= e, t[6] *= e, t[1] *= e, t[4] *= e, t[7] *= e, t[2] *= e, t[5] *= e, t[8] *= e, this; } /** * Computes and returns the determinant of this matrix. * * @return {number} The determinant. */ determinant() { const e = this.elements, t = e[0], i = e[1], s = e[2], n = e[3], a = e[4], o = e[5], l = e[6], c = e[7], h = e[8]; return t * a * h - t * o * c - i * n * h + i * o * l + s * n * c - s * a * l; } /** * Inverts this matrix, using the [analytic method](https://en.wikipedia.org/wiki/Invertible_matrix#Analytic_solution). * You can not invert with a determinant of zero. If you attempt this, the method produces * a zero matrix instead. * * @return {Matrix3} A reference to this matrix. */ invert() { const e = this.elements, t = e[0], i = e[1], s = e[2], n = e[3], a = e[4], o = e[5], l = e[6], c = e[7], h = e[8], u = h * a - o * c, d = o * l - h * n, f = c * n - a * l, g = t * u + i * d + s * f; if (g === 0) return this.set(0, 0, 0, 0, 0, 0, 0, 0, 0); const v = 1 / g; return e[0] = u * v, e[1] = (s * c - h * i) * v, e[2] = (o * i - s * a) * v, e[3] = d * v, e[4] = (h * t - s * l) * v, e[5] = (s * n - o * t) * v, e[6] = f * v, e[7] = (i * l - c * t) * v, e[8] = (a * t - i * n) * v, this; } /** * Transposes this matrix in place. * * @return {Matrix3} A reference to this matrix. */ transpose() { let e; const t = this.elements; return e = t[1], t[1] = t[3], t[3] = e, e = t[2], t[2] = t[6], t[6] = e, e = t[5], t[5] = t[7], t[7] = e, this; } /** * Computes the normal matrix which is the inverse transpose of the upper * left 3x3 portion of the given 4x4 matrix. * * @param {Matrix4} matrix4 - The 4x4 matrix. * @return {Matrix3} A reference to this matrix. */ getNormalMatrix(e) { return this.setFromMatrix4(e).invert().transpose(); } /** * Transposes this matrix into the supplied array, and returns itself unchanged. * * @param {Array} r - An array to store the transposed matrix elements. * @return {Matrix3} A reference to this matrix. */ transposeIntoArray(e) { const t = this.elements; return e[0] = t[0], e[1] = t[3], e[2] = t[6], e[3] = t[1], e[4] = t[4], e[5] = t[7], e[6] = t[2], e[7] = t[5], e[8] = t[8], this; } /** * Sets the UV transform matrix from offset, repeat, rotation, and center. * * @param {number} tx - Offset x. * @param {number} ty - Offset y. * @param {number} sx - Repeat x. * @param {number} sy - Repeat y. * @param {number} rotation - Rotation, in radians. Positive values rotate counterclockwise. * @param {number} cx - Center x of rotation. * @param {number} cy - Center y of rotation * @return {Matrix3} A reference to this matrix. */ setUvTransform(e, t, i, s, n, a, o) { const l = Math.cos(n), c = Math.sin(n); return this.set( i * l, i * c, -i * (l * a + c * o) + a + e, -s * c, s * l, -s * (-c * a + l * o) + o + t, 0, 0, 1 ), this; } /** * Scales this matrix with the given scalar values. * * @param {number} sx - The amount to scale in the X axis. * @param {number} sy - The amount to scale in the Y axis. * @return {Matrix3} A reference to this matrix. */ scale(e, t) { return this.premultiply(kn.makeScale(e, t)), this; } /** * Rotates this matrix by the given angle. * * @param {number} theta - The rotation in radians. * @return {Matrix3} A reference to this matrix. */ rotate(e) { return this.premultiply(kn.makeRotation(-e)), this; } /** * Translates this matrix by the given scalar values. * * @param {number} tx - The amount to translate in the X axis. * @param {number} ty - The amount to translate in the Y axis. * @return {Matrix3} A reference to this matrix. */ translate(e, t) { return this.premultiply(kn.makeTranslation(e, t)), this; } // for 2D Transforms /** * Sets this matrix as a 2D translation transform. * * @param {number|Vector2} x - The amount to translate in the X axis or alternatively a translation vector. * @param {number} y - The amount to translate in the Y axis. * @return {Matrix3} A reference to this matrix. */ makeTranslation(e, t) { return e.isVector2 ? this.set( 1, 0, e.x, 0, 1, e.y, 0, 0, 1 ) : this.set( 1, 0, e, 0, 1, t, 0, 0, 1 ), this; } /** * Sets this matrix as a 2D rotational transformation. * * @param {number} theta - The rotation in radians. * @return {Matrix3} A reference to this matrix. */ makeRotation(e) { const t = Math.cos(e), i = Math.sin(e); return this.set( t, -i, 0, i, t, 0, 0, 0, 1 ), this; } /** * Sets this matrix as a 2D scale transform. * * @param {number} x - The amount to scale in the X axis. * @param {number} y - The amount to scale in the Y axis. * @return {Matrix3} A reference to this matrix. */ makeScale(e, t) { return this.set( e, 0, 0, 0, t, 0, 0, 0, 1 ), this; } /** * Returns `true` if this matrix is equal with the given one. * * @param {Matrix3} matrix - The matrix to test for equality. * @return {boolean} Whether this matrix is equal with the given one. */ equals(e) { const t = this.elements, i = e.elements; for (let s = 0; s < 9; s++) if (t[s] !== i[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(e, t = 0) { for (let i = 0; i < 9; i++) this.elements[i] = e[i + t]; return this; } /** * Writes the elements of this matrix to the given array. If no array is provided, * the method returns a new instance. * * @param {Array} [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(e = [], t = 0) { const i = this.elements; return e[t] = i[0], e[t + 1] = i[1], e[t + 2] = i[2], e[t + 3] = i[3], e[t + 4] = i[4], e[t + 5] = i[5], e[t + 6] = i[6], e[t + 7] = i[7], e[t + 8] = i[8], e; } /** * Returns a matrix with copied values from this instance. * * @return {Matrix3} A clone of this instance. */ clone() { return new this.constructor().fromArray(this.elements); } } const kn = /* @__PURE__ */ new Be(), gl = /* @__PURE__ */ new Be().set( 0.4123908, 0.3575843, 0.1804808, 0.212639, 0.7151687, 0.0721923, 0.0193308, 0.1191948, 0.9505322 ), vl = /* @__PURE__ */ new Be().set( 3.2409699, -1.5373832, -0.4986108, -0.9692436, 1.8759675, 0.0415551, 0.0556301, -0.203977, 1.0569715 ); function Xu() { const r = { enabled: !0, workingColorSpace: Ut, /** * 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, n, a) { return this.enabled === !1 || n === a || !n || !a || (this.spaces[n].transfer === et && (s.r = Hi(s.r), s.g = Hi(s.g), s.b = Hi(s.b)), this.spaces[n].primaries !== this.spaces[a].primaries && (s.applyMatrix3(this.spaces[n].toXYZ), s.applyMatrix3(this.spaces[a].fromXYZ)), this.spaces[a].transfer === et && (s.r = Fr(s.r), s.g = Fr(s.g), s.b = Fr(s.b))), s; }, workingToColorSpace: function(s, n) { return this.convert(s, this.workingColorSpace, n); }, colorSpaceToWorking: function(s, n) { return this.convert(s, n, this.workingColorSpace); }, getPrimaries: function(s) { return this.spaces[s].primaries; }, getTransfer: function(s) { return s === Ki ? bn : this.spaces[s].transfer; }, getToneMappingMode: function(s) { return this.spaces[s].outputColorSpaceConfig.toneMappingMode || "standard"; }, getLuminanceCoefficients: function(s, n = this.workingColorSpace) { return s.fromArray(this.spaces[n].luminanceCoefficients); }, define: function(s) { Object.assign(this.spaces, s); }, // Internal APIs _getMatrix: function(s, n, a) { return s.copy(this.spaces[n].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, n) { return Cs("ColorManagement: .fromWorkingColorSpace() has been renamed to .workingToColorSpace()."), r.workingToColorSpace(s, n); }, toWorkingColorSpace: function(s, n) { return Cs("ColorManagement: .toWorkingColorSpace() has been renamed to .colorSpaceToWorking()."), r.colorSpaceToWorking(s, n); } }, e = [0.64, 0.33, 0.3, 0.6, 0.15, 0.06], t = [0.2126, 0.7152, 0.0722], i = [0.3127, 0.329]; return r.define({ [Ut]: { primaries: e, whitePoint: i, transfer: bn, toXYZ: gl, fromXYZ: vl, luminanceCoefficients: t, workingColorSpaceConfig: { unpackColorSpace: wt }, outputColorSpaceConfig: { drawingBufferColorSpace: wt } }, [wt]: { primaries: e, whitePoint: i, transfer: et, toXYZ: gl, fromXYZ: vl, luminanceCoefficients: t, outputColorSpaceConfig: { drawingBufferColorSpace: wt } } }), r; } const Xe = /* @__PURE__ */ Xu(); function Hi(r) { return r < 0.04045 ? r * 0.0773993808 : Math.pow(r * 0.9478672986 + 0.0521327014, 2.4); } function Fr(r) { return r < 31308e-7 ? r * 12.92 : 1.055 * Math.pow(r, 0.41666) - 0.055; } let xr; class qu { /** * Returns a data URI containing a representation of the given image. * * @param {(HTMLImageElement|HTMLCanvasElement)} image - The image object. * @param {string} [type='image/png'] - Indicates the image format. * @return {string} The data URI. */ static getDataURL(e, t = "image/png") { if (/^data:/i.test(e.src) || typeof HTMLCanvasElement > "u") return e.src; let i; if (e instanceof HTMLCanvasElement) i = e; else { xr === void 0 && (xr = ws("canvas")), xr.width = e.width, xr.height = e.height; const s = xr.getContext("2d"); e instanceof ImageData ? s.putImageData(e, 0, 0) : s.drawImage(e, 0, 0, e.width, e.height), i = xr; } return i.toDataURL(t); } /** * Converts the given sRGB image data to linear color space. * * @param {(HTMLImageElement|HTMLCanvasElement|ImageBitmap|Object)} image - The image object. * @return {HTMLCanvasElement|Object} The converted image. */ static sRGBToLinear(e) { if (typeof HTMLImageElement < "u" && e instanceof HTMLImageElement || typeof HTMLCanvasElement < "u" && e instanceof HTMLCanvasElement || typeof ImageBitmap < "u" && e instanceof ImageBitmap) { const t = ws("canvas"); t.width = e.width, t.height = e.height; const i = t.getContext("2d"); i.drawImage(e, 0, 0, e.width, e.height); const s = i.getImageData(0, 0, e.width, e.height), n = s.data; for (let a = 0; a < n.length; a++) n[a] = Hi(n[a] / 255) * 255; return i.putImageData(s, 0, 0), t; } else if (e.data) { const t = e.data.slice(0); for (let i = 0; i < t.length; i++) t instanceof Uint8Array || t instanceof Uint8ClampedArray ? t[i] = Math.floor(Hi(t[i] / 255) * 255) : t[i] = Hi(t[i]); return { data: t, width: e.width, height: e.height }; } else return Se("ImageUtils.sRGBToLinear(): Unsupported image type. No color space conversion applied."), e; } } let Yu = 0; class Oo { /** * Constructs a new video texture. * * @param {any} [data=null] - The data definition of a texture. */ constructor(e = null) { this.isSource = !0, Object.defineProperty(this, "id", { value: Yu++ }), this.uuid = di(), this.data = e, this.dataReady = !0, this.version = 0; } /** * Returns the dimensions of the source into the given target vector. * * @param {(Vector2|Vector3)} target - The target object the result is written into. * @return {(Vector2|Vector3)} The dimensions of the source. */ getSize(e) { const t = this.data; return typeof HTMLVideoElement < "u" && t instanceof HTMLVideoElement ? e.set(t.videoWidth, t.videoHeight, 0) : t instanceof VideoFrame ? e.set(t.displayHeight, t.displayWidth, 0) : t !== null ? e.set(t.width, t.height, t.depth || 0) : e.set(0, 0, 0), e; } /** * When the property is set to `true`, the engine allocates the memory * for the texture (if necessary) and triggers the actual texture upload * to the GPU next time the source is used. * * @type {boolean} * @default false * @param {boolean} value */ set needsUpdate(e) { e === !0 && this.version++; } /** * Serializes the source into JSON. * * @param {?(Object|string)} meta - An optional value holding meta information about the serialization. * @return {Object} A JSON object representing the serialized source. * @see {@link ObjectLoader#parse} */ toJSON(e) { const t = e === void 0 || typeof e == "string"; if (!t && e.images[this.uuid] !== void 0) return e.images[this.uuid]; const i = { uuid: this.uuid, url: "" }, s = this.data; if (s !== null) { let n; if (Array.isArray(s)) { n = []; for (let a = 0, o = s.length; a < o; a++) s[a].isDataTexture ? n.push(Hn(s[a].image)) : n.push(Hn(s[a])); } else n = Hn(s); i.url = n; } return t || (e.images[this.uuid] = i), i; } } function Hn(r) { return typeof HTMLImageElement < "u" && r instanceof HTMLImageElement || typeof HTMLCanvasElement < "u" && r instanceof HTMLCanvasElement || typeof ImageBitmap < "u" && r instanceof ImageBitmap ? qu.getDataURL(r) : r.data ? { data: Array.from(r.data), width: r.width, height: r.height, type: r.data.constructor.name } : (Se("Texture: Unable to serialize Texture."), {}); } let Ku = 0; const Vn = /* @__PURE__ */ new w(); class Ct extends gr { /** * Constructs a new texture. * * @param {?Object} [image=Texture.DEFAULT_IMAGE] - The image holding the texture data. * @param {number} [mapping=Texture.DEFAULT_MAPPING] - The texture mapping. * @param {number} [wrapS=ClampToEdgeWrapping] - The wrapS value. * @param {number} [wrapT=ClampToEdgeWrapping] - The wrapT value. * @param {number} [magFilter=LinearFilter] - The mag filter value. * @param {number} [minFilter=LinearMipmapLinearFilter] - The min filter value. * @param {number} [format=RGBAFormat] - The texture format. * @param {number} [type=UnsignedByteType] - The texture type. * @param {number} [anisotropy=Texture.DEFAULT_ANISOTROPY] - The anisotropy value. * @param {string} [colorSpace=NoColorSpace] - The color space. */ constructor(e = Ct.DEFAULT_IMAGE, t = Ct.DEFAULT_MAPPING, i = Jt, s = Jt, n = xt, a = Si, o = qt, l = fi, c = Ct.DEFAULT_ANISOTROPY, h = Ki) { super(), this.isTexture = !0, Object.defineProperty(this, "id", { value: Ku++ }), this.uuid = di(), this.name = "", this.source = new Oo(e), this.mipmaps = [], this.mapping = t, this.channel = 0, this.wrapS = i, this.wrapT = s, this.magFilter = n, this.minFilter = a, this.anisotropy = c, this.format = o, this.internalFormat = null, this.type = l, this.offset = new oe(0, 0), this.repeat = new oe(1, 1), this.center = new oe(0, 0), this.rotation = 0, this.matrixAutoUpdate = !0, this.matrix = new Be(), this.generateMipmaps = !0, this.premultiplyAlpha = !1, this.flipY = !0, this.unpackAlignment = 4, this.colorSpace = h, this.userData = {}, this.updateRanges = [], this.version = 0, this.onUpdate = null, this.renderTarget = null, this.isRenderTargetTexture = !1, this.isArrayTexture = !!(e && e.depth && e.depth > 1), this.pmremVersion = 0; } /** * The width of the texture in pixels. */ get width() { return this.source.getSize(Vn).x; } /** * The height of the texture in pixels. */ get height() { return this.source.getSize(Vn).y; } /** * The depth of the texture in pixels. */ get depth() { return this.source.getSize(Vn).z; } /** * The image object holding the texture data. * * @type {?Object} */ get image() { return this.source.data; } set image(e = null) { this.source.data = e; } /** * Updates the texture transformation matrix from the from the properties {@link Texture#offset}, * {@link Texture#repeat}, {@link Texture#rotation}, and {@link Texture#center}. */ updateMatrix() { this.matrix.setUvTransform(this.offset.x, this.offset.y, this.repeat.x, this.repeat.y, this.rotation, this.center.x, this.center.y); } /** * Adds a range of data in the data texture to be updated on the GPU. * * @param {number} start - Position at which to start update. * @param {number} count - The number of components to update. */ addUpdateRange(e, t) { this.updateRanges.push({ start: e, count: t }); } /** * Clears the update ranges. */ clearUpdateRanges() { this.updateRanges.length = 0; } /** * Returns a new texture with copied values from this instance. * * @return {Texture} A clone of this instance. */ clone() { return new this.constructor().copy(this); } /** * Copies the values of the given texture to this instance. * * @param {Texture} source - The texture to copy. * @return {Texture} A reference to this instance. */ copy(e) { return this.name = e.name, this.source = e.source, this.mipmaps = e.mipmaps.slice(0), this.mapping = e.mapping, this.channel = e.channel, this.wrapS = e.wrapS, this.wrapT = e.wrapT, this.magFilter = e.magFilter, this.minFilter = e.minFilter, this.anisotropy = e.anisotropy, this.format = e.format, this.internalFormat = e.internalFormat, this.type = e.type, this.offset.copy(e.offset), this.repeat.copy(e.repeat), this.center.copy(e.center), this.rotation = e.rotation, this.matrixAutoUpdate = e.matrixAutoUpdate, this.matrix.copy(e.matrix), this.generateMipmaps = e.generateMipmaps, this.premultiplyAlpha = e.premultiplyAlpha, this.flipY = e.flipY, this.unpackAlignment = e.unpackAlignment, this.colorSpace = e.colorSpace, this.renderTarget = e.renderTarget, this.isRenderTargetTexture = e.isRenderTargetTexture, this.isArrayTexture = e.isArrayTexture, this.userData = JSON.parse(JSON.stringify(e.userData)), this.needsUpdate = !0, this; } /** * Sets this texture's properties based on `values`. * @param {Object} values - A container with texture parameters. */ setValues(e) { for (const t in e) { const i = e[t]; if (i === void 0) { Se(`Texture.setValues(): parameter '${t}' has value of undefined.`); continue; } const s = this[t]; if (s === void 0) { Se(`Texture.setValues(): property '${t}' does not exist.`); continue; } s && i && s.isVector2 && i.isVector2 || s && i && s.isVector3 && i.isVector3 || s && i && s.isMatrix3 && i.isMatrix3 ? s.copy(i) : this[t] = i; } } /** * Serializes the texture into JSON. * * @param {?(Object|string)} meta - An optional value holding meta information about the serialization. * @return {Object} A JSON object representing the serialized texture. * @see {@link ObjectLoader#parse} */ toJSON(e) { const t = e === void 0 || typeof e == "string"; if (!t && e.textures[this.uuid] !== void 0) return e.textures[this.uuid]; const i = { metadata: { version: 4.7, type: "Texture", generator: "Texture.toJSON" }, uuid: this.uuid, name: this.name, image: this.source.toJSON(e).uuid, mapping: this.mapping, channel: this.channel, repeat: [this.repeat.x, this.repeat.y], offset: [this.offset.x, this.offset.y], center: [this.center.x, this.center.y], rotation: this.rotation, wrap: [this.wrapS, this.wrapT], format: this.format, internalFormat: this.internalFormat, type: this.type, colorSpace: this.colorSpace, minFilter: this.minFilter, magFilter: this.magFilter, anisotropy: this.anisotropy, flipY: this.flipY, generateMipmaps: this.generateMipmaps, premultiplyAlpha: this.premultiplyAlpha, unpackAlignment: this.unpackAlignment }; return Object.keys(this.userData).length > 0 && (i.userData = this.userData), t || (e.textures[this.uuid] = i), i; } /** * Frees the GPU-related resources allocated by this instance. Call this * method whenever this instance is no longer used in your app. * * @fires Texture#dispose */ dispose() { this.dispatchEvent({ type: "dispose" }); } /** * Transforms the given uv vector with the textures uv transformation matrix. * * @param {Vector2} uv - The uv vector. * @return {Vector2} The transformed uv vector. */ transformUv(e) { if (this.mapping !== Xc) return e; if (e.applyMatrix3(this.matrix), e.x < 0 || e.x > 1) switch (this.wrapS) { case Ei: e.x = e.x - Math.floor(e.x); break; case Jt: e.x = e.x < 0 ? 0 : 1; break; case Sn: Math.abs(Math.floor(e.x) % 2) === 1 ? e.x = Math.ceil(e.x) - e.x : e.x = e.x - Math.floor(e.x); break; } if (e.y < 0 || e.y > 1) switch (this.wrapT) { case Ei: e.y = e.y - Math.floor(e.y); break; case Jt: e.y = e.y < 0 ? 0 : 1; break; case Sn: Math.abs(Math.floor(e.y) % 2) === 1 ? e.y = Math.ceil(e.y) - e.y : e.y = e.y - Math.floor(e.y); break; } return this.flipY && (e.y = 1 - e.y), e; } /** * Setting this property to `true` indicates the engine the texture * must be updated in the next render. This triggers a texture upload * to the GPU and ensures correct texture parameter configuration. * * @type {boolean} * @default false * @param {boolean} value */ set needsUpdate(e) { e === !0 && (this.version++, this.source.needsUpdate = !0); } /** * Setting this property to `true` indicates the engine the PMREM * must be regenerated. * * @type {boolean} * @default false * @param {boolean} value */ set needsPMREMUpdate(e) { e === !0 && this.pmremVersion++; } } Ct.DEFAULT_IMAGE = null; Ct.DEFAULT_MAPPING = Xc; Ct.DEFAULT_ANISOTROPY = 1; class Je { /** * Constructs a new 4D vector. * * @param {number} [x=0] - The x value of this vector. * @param {number} [y=0] - The y value of this vector. * @param {number} [z=0] - The z value of this vector. * @param {number} [w=1] - The w value of this vector. */ constructor(e = 0, t = 0, i = 0, s = 1) { Je.prototype.isVector4 = !0, this.x = e, this.y = t, this.z = i, this.w = s; } /** * Alias for {@link Vector4#z}. * * @type {number} */ get width() { return this.z; } set width(e) { this.z = e; } /** * Alias for {@link Vector4#w}. * * @type {number} */ get height() { return this.w; } set height(e) { this.w = e; } /** * Sets the vector components. * * @param {number} x - The value of the x component. * @param {number} y - The value of the y component. * @param {number} z - The value of the z component. * @param {number} w - The value of the w component. * @return {Vector4} A reference to this vector. */ set(e, t, i, s) { return this.x = e, this.y = t, this.z = i, 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(e) { return this.x = e, this.y = e, this.z = e, this.w = e, this; } /** * Sets the vector's x component to the given value * * @param {number} x - The value to set. * @return {Vector4} A reference to this vector. */ setX(e) { return this.x = e, this; } /** * Sets the vector's y component to the given value * * @param {number} y - The value to set. * @return {Vector4} A reference to this vector. */ setY(e) { return this.y = e, this; } /** * Sets the vector's z component to the given value * * @param {number} z - The value to set. * @return {Vector4} A reference to this vector. */ setZ(e) { return this.z = e, this; } /** * Sets the vector's w component to the given value * * @param {number} w - The value to set. * @return {Vector4} A reference to this vector. */ setW(e) { return this.w = e, this; } /** * Allows to set a vector component with an index. * * @param {number} index - The component index. `0` equals to x, `1` equals to y, * `2` equals to z, `3` equals to w. * @param {number} value - The value to set. * @return {Vector4} A reference to this vector. */ setComponent(e, t) { switch (e) { case 0: this.x = t; break; case 1: this.y = t; break; case 2: this.z = t; break; case 3: this.w = t; break; default: throw new Error("index is out of range: " + e); } return this; } /** * Returns the value of the vector component which matches the given index. * * @param {number} index - The component index. `0` equals to x, `1` equals to y, * `2` equals to z, `3` equals to w. * @return {number} A vector component value. */ getComponent(e) { switch (e) { case 0: return this.x; case 1: return this.y; case 2: return this.z; case 3: return this.w; default: throw new Error("index is out of range: " + e); } } /** * Returns a new vector with copied values from this instance. * * @return {Vector4} A clone of this instance. */ clone() { return new this.constructor(this.x, this.y, this.z, this.w); } /** * Copies the values of the given vector to this instance. * * @param {Vector3|Vector4} v - The vector to copy. * @return {Vector4} A reference to this vector. */ copy(e) { return this.x = e.x, this.y = e.y, this.z = e.z, this.w = e.w !== void 0 ? e.w : 1, this; } /** * Adds the given vector to this instance. * * @param {Vector4} v - The vector to add. * @return {Vector4} A reference to this vector. */ add(e) { return this.x += e.x, this.y += e.y, this.z += e.z, this.w += e.w, this; } /** * Adds the given scalar value to all components of this instance. * * @param {number} s - The scalar to add. * @return {Vector4} A reference to this vector. */ addScalar(e) { return this.x += e, this.y += e, this.z += e, this.w += e, this; } /** * Adds the given vectors and stores the result in this instance. * * @param {Vector4} a - The first vector. * @param {Vector4} b - The second vector. * @return {Vector4} A reference to this vector. */ addVectors(e, t) { return this.x = e.x + t.x, this.y = e.y + t.y, this.z = e.z + t.z, this.w = e.w + t.w, this; } /** * Adds the given vector scaled by the given factor to this instance. * * @param {Vector4} v - The vector. * @param {number} s - The factor that scales `v`. * @return {Vector4} A reference to this vector. */ addScaledVector(e, t) { return this.x += e.x * t, this.y += e.y * t, this.z += e.z * t, this.w += e.w * t, this; } /** * Subtracts the given vector from this instance. * * @param {Vector4} v - The vector to subtract. * @return {Vector4} A reference to this vector. */ sub(e) { return this.x -= e.x, this.y -= e.y, this.z -= e.z, this.w -= e.w, this; } /** * Subtracts the given scalar value from all components of this instance. * * @param {number} s - The scalar to subtract. * @return {Vector4} A reference to this vector. */ subScalar(e) { return this.x -= e, this.y -= e, this.z -= e, this.w -= e, this; } /** * Subtracts the given vectors and stores the result in this instance. * * @param {Vector4} a - The first vector. * @param {Vector4} b - The second vector. * @return {Vector4} A reference to this vector. */ subVectors(e, t) { return this.x = e.x - t.x, this.y = e.y - t.y, this.z = e.z - t.z, this.w = e.w - t.w, this; } /** * Multiplies the given vector with this instance. * * @param {Vector4} v - The vector to multiply. * @return {Vector4} A reference to this vector. */ multiply(e) { return this.x *= e.x, this.y *= e.y, this.z *= e.z, this.w *= e.w, this; } /** * Multiplies the given scalar value with all components of this instance. * * @param {number} scalar - The scalar to multiply. * @return {Vector4} A reference to this vector. */ multiplyScalar(e) { return this.x *= e, this.y *= e, this.z *= e, this.w *= e, this; } /** * Multiplies this vector with the given 4x4 matrix. * * @param {Matrix4} m - The 4x4 matrix. * @return {Vector4} A reference to this vector. */ applyMatrix4(e) { const t = this.x, i = this.y, s = this.z, n = this.w, a = e.elements; return this.x = a[0] * t + a[4] * i + a[8] * s + a[12] * n, this.y = a[1] * t + a[5] * i + a[9] * s + a[13] * n, this.z = a[2] * t + a[6] * i + a[10] * s + a[14] * n, this.w = a[3] * t + a[7] * i + a[11] * s + a[15] * n, this; } /** * Divides this instance by the given vector. * * @param {Vector4} v - The vector to divide. * @return {Vector4} A reference to this vector. */ divide(e) { return this.x /= e.x, this.y /= e.y, this.z /= e.z, this.w /= e.w, this; } /** * Divides this vector by the given scalar. * * @param {number} scalar - The scalar to divide. * @return {Vector4} A reference to this vector. */ divideScalar(e) { return this.multiplyScalar(1 / e); } /** * Sets the x, y and z components of this * vector to the quaternion's axis and w to the angle. * * @param {Quaternion} q - The Quaternion to set. * @return {Vector4} A reference to this vector. */ setAxisAngleFromQuaternion(e) { this.w = 2 * Math.acos(e.w); const t = Math.sqrt(1 - e.w * e.w); return t < 1e-4 ? (this.x = 1, this.y = 0, this.z = 0) : (this.x = e.x / t, this.y = e.y / t, this.z = e.z / t), this; } /** * Sets the x, y and z components of this * vector to the axis of rotation and w to the angle. * * @param {Matrix4} m - A 4x4 matrix of which the upper left 3x3 matrix is a pure rotation matrix. * @return {Vector4} A reference to this vector. */ setAxisAngleFromRotationMatrix(e) { let t, i, s, n; const a = e.elements, o = a[0], l = a[4], c = a[8], h = a[1], u = a[5], d = a[9], f = a[2], g = a[6], v = a[10]; if (Math.abs(l - h) < 0.01 && Math.abs(c - f) < 0.01 && Math.abs(d - g) < 0.01) { if (Math.abs(l + h) < 0.1 && Math.abs(c + f) < 0.1 && Math.abs(d + g) < 0.1 && Math.abs(o + u + v - 3) < 0.1) return this.set(1, 0, 0, 0), this; t = Math.PI; const p = (o + 1) / 2, y = (u + 1) / 2, _ = (v + 1) / 2, E = (l + h) / 4, A = (c + f) / 4, T = (d + g) / 4; return p > y && p > _ ? p < 0.01 ? (i = 0, s = 0.707106781, n = 0.707106781) : (i = Math.sqrt(p), s = E / i, n = A / i) : y > _ ? y < 0.01 ? (i = 0.707106781, s = 0, n = 0.707106781) : (s = Math.sqrt(y), i = E / s, n = T / s) : _ < 0.01 ? (i = 0.707106781, s = 0.707106781, n = 0) : (n = Math.sqrt(_), i = A / n, s = T / n), this.set(i, s, n, t), this; } let m = Math.sqrt((g - d) * (g - d) + (c - f) * (c - f) + (h - l) * (h - l)); return Math.abs(m) < 1e-3 && (m = 1), this.x = (g - d) / m, this.y = (c - f) / m, this.z = (h - l) / m, this.w = Math.acos((o + u + v - 1) / 2), this; } /** * Sets the vector components to the position elements of the * given transformation matrix. * * @param {Matrix4} m - The 4x4 matrix. * @return {Vector4} A reference to this vector. */ setFromMatrixPosition(e) { const t = e.elements; return this.x = t[12], this.y = t[13], this.z = t[14], this.w = t[15], this; } /** * If this vector's x, y, z or w value is greater than the given vector's x, y, z or w * value, replace that value with the corresponding min value. * * @param {Vector4} v - The vector. * @return {Vector4} A reference to this vector. */ min(e) { return this.x = Math.min(this.x, e.x), this.y = Math.min(this.y, e.y), this.z = Math.min(this.z, e.z), this.w = Math.min(this.w, e.w), this; } /** * If this vector's x, y, z or w value is less than the given vector's x, y, z or w * value, replace that value with the corresponding max value. * * @param {Vector4} v - The vector. * @return {Vector4} A reference to this vector. */ max(e) { return this.x = Math.max(this.x, e.x), this.y = Math.max(this.y, e.y), this.z = Math.max(this.z, e.z), this.w = Math.max(this.w, e.w), this; } /** * If this vector's x, y, z or w value is greater than the max vector's x, y, z or w * value, it is replaced by the corresponding value. * If this vector's x, y, z or w value is less than the min vector's x, y, z or w value, * it is replaced by the corresponding value. * * @param {Vector4} min - The minimum x, y and z values. * @param {Vector4} max - The maximum x, y and z values in the desired range. * @return {Vector4} A reference to this vector. */ clamp(e, t) { return this.x = ze(this.x, e.x, t.x), this.y = ze(this.y, e.y, t.y), this.z = ze(this.z, e.z, t.z), this.w = ze(this.w, e.w, t.w), this; } /** * If this vector's x, y, z or w values are greater than the max value, they are * replaced by the max value. * If this vector's x, y, z or w values are less than the min value, they are * replaced by the min value. * * @param {number} minVal - The minimum value the components will be clamped to. * @param {number} maxVal - The maximum value the components will be clamped to. * @return {Vector4} A reference to this vector. */ clampScalar(e, t) { return this.x = ze(this.x, e, t), this.y = ze(this.y, e, t), this.z = ze(this.z, e, t), this.w = ze(this.w, e, t), this; } /** * If this vector's length is greater than the max value, it is replaced by * the max value. * If this vector's length is less than the min value, it is replaced by the * min value. * * @param {number} min - The minimum value the vector length will be clamped to. * @param {number} max - The maximum value the vector length will be clamped to. * @return {Vector4} A reference to this vector. */ clampLength(e, t) { const i = this.length(); return this.divideScalar(i || 1).multiplyScalar(ze(i, e, t)); } /** * The components of this vector are rounded down to the nearest integer value. * * @return {Vector4} A reference to this vector. */ floor() { return this.x = Math.floor(this.x), this.y = Math.floor(this.y), this.z = Math.floor(this.z), this.w = Math.floor(this.w), this; } /** * The components of this vector are rounded up to the nearest integer value. * * @return {Vector4} A reference to this vector. */ ceil() { return this.x = Math.ceil(this.x), this.y = Math.ceil(this.y), this.z = Math.ceil(this.z), this.w = Math.ceil(this.w), this; } /** * The components of this vector are rounded to the nearest integer value * * @return {Vector4} A reference to this vector. */ round() { return this.x = Math.round(this.x), this.y = Math.round(this.y), this.z = Math.round(this.z), this.w = Math.round(this.w), this; } /** * The components of this vector are rounded towards zero (up if negative, * down if positive) to an integer value. * * @return {Vector4} A reference to this vector. */ roundToZero() { return this.x = Math.trunc(this.x), this.y = Math.trunc(this.y), this.z = Math.trunc(this.z), this.w = Math.trunc(this.w), this; } /** * Inverts this vector - i.e. sets x = -x, y = -y, z = -z, w = -w. * * @return {Vector4} A reference to this vector. */ negate() { return this.x = -this.x, this.y = -this.y, this.z = -this.z, this.w = -this.w, this; } /** * Calculates the dot product of the given vector with this instance. * * @param {Vector4} v - The vector to compute the dot product with. * @return {number} The result of the dot product. */ dot(e) { return this.x * e.x + this.y * e.y + this.z * e.z + this.w * e.w; } /** * Computes the square of the Euclidean length (straight-line length) from * (0, 0, 0, 0) to (x, y, z, w). If you are comparing the lengths of vectors, you should * compare the length squared instead as it is slightly more efficient to calculate. * * @return {number} The square length of this vector. */ lengthSq() { return this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w; } /** * Computes the Euclidean length (straight-line length) from (0, 0, 0, 0) to (x, y, z, w). * * @return {number} The length of this vector. */ length() { return Math.sqrt(this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w); } /** * Computes the Manhattan length of this vector. * * @return {number} The length of this vector. */ manhattanLength() { return Math.abs(this.x) + Math.abs(this.y) + Math.abs(this.z) + Math.abs(this.w); } /** * Converts this vector to a unit vector - that is, sets it equal to a vector * with the same direction as this one, but with a vector length of `1`. * * @return {Vector4} A reference to this vector. */ normalize() { return this.divideScalar(this.length() || 1); } /** * Sets this vector to a vector with the same direction as this one, but * with the specified length. * * @param {number} length - The new length of this vector. * @return {Vector4} A reference to this vector. */ setLength(e) { return this.normalize().multiplyScalar(e); } /** * Linearly interpolates between the given vector and this instance, where * alpha is the percent distance along the line - alpha = 0 will be this * vector, and alpha = 1 will be the given one. * * @param {Vector4} v - The vector to interpolate towards. * @param {number} alpha - The interpolation factor, typically in the closed interval `[0, 1]`. * @return {Vector4} A reference to this vector. */ lerp(e, t) { return this.x += (e.x - this.x) * t, this.y += (e.y - this.y) * t, this.z += (e.z - this.z) * t, this.w += (e.w - this.w) * t, this; } /** * Linearly interpolates between the given vectors, where alpha is the percent * distance along the line - alpha = 0 will be first vector, and alpha = 1 will * be the second one. The result is stored in this instance. * * @param {Vector4} v1 - The first vector. * @param {Vector4} v2 - The second vector. * @param {number} alpha - The interpolation factor, typically in the closed interval `[0, 1]`. * @return {Vector4} A reference to this vector. */ lerpVectors(e, t, i) { return this.x = e.x + (t.x - e.x) * i, this.y = e.y + (t.y - e.y) * i, this.z = e.z + (t.z - e.z) * i, this.w = e.w + (t.w - e.w) * i, this; } /** * Returns `true` if this vector is equal with the given one. * * @param {Vector4} v - The vector to test for equality. * @return {boolean} Whether this vector is equal with the given one. */ equals(e) { return e.x === this.x && e.y === this.y && e.z === this.z && e.w === this.w; } /** * Sets this vector's x value to be `array[ offset ]`, y value to be `array[ offset + 1 ]`, * z value to be `array[ offset + 2 ]`, w value to be `array[ offset + 3 ]`. * * @param {Array} array - An array holding the vector component values. * @param {number} [offset=0] - The offset into the array. * @return {Vector4} A reference to this vector. */ fromArray(e, t = 0) { return this.x = e[t], this.y = e[t + 1], this.z = e[t + 2], this.w = e[t + 3], this; } /** * Writes the components of this vector to the given array. If no array is provided, * the method returns a new instance. * * @param {Array} [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(e = [], t = 0) { return e[t] = this.x, e[t + 1] = this.y, e[t + 2] = this.z, e[t + 3] = this.w, e; } /** * Sets the components of this vector from the given buffer attribute. * * @param {BufferAttribute} attribute - The buffer attribute holding vector data. * @param {number} index - The index into the attribute. * @return {Vector4} A reference to this vector. */ fromBufferAttribute(e, t) { return this.x = e.getX(t), this.y = e.getY(t), this.z = e.getZ(t), this.w = e.getW(t), this; } /** * Sets each component of this vector to a pseudo-random value between `0` and * `1`, excluding `1`. * * @return {Vector4} A reference to this vector. */ random() { return this.x = Math.random(), this.y = Math.random(), this.z = Math.random(), this.w = Math.random(), this; } *[Symbol.iterator]() { yield this.x, yield this.y, yield this.z, yield this.w; } } class Zu extends gr { /** * Render target options. * * @typedef {Object} RenderTarget~Options * @property {boolean} [generateMipmaps=false] - Whether to generate mipmaps or not. * @property {number} [magFilter=LinearFilter] - The mag filter. * @property {number} [minFilter=LinearFilter] - The min filter. * @property {number} [format=RGBAFormat] - The texture format. * @property {number} [type=UnsignedByteType] - The texture type. * @property {?string} [internalFormat=null] - The texture's internal format. * @property {number} [wrapS=ClampToEdgeWrapping] - The texture's uv wrapping mode. * @property {number} [wrapT=ClampToEdgeWrapping] - The texture's uv wrapping mode. * @property {number} [anisotropy=1] - The texture's anisotropy value. * @property {string} [colorSpace=NoColorSpace] - The texture's color space. * @property {boolean} [depthBuffer=true] - Whether to allocate a depth buffer or not. * @property {boolean} [stencilBuffer=false] - Whether to allocate a stencil buffer or not. * @property {boolean} [resolveDepthBuffer=true] - Whether to resolve the depth buffer or not. * @property {boolean} [resolveStencilBuffer=true] - Whether to resolve the stencil buffer or not. * @property {?Texture} [depthTexture=null] - Reference to a depth texture. * @property {number} [samples=0] - The MSAA samples count. * @property {number} [count=1] - Defines the number of color attachments . Must be at least `1`. * @property {number} [depth=1] - The texture depth. * @property {boolean} [multiview=false] - Whether this target is used for multiview rendering. */ /** * Constructs a new render target. * * @param {number} [width=1] - The width of the render target. * @param {number} [height=1] - The height of the render target. * @param {RenderTarget~Options} [options] - The configuration object. */ constructor(e = 1, t = 1, i = {}) { super(), i = Object.assign({ generateMipmaps: !1, internalFormat: null, minFilter: xt, depthBuffer: !0, stencilBuffer: !1, resolveDepthBuffer: !0, resolveStencilBuffer: !0, depthTexture: null, samples: 0, count: 1, depth: 1, multiview: !1 }, i), this.isRenderTarget = !0, this.width = e, this.height = t, this.depth = i.depth, this.scissor = new Je(0, 0, e, t), this.scissorTest = !1, this.viewport = new Je(0, 0, e, t); const s = { width: e, height: t, depth: i.depth }, n = new Ct(s); this.textures = []; const a = i.count; for (let o = 0; o < a; o++) this.textures[o] = n.clone(), this.textures[o].isRenderTargetTexture = !0, this.textures[o].renderTarget = this; this._setTextureOptions(i), this.depthBuffer = i.depthBuffer, this.stencilBuffer = i.stencilBuffer, this.resolveDepthBuffer = i.resolveDepthBuffer, this.resolveStencilBuffer = i.resolveStencilBuffer, this._depthTexture = null, this.depthTexture = i.depthTexture, this.samples = i.samples, this.multiview = i.multiview; } _setTextureOptions(e = {}) { const t = { minFilter: xt, generateMipmaps: !1, flipY: !1, internalFormat: null }; e.mapping !== void 0 && (t.mapping = e.mapping), e.wrapS !== void 0 && (t.wrapS = e.wrapS), e.wrapT !== void 0 && (t.wrapT = e.wrapT), e.wrapR !== void 0 && (t.wrapR = e.wrapR), e.magFilter !== void 0 && (t.magFilter = e.magFilter), e.minFilter !== void 0 && (t.minFilter = e.minFilter), e.format !== void 0 && (t.format = e.format), e.type !== void 0 && (t.type = e.type), e.anisotropy !== void 0 && (t.anisotropy = e.anisotropy), e.colorSpace !== void 0 && (t.colorSpace = e.colorSpace), e.flipY !== void 0 && (t.flipY = e.flipY), e.generateMipmaps !== void 0 && (t.generateMipmaps = e.generateMipmaps), e.internalFormat !== void 0 && (t.internalFormat = e.internalFormat); for (let i = 0; i < this.textures.length; i++) this.textures[i].setValues(t); } /** * The texture representing the default color attachment. * * @type {Texture} */ get texture() { return this.textures[0]; } set texture(e) { this.textures[0] = e; } set depthTexture(e) { this._depthTexture !== null && (this._depthTexture.renderTarget = null), e !== null && (e.renderTarget = this), this._depthTexture = e; } /** * Instead of saving the depth in a renderbuffer, a texture * can be used instead which is useful for further processing * e.g. in context of post-processing. * * @type {?DepthTexture} * @default null */ get depthTexture() { return this._depthTexture; } /** * Sets the size of this render target. * * @param {number} width - The width. * @param {number} height - The height. * @param {number} [depth=1] - The depth. */ setSize(e, t, i = 1) { if (this.width !== e || this.height !== t || this.depth !== i) { this.width = e, this.height = t, this.depth = i; for (let s = 0, n = this.textures.length; s < n; s++) this.textures[s].image.width = e, this.textures[s].image.height = t, this.textures[s].image.depth = i, this.textures[s].isData3DTexture !== !0 && (this.textures[s].isArrayTexture = this.textures[s].image.depth > 1); this.dispose(); } this.viewport.set(0, 0, e, t), this.scissor.set(0, 0, e, t); } /** * Returns a new render target with copied values from this instance. * * @return {RenderTarget} A clone of this instance. */ clone() { return new this.constructor().copy(this); } /** * Copies the settings of the given render target. This is a structural copy so * no resources are shared between render targets after the copy. That includes * all MRT textures and the depth texture. * * @param {RenderTarget} source - The render target to copy. * @return {RenderTarget} A reference to this instance. */ copy(e) { this.width = e.width, this.height = e.height, this.depth = e.depth, this.scissor.copy(e.scissor), this.scissorTest = e.scissorTest, this.viewport.copy(e.viewport), this.textures.length = 0; for (let t = 0, i = e.textures.length; t < i; t++) { this.textures[t] = e.textures[t].clone(), this.textures[t].isRenderTargetTexture = !0, this.textures[t].renderTarget = this; const s = Object.assign({}, e.textures[t].image); this.textures[t].source = new Oo(s); } return this.depthBuffer = e.depthBuffer, this.stencilBuffer = e.stencilBuffer, this.resolveDepthBuffer = e.resolveDepthBuffer, this.resolveStencilBuffer = e.resolveStencilBuffer, e.depthTexture !== null && (this.depthTexture = e.depthTexture.clone()), this.samples = e.samples, this; } /** * Frees the GPU-related resources allocated by this instance. Call this * method whenever this instance is no longer used in your app. * * @fires RenderTarget#dispose */ dispose() { this.dispatchEvent({ type: "dispose" }); } } class _t extends Zu { /** * Constructs a new 3D render target. * * @param {number} [width=1] - The width of the render target. * @param {number} [height=1] - The height of the render target. * @param {RenderTarget~Options} [options] - The configuration object. */ constructor(e = 1, t = 1, i = {}) { super(e, t, i), this.isWebGLRenderTarget = !0; } } class sh extends Ct { /** * Constructs a new data array texture. * * @param {?TypedArray} [data=null] - The buffer data. * @param {number} [width=1] - The width of the texture. * @param {number} [height=1] - The height of the texture. * @param {number} [depth=1] - The depth of the texture. */ constructor(e = null, t = 1, i = 1, s = 1) { super(null), this.isDataArrayTexture = !0, this.image = { data: e, width: t, height: i, depth: s }, this.magFilter = Dt, this.minFilter = Dt, this.wrapR = Jt, this.generateMipmaps = !1, this.flipY = !1, this.unpackAlignment = 1, this.layerUpdates = /* @__PURE__ */ new Set(); } /** * Describes that a specific layer of the texture needs to be updated. * Normally when {@link Texture#needsUpdate} is set to `true`, the * entire data texture array is sent to the GPU. Marking specific * layers will only transmit subsets of all mipmaps associated with a * specific depth in the array which is often much more performant. * * @param {number} layerIndex - The layer index that should be updated. */ addLayerUpdate(e) { this.layerUpdates.add(e); } /** * Resets the layer updates registry. */ clearLayerUpdates() { this.layerUpdates.clear(); } } class Ju extends Ct { /** * Constructs a new data array texture. * * @param {?TypedArray} [data=null] - The buffer data. * @param {number} [width=1] - The width of the texture. * @param {number} [height=1] - The height of the texture. * @param {number} [depth=1] - The depth of the texture. */ constructor(e = null, t = 1, i = 1, s = 1) { super(null), this.isData3DTexture = !0, this.image = { data: e, width: t, height: i, depth: s }, this.magFilter = Dt, this.minFilter = Dt, this.wrapR = Jt, this.generateMipmaps = !1, this.flipY = !1, this.unpackAlignment = 1; } } class Rt { /** * Constructs a new bounding box. * * @param {Vector3} [min=(Infinity,Infinity,Infinity)] - A vector representing the lower boundary of the box. * @param {Vector3} [max=(-Infinity,-Infinity,-Infinity)] - A vector representing the upper boundary of the box. */ constructor(e = new w(1 / 0, 1 / 0, 1 / 0), t = new w(-1 / 0, -1 / 0, -1 / 0)) { this.isBox3 = !0, this.min = e, this.max = t; } /** * Sets the lower and upper boundaries of this box. * Please note that this method only copies the values from the given objects. * * @param {Vector3} min - The lower boundary of the box. * @param {Vector3} max - The upper boundary of the box. * @return {Box3} A reference to this bounding box. */ set(e, t) { return this.min.copy(e), this.max.copy(t), this; } /** * Sets the upper and lower bounds of this box so it encloses the position data * in the given array. * * @param {Array} array - An array holding 3D position data. * @return {Box3} A reference to this bounding box. */ setFromArray(e) { this.makeEmpty(); for (let t = 0, i = e.length; t < i; t += 3) this.expandByPoint(ri.fromArray(e, t)); return this; } /** * Sets the upper and lower bounds of this box so it encloses the position data * in the given buffer attribute. * * @param {BufferAttribute} attribute - A buffer attribute holding 3D position data. * @return {Box3} A reference to this bounding box. */ setFromBufferAttribute(e) { this.makeEmpty(); for (let t = 0, i = e.count; t < i; t++) this.expandByPoint(ri.fromBufferAttribute(e, t)); return this; } /** * Sets the upper and lower bounds of this box so it encloses the position data * in the given array. * * @param {Array} points - An array holding 3D position data as instances of {@link Vector3}. * @return {Box3} A reference to this bounding box. */ setFromPoints(e) { this.makeEmpty(); for (let t = 0, i = e.length; t < i; t++) this.expandByPoint(e[t]); return this; } /** * Centers this box on the given center vector and sets this box's width, height and * depth to the given size values. * * @param {Vector3} center - The center of the box. * @param {Vector3} size - The x, y and z dimensions of the box. * @return {Box3} A reference to this bounding box. */ setFromCenterAndSize(e, t) { const i = ri.copy(t).multiplyScalar(0.5); return this.min.copy(e).sub(i), this.max.copy(e).add(i), this; } /** * Computes the world-axis-aligned bounding box for the given 3D object * (including its children), accounting for the object's, and children's, * world transforms. The function may result in a larger box than strictly necessary. * * @param {Object3D} object - The 3D object to compute the bounding box for. * @param {boolean} [precise=false] - If set to `true`, the method computes the smallest * world-axis-aligned bounding box at the expense of more computation. * @return {Box3} A reference to this bounding box. */ setFromObject(e, t = !1) { return this.makeEmpty(), this.expandByObject(e, t); } /** * Returns a new box with copied values from this instance. * * @return {Box3} A clone of this instance. */ clone() { return new this.constructor().copy(this); } /** * Copies the values of the given box to this instance. * * @param {Box3} box - The box to copy. * @return {Box3} A reference to this bounding box. */ copy(e) { return this.min.copy(e.min), this.max.copy(e.max), this; } /** * Makes this box empty which means in encloses a zero space in 3D. * * @return {Box3} A reference to this bounding box. */ makeEmpty() { return this.min.x = this.min.y = this.min.z = 1 / 0, this.max.x = this.max.y = this.max.z = -1 / 0, this; } /** * Returns true if this box includes zero points within its bounds. * Note that a box with equal lower and upper bounds still includes one * point, the one both bounds share. * * @return {boolean} Whether this box is empty or not. */ isEmpty() { return this.max.x < this.min.x || this.max.y < this.min.y || this.max.z < this.min.z; } /** * Returns the center point of this box. * * @param {Vector3} target - The target vector that is used to store the method's result. * @return {Vector3} The center point. */ getCenter(e) { return this.isEmpty() ? e.set(0, 0, 0) : e.addVectors(this.min, this.max).multiplyScalar(0.5); } /** * Returns the dimensions of this box. * * @param {Vector3} target - The target vector that is used to store the method's result. * @return {Vector3} The size. */ getSize(e) { return this.isEmpty() ? e.set(0, 0, 0) : e.subVectors(this.max, this.min); } /** * Expands the boundaries of this box to include the given point. * * @param {Vector3} point - The point that should be included by the bounding box. * @return {Box3} A reference to this bounding box. */ expandByPoint(e) { return this.min.min(e), this.max.max(e), this; } /** * Expands this box equilaterally by the given vector. The width of this * box will be expanded by the x component of the vector in both * directions. The height of this box will be expanded by the y component of * the vector in both directions. The depth of this box will be * expanded by the z component of the vector in both directions. * * @param {Vector3} vector - The vector that should expand the bounding box. * @return {Box3} A reference to this bounding box. */ expandByVector(e) { return this.min.sub(e), this.max.add(e), this; } /** * Expands each dimension of the box by the given scalar. If negative, the * dimensions of the box will be contracted. * * @param {number} scalar - The scalar value that should expand the bounding box. * @return {Box3} A reference to this bounding box. */ expandByScalar(e) { return this.min.addScalar(-e), this.max.addScalar(e), this; } /** * Expands the boundaries of this box to include the given 3D object and * its children, accounting for the object's, and children's, world * transforms. The function may result in a larger box than strictly * necessary (unless the precise parameter is set to true). * * @param {Object3D} object - The 3D object that should expand the bounding box. * @param {boolean} precise - If set to `true`, the method expands the bounding box * as little as necessary at the expense of more computation. * @return {Box3} A reference to this bounding box. */ expandByObject(e, t = !1) { e.updateWorldMatrix(!1, !1); const i = e.geometry; if (i !== void 0) { const n = i.getAttribute("position"); if (t === !0 && n !== void 0 && e.isInstancedMesh !== !0) for (let a = 0, o = n.count; a < o; a++) e.isMesh === !0 ? e.getVertexPosition(a, ri) : ri.fromBufferAttribute(n, a), ri.applyMatrix4(e.matrixWorld), this.expandByPoint(ri); else e.boundingBox !== void 0 ? (e.boundingBox === null && e.computeBoundingBox(), Us.copy(e.boundingBox)) : (i.boundingBox === null && i.computeBoundingBox(), Us.copy(i.boundingBox)), Us.applyMatrix4(e.matrixWorld), this.union(Us); } const s = e.children; for (let n = 0, a = s.length; n < a; n++) this.expandByObject(s[n], t); return this; } /** * Returns `true` if the given point lies within or on the boundaries of this box. * * @param {Vector3} point - The point to test. * @return {boolean} Whether the bounding box contains the given point or not. */ containsPoint(e) { return e.x >= this.min.x && e.x <= this.max.x && e.y >= this.min.y && e.y <= this.max.y && e.z >= this.min.z && e.z <= this.max.z; } /** * Returns `true` if this bounding box includes the entirety of the given bounding box. * If this box and the given one are identical, this function also returns `true`. * * @param {Box3} box - The bounding box to test. * @return {boolean} Whether the bounding box contains the given bounding box or not. */ containsBox(e) { return this.min.x <= e.min.x && e.max.x <= this.max.x && this.min.y <= e.min.y && e.max.y <= this.max.y && this.min.z <= e.min.z && e.max.z <= this.max.z; } /** * Returns a point as a proportion of this box's width, height and depth. * * @param {Vector3} point - A point in 3D space. * @param {Vector3} target - The target vector that is used to store the method's result. * @return {Vector3} A point as a proportion of this box's width, height and depth. */ getParameter(e, t) { return t.set( (e.x - this.min.x) / (this.max.x - this.min.x), (e.y - this.min.y) / (this.max.y - this.min.y), (e.z - this.min.z) / (this.max.z - this.min.z) ); } /** * Returns `true` if the given bounding box intersects with this bounding box. * * @param {Box3} box - The bounding box to test. * @return {boolean} Whether the given bounding box intersects with this bounding box. */ intersectsBox(e) { return e.max.x >= this.min.x && e.min.x <= this.max.x && e.max.y >= this.min.y && e.min.y <= this.max.y && e.max.z >= this.min.z && e.min.z <= this.max.z; } /** * Returns `true` if the given bounding sphere intersects with this bounding box. * * @param {Sphere} sphere - The bounding sphere to test. * @return {boolean} Whether the given bounding sphere intersects with this bounding box. */ intersectsSphere(e) { return this.clampPoint(e.center, ri), ri.distanceToSquared(e.center) <= e.radius * e.radius; } /** * Returns `true` if the given plane intersects with this bounding box. * * @param {Plane} plane - The plane to test. * @return {boolean} Whether the given plane intersects with this bounding box. */ intersectsPlane(e) { let t, i; return e.normal.x > 0 ? (t = e.normal.x * this.min.x, i = e.normal.x * this.max.x) : (t = e.normal.x * this.max.x, i = e.normal.x * this.min.x), e.normal.y > 0 ? (t += e.normal.y * this.min.y, i += e.normal.y * this.max.y) : (t += e.normal.y * this.max.y, i += e.normal.y * this.min.y), e.normal.z > 0 ? (t += e.normal.z * this.min.z, i += e.normal.z * this.max.z) : (t += e.normal.z * this.max.z, i += e.normal.z * this.min.z), t <= -e.constant && i >= -e.constant; } /** * Returns `true` if the given triangle intersects with this bounding box. * * @param {Triangle} triangle - The triangle to test. * @return {boolean} Whether the given triangle intersects with this bounding box. */ intersectsTriangle(e) { if (this.isEmpty()) return !1; this.getCenter(ns), Ns.subVectors(this.max, ns), yr.subVectors(e.a, ns), Mr.subVectors(e.b, ns), Sr.subVectors(e.c, ns), Vi.subVectors(Mr, yr), Gi.subVectors(Sr, Mr), sr.subVectors(yr, Sr); let t = [ 0, -Vi.z, Vi.y, 0, -Gi.z, Gi.y, 0, -sr.z, sr.y, Vi.z, 0, -Vi.x, Gi.z, 0, -Gi.x, sr.z, 0, -sr.x, -Vi.y, Vi.x, 0, -Gi.y, Gi.x, 0, -sr.y, sr.x, 0 ]; return !Gn(t, yr, Mr, Sr, Ns) || (t = [1, 0, 0, 0, 1, 0, 0, 0, 1], !Gn(t, yr, Mr, Sr, Ns)) ? !1 : (Os.crossVectors(Vi, Gi), t = [Os.x, Os.y, Os.z], Gn(t, yr, Mr, Sr, Ns)); } /** * Clamps the given point within the bounds of this box. * * @param {Vector3} point - The point to clamp. * @param {Vector3} target - The target vector that is used to store the method's result. * @return {Vector3} The clamped point. */ clampPoint(e, t) { return t.copy(e).clamp(this.min, this.max); } /** * Returns the euclidean distance from any edge of this box to the specified point. If * the given point lies inside of this box, the distance will be `0`. * * @param {Vector3} point - The point to compute the distance to. * @return {number} The euclidean distance. */ distanceToPoint(e) { return this.clampPoint(e, ri).distanceTo(e); } /** * Returns a bounding sphere that encloses this bounding box. * * @param {Sphere} target - The target sphere that is used to store the method's result. * @return {Sphere} The bounding sphere that encloses this bounding box. */ getBoundingSphere(e) { return this.isEmpty() ? e.makeEmpty() : (this.getCenter(e.center), e.radius = this.getSize(ri).length() * 0.5), e; } /** * Computes the intersection of this bounding box and the given one, setting the upper * bound of this box to the lesser of the two boxes' upper bounds and the * lower bound of this box to the greater of the two boxes' lower bounds. If * there's no overlap, makes this box empty. * * @param {Box3} box - The bounding box to intersect with. * @return {Box3} A reference to this bounding box. */ intersect(e) { return this.min.max(e.min), this.max.min(e.max), this.isEmpty() && this.makeEmpty(), this; } /** * Computes the union of this box and another and the given one, setting the upper * bound of this box to the greater of the two boxes' upper bounds and the * lower bound of this box to the lesser of the two boxes' lower bounds. * * @param {Box3} box - The bounding box that will be unioned with this instance. * @return {Box3} A reference to this bounding box. */ union(e) { return this.min.min(e.min), this.max.max(e.max), this; } /** * Transforms this bounding box by the given 4x4 transformation matrix. * * @param {Matrix4} matrix - The transformation matrix. * @return {Box3} A reference to this bounding box. */ applyMatrix4(e) { return this.isEmpty() ? this : (Pi[0].set(this.min.x, this.min.y, this.min.z).applyMatrix4(e), Pi[1].set(this.min.x, this.min.y, this.max.z).applyMatrix4(e), Pi[2].set(this.min.x, this.max.y, this.min.z).applyMatrix4(e), Pi[3].set(this.min.x, this.max.y, this.max.z).applyMatrix4(e), Pi[4].set(this.max.x, this.min.y, this.min.z).applyMatrix4(e), Pi[5].set(this.max.x, this.min.y, this.max.z).applyMatrix4(e), Pi[6].set(this.max.x, this.max.y, this.min.z).applyMatrix4(e), Pi[7].set(this.max.x, this.max.y, this.max.z).applyMatrix4(e), this.setFromPoints(Pi), this); } /** * Adds the given offset to both the upper and lower bounds of this bounding box, * effectively moving it in 3D space. * * @param {Vector3} offset - The offset that should be used to translate the bounding box. * @return {Box3} A reference to this bounding box. */ translate(e) { return this.min.add(e), this.max.add(e), this; } /** * Returns `true` if this bounding box is equal with the given one. * * @param {Box3} box - The box to test for equality. * @return {boolean} Whether this bounding box is equal with the given one. */ equals(e) { return e.min.equals(this.min) && e.max.equals(this.max); } /** * Returns a serialized structure of the bounding box. * * @return {Object} Serialized structure with fields representing the object state. */ toJSON() { return { min: this.min.toArray(), max: this.max.toArray() }; } /** * Returns a serialized structure of the bounding box. * * @param {Object} json - The serialized json to set the box from. * @return {Box3} A reference to this bounding box. */ fromJSON(e) { return this.min.fromArray(e.min), this.max.fromArray(e.max), this; } } const Pi = [ /* @__PURE__ */ new w(), /* @__PURE__ */ new w(), /* @__PURE__ */ new w(), /* @__PURE__ */ new w(), /* @__PURE__ */ new w(), /* @__PURE__ */ new w(), /* @__PURE__ */ new w(), /* @__PURE__ */ new w() ], ri = /* @__PURE__ */ new w(), Us = /* @__PURE__ */ new Rt(), yr = /* @__PURE__ */ new w(), Mr = /* @__PURE__ */ new w(), Sr = /* @__PURE__ */ new w(), Vi = /* @__PURE__ */ new w(), Gi = /* @__PURE__ */ new w(), sr = /* @__PURE__ */ new w(), ns = /* @__PURE__ */ new w(), Ns = /* @__PURE__ */ new w(), Os = /* @__PURE__ */ new w(), nr = /* @__PURE__ */ new w(); function Gn(r, e, t, i, s) { for (let n = 0, a = r.length - 3; n <= a; n += 3) { nr.fromArray(r, n); const o = s.x * Math.abs(nr.x) + s.y * Math.abs(nr.y) + s.z * Math.abs(nr.z), l = e.dot(nr), c = t.dot(nr), h = i.dot(nr); if (Math.max(-Math.max(l, c, h), Math.min(l, c, h)) > o) return !1; } return !0; } const $u = /* @__PURE__ */ new Rt(), as = /* @__PURE__ */ new w(), Wn = /* @__PURE__ */ new w(); class Ci { /** * Constructs a new sphere. * * @param {Vector3} [center=(0,0,0)] - The center of the sphere * @param {number} [radius=-1] - The radius of the sphere. */ constructor(e = new w(), t = -1) { this.isSphere = !0, this.center = e, this.radius = t; } /** * Sets the sphere's components by copying the given values. * * @param {Vector3} center - The center. * @param {number} radius - The radius. * @return {Sphere} A reference to this sphere. */ set(e, t) { return this.center.copy(e), this.radius = t, this; } /** * Computes the minimum bounding sphere for list of points. * If the optional center point is given, it is used as the sphere's * center. Otherwise, the center of the axis-aligned bounding box * encompassing the points is calculated. * * @param {Array} points - A list of points in 3D space. * @param {Vector3} [optionalCenter] - The center of the sphere. * @return {Sphere} A reference to this sphere. */ setFromPoints(e, t) { const i = this.center; t !== void 0 ? i.copy(t) : $u.setFromPoints(e).getCenter(i); let s = 0; for (let n = 0, a = e.length; n < a; n++) s = Math.max(s, i.distanceToSquared(e[n])); 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(e) { return this.center.copy(e.center), this.radius = e.radius, this; } /** * Returns `true` if the sphere is empty (the radius set to a negative number). * * Spheres with a radius of `0` contain only their center point and are not * considered to be empty. * * @return {boolean} Whether this sphere is empty or not. */ isEmpty() { return this.radius < 0; } /** * Makes this sphere empty which means in encloses a zero space in 3D. * * @return {Sphere} A reference to this sphere. */ makeEmpty() { return this.center.set(0, 0, 0), this.radius = -1, this; } /** * Returns `true` if this sphere contains the given point inclusive of * the surface of the sphere. * * @param {Vector3} point - The point to check. * @return {boolean} Whether this sphere contains the given point or not. */ containsPoint(e) { return e.distanceToSquared(this.center) <= this.radius * this.radius; } /** * Returns the closest distance from the boundary of the sphere to the * given point. If the sphere contains the point, the distance will * be negative. * * @param {Vector3} point - The point to compute the distance to. * @return {number} The distance to the point. */ distanceToPoint(e) { return e.distanceTo(this.center) - this.radius; } /** * Returns `true` if this sphere intersects with the given one. * * @param {Sphere} sphere - The sphere to test. * @return {boolean} Whether this sphere intersects with the given one or not. */ intersectsSphere(e) { const t = this.radius + e.radius; return e.center.distanceToSquared(this.center) <= t * t; } /** * Returns `true` if this sphere intersects with the given box. * * @param {Box3} box - The box to test. * @return {boolean} Whether this sphere intersects with the given box or not. */ intersectsBox(e) { return e.intersectsSphere(this); } /** * Returns `true` if this sphere intersects with the given plane. * * @param {Plane} plane - The plane to test. * @return {boolean} Whether this sphere intersects with the given plane or not. */ intersectsPlane(e) { return Math.abs(e.distanceToPoint(this.center)) <= this.radius; } /** * Clamps a point within the sphere. If the point is outside the sphere, it * will clamp it to the closest point on the edge of the sphere. Points * already inside the sphere will not be affected. * * @param {Vector3} point - The plane to clamp. * @param {Vector3} target - The target vector that is used to store the method's result. * @return {Vector3} The clamped point. */ clampPoint(e, t) { const i = this.center.distanceToSquared(e); return t.copy(e), i > this.radius * this.radius && (t.sub(this.center).normalize(), t.multiplyScalar(this.radius).add(this.center)), t; } /** * Returns a bounding box that encloses this sphere. * * @param {Box3} target - The target box that is used to store the method's result. * @return {Box3} The bounding box that encloses this sphere. */ getBoundingBox(e) { return this.isEmpty() ? (e.makeEmpty(), e) : (e.set(this.center, this.center), e.expandByScalar(this.radius), e); } /** * Transforms this sphere with the given 4x4 transformation matrix. * * @param {Matrix4} matrix - The transformation matrix. * @return {Sphere} A reference to this sphere. */ applyMatrix4(e) { return this.center.applyMatrix4(e), this.radius = this.radius * e.getMaxScaleOnAxis(), this; } /** * Translates the sphere's center by the given offset. * * @param {Vector3} offset - The offset. * @return {Sphere} A reference to this sphere. */ translate(e) { return this.center.add(e), this; } /** * Expands the boundaries of this sphere to include the given point. * * @param {Vector3} point - The point to include. * @return {Sphere} A reference to this sphere. */ expandByPoint(e) { if (this.isEmpty()) return this.center.copy(e), this.radius = 0, this; as.subVectors(e, this.center); const t = as.lengthSq(); if (t > this.radius * this.radius) { const i = Math.sqrt(t), s = (i - this.radius) * 0.5; this.center.addScaledVector(as, s / i), 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(e) { return e.isEmpty() ? this : this.isEmpty() ? (this.copy(e), this) : (this.center.equals(e.center) === !0 ? this.radius = Math.max(this.radius, e.radius) : (Wn.subVectors(e.center, this.center).setLength(e.radius), this.expandByPoint(as.copy(e.center).add(Wn)), this.expandByPoint(as.copy(e.center).sub(Wn))), this); } /** * Returns `true` if this sphere is equal with the given one. * * @param {Sphere} sphere - The sphere to test for equality. * @return {boolean} Whether this bounding sphere is equal with the given one. */ equals(e) { return e.center.equals(this.center) && e.radius === this.radius; } /** * Returns a new sphere with copied values from this instance. * * @return {Sphere} A clone of this instance. */ clone() { return new this.constructor().copy(this); } /** * Returns a serialized structure of the bounding sphere. * * @return {Object} Serialized structure with fields representing the object state. */ toJSON() { return { radius: this.radius, center: this.center.toArray() }; } /** * Returns a serialized structure of the bounding sphere. * * @param {Object} json - The serialized json to set the sphere from. * @return {Box3} A reference to this bounding sphere. */ fromJSON(e) { return this.radius = e.radius, this.center.fromArray(e.center), this; } } const Di = /* @__PURE__ */ new w(), jn = /* @__PURE__ */ new w(), Bs = /* @__PURE__ */ new w(), Wi = /* @__PURE__ */ new w(), Xn = /* @__PURE__ */ new w(), Fs = /* @__PURE__ */ new w(), qn = /* @__PURE__ */ new w(); class Qr { /** * Constructs a new ray. * * @param {Vector3} [origin=(0,0,0)] - The origin of the ray. * @param {Vector3} [direction=(0,0,-1)] - The (normalized) direction of the ray. */ constructor(e = new w(), t = new w(0, 0, -1)) { this.origin = e, this.direction = t; } /** * Sets the ray's components by copying the given values. * * @param {Vector3} origin - The origin. * @param {Vector3} direction - The direction. * @return {Ray} A reference to this ray. */ set(e, t) { return this.origin.copy(e), this.direction.copy(t), this; } /** * Copies the values of the given ray to this instance. * * @param {Ray} ray - The ray to copy. * @return {Ray} A reference to this ray. */ copy(e) { return this.origin.copy(e.origin), this.direction.copy(e.direction), this; } /** * Returns a vector that is located at a given distance along this ray. * * @param {number} t - The distance along the ray to retrieve a position for. * @param {Vector3} target - The target vector that is used to store the method's result. * @return {Vector3} A position on the ray. */ at(e, t) { return t.copy(this.origin).addScaledVector(this.direction, e); } /** * Adjusts the direction of the ray to point at the given vector in world space. * * @param {Vector3} v - The target position. * @return {Ray} A reference to this ray. */ lookAt(e) { return this.direction.copy(e).sub(this.origin).normalize(), this; } /** * Shift the origin of this ray along its direction by the given distance. * * @param {number} t - The distance along the ray to interpolate. * @return {Ray} A reference to this ray. */ recast(e) { return this.origin.copy(this.at(e, Di)), this; } /** * Returns the point along this ray that is closest to the given point. * * @param {Vector3} point - A point in 3D space to get the closet location on the ray for. * @param {Vector3} target - The target vector that is used to store the method's result. * @return {Vector3} The closest point on this ray. */ closestPointToPoint(e, t) { t.subVectors(e, this.origin); const i = t.dot(this.direction); return i < 0 ? t.copy(this.origin) : t.copy(this.origin).addScaledVector(this.direction, i); } /** * Returns the distance of the closest approach between this ray and the given point. * * @param {Vector3} point - A point in 3D space to compute the distance to. * @return {number} The distance. */ distanceToPoint(e) { return Math.sqrt(this.distanceSqToPoint(e)); } /** * Returns the squared distance of the closest approach between this ray and the given point. * * @param {Vector3} point - A point in 3D space to compute the distance to. * @return {number} The squared distance. */ distanceSqToPoint(e) { const t = Di.subVectors(e, this.origin).dot(this.direction); return t < 0 ? this.origin.distanceToSquared(e) : (Di.copy(this.origin).addScaledVector(this.direction, t), Di.distanceToSquared(e)); } /** * Returns the squared distance between this ray and the given line segment. * * @param {Vector3} v0 - The start point of the line segment. * @param {Vector3} v1 - The end point of the line segment. * @param {Vector3} [optionalPointOnRay] - When provided, it receives the point on this ray that is closest to the segment. * @param {Vector3} [optionalPointOnSegment] - When provided, it receives the point on the line segment that is closest to this ray. * @return {number} The squared distance. */ distanceSqToSegment(e, t, i, s) { jn.copy(e).add(t).multiplyScalar(0.5), Bs.copy(t).sub(e).normalize(), Wi.copy(this.origin).sub(jn); const n = e.distanceTo(t) * 0.5, a = -this.direction.dot(Bs), o = Wi.dot(this.direction), l = -Wi.dot(Bs), c = Wi.lengthSq(), h = Math.abs(1 - a * a); let u, d, f, g; if (h > 0) if (u = a * l - o, d = a * o - l, g = n * h, u >= 0) if (d >= -g) if (d <= g) { const v = 1 / h; u *= v, d *= v, f = u * (u + a * d + 2 * o) + d * (a * u + d + 2 * l) + c; } else d = n, u = Math.max(0, -(a * d + o)), f = -u * u + d * (d + 2 * l) + c; else d = -n, u = Math.max(0, -(a * d + o)), f = -u * u + d * (d + 2 * l) + c; else d <= -g ? (u = Math.max(0, -(-a * n + o)), d = u > 0 ? -n : Math.min(Math.max(-n, -l), n), f = -u * u + d * (d + 2 * l) + c) : d <= g ? (u = 0, d = Math.min(Math.max(-n, -l), n), f = d * (d + 2 * l) + c) : (u = Math.max(0, -(a * n + o)), d = u > 0 ? n : Math.min(Math.max(-n, -l), n), f = -u * u + d * (d + 2 * l) + c); else d = a > 0 ? -n : n, u = Math.max(0, -(a * d + o)), f = -u * u + d * (d + 2 * l) + c; return i && i.copy(this.origin).addScaledVector(this.direction, u), s && s.copy(jn).addScaledVector(Bs, d), f; } /** * Intersects this ray with the given sphere, returning the intersection * point or `null` if there is no intersection. * * @param {Sphere} sphere - The sphere to intersect. * @param {Vector3} target - The target vector that is used to store the method's result. * @return {?Vector3} The intersection point. */ intersectSphere(e, t) { Di.subVectors(e.center, this.origin); const i = Di.dot(this.direction), s = Di.dot(Di) - i * i, n = e.radius * e.radius; if (s > n) return null; const a = Math.sqrt(n - s), o = i - a, l = i + a; return l < 0 ? null : o < 0 ? this.at(l, t) : this.at(o, t); } /** * Returns `true` if this ray intersects with the given sphere. * * @param {Sphere} sphere - The sphere to intersect. * @return {boolean} Whether this ray intersects with the given sphere or not. */ intersectsSphere(e) { return e.radius < 0 ? !1 : this.distanceSqToPoint(e.center) <= e.radius * e.radius; } /** * Computes the distance from the ray's origin to the given plane. Returns `null` if the ray * does not intersect with the plane. * * @param {Plane} plane - The plane to compute the distance to. * @return {?number} Whether this ray intersects with the given sphere or not. */ distanceToPlane(e) { const t = e.normal.dot(this.direction); if (t === 0) return e.distanceToPoint(this.origin) === 0 ? 0 : null; const i = -(this.origin.dot(e.normal) + e.constant) / t; return i >= 0 ? i : null; } /** * Intersects this ray with the given plane, returning the intersection * point or `null` if there is no intersection. * * @param {Plane} plane - The plane to intersect. * @param {Vector3} target - The target vector that is used to store the method's result. * @return {?Vector3} The intersection point. */ intersectPlane(e, t) { const i = this.distanceToPlane(e); return i === null ? null : this.at(i, t); } /** * Returns `true` if this ray intersects with the given plane. * * @param {Plane} plane - The plane to intersect. * @return {boolean} Whether this ray intersects with the given plane or not. */ intersectsPlane(e) { const t = e.distanceToPoint(this.origin); return t === 0 || e.normal.dot(this.direction) * t < 0; } /** * Intersects this ray with the given bounding box, returning the intersection * point or `null` if there is no intersection. * * @param {Box3} box - The box to intersect. * @param {Vector3} target - The target vector that is used to store the method's result. * @return {?Vector3} The intersection point. */ intersectBox(e, t) { let i, s, n, a, o, l; const c = 1 / this.direction.x, h = 1 / this.direction.y, u = 1 / this.direction.z, d = this.origin; return c >= 0 ? (i = (e.min.x - d.x) * c, s = (e.max.x - d.x) * c) : (i = (e.max.x - d.x) * c, s = (e.min.x - d.x) * c), h >= 0 ? (n = (e.min.y - d.y) * h, a = (e.max.y - d.y) * h) : (n = (e.max.y - d.y) * h, a = (e.min.y - d.y) * h), i > a || n > s || ((n > i || isNaN(i)) && (i = n), (a < s || isNaN(s)) && (s = a), u >= 0 ? (o = (e.min.z - d.z) * u, l = (e.max.z - d.z) * u) : (o = (e.max.z - d.z) * u, l = (e.min.z - d.z) * u), i > l || o > s) || ((o > i || i !== i) && (i = o), (l < s || s !== s) && (s = l), s < 0) ? null : this.at(i >= 0 ? i : s, t); } /** * Returns `true` if this ray intersects with the given box. * * @param {Box3} box - The box to intersect. * @return {boolean} Whether this ray intersects with the given box or not. */ intersectsBox(e) { return this.intersectBox(e, Di) !== null; } /** * Intersects this ray with the given triangle, returning the intersection * point or `null` if there is no intersection. * * @param {Vector3} a - The first vertex of the triangle. * @param {Vector3} b - The second vertex of the triangle. * @param {Vector3} c - The third vertex of the triangle. * @param {boolean} backfaceCulling - Whether to use backface culling or not. * @param {Vector3} target - The target vector that is used to store the method's result. * @return {?Vector3} The intersection point. */ intersectTriangle(e, t, i, s, n) { Xn.subVectors(t, e), Fs.subVectors(i, e), qn.crossVectors(Xn, Fs); let a = this.direction.dot(qn), o; if (a > 0) { if (s) return null; o = 1; } else if (a < 0) o = -1, a = -a; else return null; Wi.subVectors(this.origin, e); const l = o * this.direction.dot(Fs.crossVectors(Wi, Fs)); if (l < 0) return null; const c = o * this.direction.dot(Xn.cross(Wi)); if (c < 0 || l + c > a) return null; const h = -o * Wi.dot(qn); return h < 0 ? null : this.at(h / a, n); } /** * Transforms this ray with the given 4x4 transformation matrix. * * @param {Matrix4} matrix4 - The transformation matrix. * @return {Ray} A reference to this ray. */ applyMatrix4(e) { return this.origin.applyMatrix4(e), this.direction.transformDirection(e), this; } /** * Returns `true` if this ray is equal with the given one. * * @param {Ray} ray - The ray to test for equality. * @return {boolean} Whether this ray is equal with the given one. */ equals(e) { return e.origin.equals(this.origin) && e.direction.equals(this.direction); } /** * Returns a new ray with copied values from this instance. * * @return {Ray} A clone of this instance. */ clone() { return new this.constructor().copy(this); } } class Ue { /** * Constructs a new 4x4 matrix. The arguments are supposed to be * in row-major order. If no arguments are provided, the constructor * initializes the matrix as an identity matrix. * * @param {number} [n11] - 1-1 matrix element. * @param {number} [n12] - 1-2 matrix element. * @param {number} [n13] - 1-3 matrix element. * @param {number} [n14] - 1-4 matrix element. * @param {number} [n21] - 2-1 matrix element. * @param {number} [n22] - 2-2 matrix element. * @param {number} [n23] - 2-3 matrix element. * @param {number} [n24] - 2-4 matrix element. * @param {number} [n31] - 3-1 matrix element. * @param {number} [n32] - 3-2 matrix element. * @param {number} [n33] - 3-3 matrix element. * @param {number} [n34] - 3-4 matrix element. * @param {number} [n41] - 4-1 matrix element. * @param {number} [n42] - 4-2 matrix element. * @param {number} [n43] - 4-3 matrix element. * @param {number} [n44] - 4-4 matrix element. */ constructor(e, t, i, s, n, a, o, l, c, h, u, d, f, g, v, m) { Ue.prototype.isMatrix4 = !0, this.elements = [ 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1 ], e !== void 0 && this.set(e, t, i, s, n, a, o, l, c, h, u, d, f, g, v, m); } /** * Sets the elements of the matrix.The arguments are supposed to be * in row-major order. * * @param {number} [n11] - 1-1 matrix element. * @param {number} [n12] - 1-2 matrix element. * @param {number} [n13] - 1-3 matrix element. * @param {number} [n14] - 1-4 matrix element. * @param {number} [n21] - 2-1 matrix element. * @param {number} [n22] - 2-2 matrix element. * @param {number} [n23] - 2-3 matrix element. * @param {number} [n24] - 2-4 matrix element. * @param {number} [n31] - 3-1 matrix element. * @param {number} [n32] - 3-2 matrix element. * @param {number} [n33] - 3-3 matrix element. * @param {number} [n34] - 3-4 matrix element. * @param {number} [n41] - 4-1 matrix element. * @param {number} [n42] - 4-2 matrix element. * @param {number} [n43] - 4-3 matrix element. * @param {number} [n44] - 4-4 matrix element. * @return {Matrix4} A reference to this matrix. */ set(e, t, i, s, n, a, o, l, c, h, u, d, f, g, v, m) { const p = this.elements; return p[0] = e, p[4] = t, p[8] = i, p[12] = s, p[1] = n, p[5] = a, p[9] = o, p[13] = l, p[2] = c, p[6] = h, p[10] = u, p[14] = d, p[3] = f, p[7] = g, p[11] = v, p[15] = m, 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 Ue().fromArray(this.elements); } /** * Copies the values of the given matrix to this instance. * * @param {Matrix4} m - The matrix to copy. * @return {Matrix4} A reference to this matrix. */ copy(e) { const t = this.elements, i = e.elements; return t[0] = i[0], t[1] = i[1], t[2] = i[2], t[3] = i[3], t[4] = i[4], t[5] = i[5], t[6] = i[6], t[7] = i[7], t[8] = i[8], t[9] = i[9], t[10] = i[10], t[11] = i[11], t[12] = i[12], t[13] = i[13], t[14] = i[14], t[15] = i[15], this; } /** * Copies the translation component of the given matrix * into this matrix's translation component. * * @param {Matrix4} m - The matrix to copy the translation component. * @return {Matrix4} A reference to this matrix. */ copyPosition(e) { const t = this.elements, i = e.elements; return t[12] = i[12], t[13] = i[13], t[14] = i[14], this; } /** * Set the upper 3x3 elements of this matrix to the values of given 3x3 matrix. * * @param {Matrix3} m - The 3x3 matrix. * @return {Matrix4} A reference to this matrix. */ setFromMatrix3(e) { const t = e.elements; return this.set( t[0], t[3], t[6], 0, t[1], t[4], t[7], 0, t[2], t[5], t[8], 0, 0, 0, 0, 1 ), this; } /** * Extracts the basis of this matrix into the three axis vectors provided. * * @param {Vector3} xAxis - The basis's x axis. * @param {Vector3} yAxis - The basis's y axis. * @param {Vector3} zAxis - The basis's z axis. * @return {Matrix4} A reference to this matrix. */ extractBasis(e, t, i) { return e.setFromMatrixColumn(this, 0), t.setFromMatrixColumn(this, 1), i.setFromMatrixColumn(this, 2), this; } /** * Sets the given basis vectors to this matrix. * * @param {Vector3} xAxis - The basis's x axis. * @param {Vector3} yAxis - The basis's y axis. * @param {Vector3} zAxis - The basis's z axis. * @return {Matrix4} A reference to this matrix. */ makeBasis(e, t, i) { return this.set( e.x, t.x, i.x, 0, e.y, t.y, i.y, 0, e.z, t.z, i.z, 0, 0, 0, 0, 1 ), this; } /** * Extracts the rotation component of the given matrix * into this matrix's rotation component. * * Note: This method does not support reflection matrices. * * @param {Matrix4} m - The matrix. * @return {Matrix4} A reference to this matrix. */ extractRotation(e) { const t = this.elements, i = e.elements, s = 1 / br.setFromMatrixColumn(e, 0).length(), n = 1 / br.setFromMatrixColumn(e, 1).length(), a = 1 / br.setFromMatrixColumn(e, 2).length(); return t[0] = i[0] * s, t[1] = i[1] * s, t[2] = i[2] * s, t[3] = 0, t[4] = i[4] * n, t[5] = i[5] * n, t[6] = i[6] * n, t[7] = 0, t[8] = i[8] * a, t[9] = i[9] * a, t[10] = i[10] * a, t[11] = 0, t[12] = 0, t[13] = 0, t[14] = 0, t[15] = 1, this; } /** * Sets the rotation component (the upper left 3x3 matrix) of this matrix to * the rotation specified by the given Euler angles. The rest of * the matrix is set to the identity. Depending on the {@link Euler#order}, * there are six possible outcomes. See [this page](https://en.wikipedia.org/wiki/Euler_angles#Rotation_matrix) * for a complete list. * * @param {Euler} euler - The Euler angles. * @return {Matrix4} A reference to this matrix. */ makeRotationFromEuler(e) { const t = this.elements, i = e.x, s = e.y, n = e.z, a = Math.cos(i), o = Math.sin(i), l = Math.cos(s), c = Math.sin(s), h = Math.cos(n), u = Math.sin(n); if (e.order === "XYZ") { const d = a * h, f = a * u, g = o * h, v = o * u; t[0] = l * h, t[4] = -l * u, t[8] = c, t[1] = f + g * c, t[5] = d - v * c, t[9] = -o * l, t[2] = v - d * c, t[6] = g + f * c, t[10] = a * l; } else if (e.order === "YXZ") { const d = l * h, f = l * u, g = c * h, v = c * u; t[0] = d + v * o, t[4] = g * o - f, t[8] = a * c, t[1] = a * u, t[5] = a * h, t[9] = -o, t[2] = f * o - g, t[6] = v + d * o, t[10] = a * l; } else if (e.order === "ZXY") { const d = l * h, f = l * u, g = c * h, v = c * u; t[0] = d - v * o, t[4] = -a * u, t[8] = g + f * o, t[1] = f + g * o, t[5] = a * h, t[9] = v - d * o, t[2] = -a * c, t[6] = o, t[10] = a * l; } else if (e.order === "ZYX") { const d = a * h, f = a * u, g = o * h, v = o * u; t[0] = l * h, t[4] = g * c - f, t[8] = d * c + v, t[1] = l * u, t[5] = v * c + d, t[9] = f * c - g, t[2] = -c, t[6] = o * l, t[10] = a * l; } else if (e.order === "YZX") { const d = a * l, f = a * c, g = o * l, v = o * c; t[0] = l * h, t[4] = v - d * u, t[8] = g * u + f, t[1] = u, t[5] = a * h, t[9] = -o * h, t[2] = -c * h, t[6] = f * u + g, t[10] = d - v * u; } else if (e.order === "XZY") { const d = a * l, f = a * c, g = o * l, v = o * c; t[0] = l * h, t[4] = -u, t[8] = c * h, t[1] = d * u + v, t[5] = a * h, t[9] = f * u - g, t[2] = g * u - f, t[6] = o * h, t[10] = v * u + d; } return t[3] = 0, t[7] = 0, t[11] = 0, t[12] = 0, t[13] = 0, t[14] = 0, t[15] = 1, this; } /** * Sets the rotation component of this matrix to the rotation specified by * the given Quaternion as outlined [here](https://en.wikipedia.org/wiki/Rotation_matrix#Quaternion) * The rest of the matrix is set to the identity. * * @param {Quaternion} q - The Quaternion. * @return {Matrix4} A reference to this matrix. */ makeRotationFromQuaternion(e) { return this.compose(Qu, e, ed); } /** * Sets the rotation component of the transformation matrix, looking from `eye` towards * `target`, and oriented by the up-direction. * * @param {Vector3} eye - The eye vector. * @param {Vector3} target - The target vector. * @param {Vector3} up - The up vector. * @return {Matrix4} A reference to this matrix. */ lookAt(e, t, i) { const s = this.elements; return jt.subVectors(e, t), jt.lengthSq() === 0 && (jt.z = 1), jt.normalize(), ji.crossVectors(i, jt), ji.lengthSq() === 0 && (Math.abs(i.z) === 1 ? jt.x += 1e-4 : jt.z += 1e-4, jt.normalize(), ji.crossVectors(i, jt)), ji.normalize(), zs.crossVectors(jt, ji), s[0] = ji.x, s[4] = zs.x, s[8] = jt.x, s[1] = ji.y, s[5] = zs.y, s[9] = jt.y, s[2] = ji.z, s[6] = zs.z, s[10] = jt.z, this; } /** * Post-multiplies this matrix by the given 4x4 matrix. * * @param {Matrix4} m - The matrix to multiply with. * @return {Matrix4} A reference to this matrix. */ multiply(e) { return this.multiplyMatrices(this, e); } /** * Pre-multiplies this matrix by the given 4x4 matrix. * * @param {Matrix4} m - The matrix to multiply with. * @return {Matrix4} A reference to this matrix. */ premultiply(e) { return this.multiplyMatrices(e, this); } /** * Multiples the given 4x4 matrices and stores the result * in this matrix. * * @param {Matrix4} a - The first matrix. * @param {Matrix4} b - The second matrix. * @return {Matrix4} A reference to this matrix. */ multiplyMatrices(e, t) { const i = e.elements, s = t.elements, n = this.elements, a = i[0], o = i[4], l = i[8], c = i[12], h = i[1], u = i[5], d = i[9], f = i[13], g = i[2], v = i[6], m = i[10], p = i[14], y = i[3], _ = i[7], E = i[11], A = i[15], T = s[0], R = s[4], I = s[8], b = s[12], S = s[1], D = s[5], N = s[9], k = s[13], H = s[2], j = s[6], q = s[10], te = s[14], G = s[3], Z = s[7], se = s[11], Pe = s[15]; return n[0] = a * T + o * S + l * H + c * G, n[4] = a * R + o * D + l * j + c * Z, n[8] = a * I + o * N + l * q + c * se, n[12] = a * b + o * k + l * te + c * Pe, n[1] = h * T + u * S + d * H + f * G, n[5] = h * R + u * D + d * j + f * Z, n[9] = h * I + u * N + d * q + f * se, n[13] = h * b + u * k + d * te + f * Pe, n[2] = g * T + v * S + m * H + p * G, n[6] = g * R + v * D + m * j + p * Z, n[10] = g * I + v * N + m * q + p * se, n[14] = g * b + v * k + m * te + p * Pe, n[3] = y * T + _ * S + E * H + A * G, n[7] = y * R + _ * D + E * j + A * Z, n[11] = y * I + _ * N + E * q + A * se, n[15] = y * b + _ * k + E * te + A * Pe, this; } /** * Multiplies every component of the matrix by the given scalar. * * @param {number} s - The scalar. * @return {Matrix4} A reference to this matrix. */ multiplyScalar(e) { const t = this.elements; return t[0] *= e, t[4] *= e, t[8] *= e, t[12] *= e, t[1] *= e, t[5] *= e, t[9] *= e, t[13] *= e, t[2] *= e, t[6] *= e, t[10] *= e, t[14] *= e, t[3] *= e, t[7] *= e, t[11] *= e, t[15] *= e, this; } /** * Computes and returns the determinant of this matrix. * * Based on the method outlined [here](http://www.euclideanspace.com/maths/algebra/matrix/functions/inverse/fourD/index.html). * * @return {number} The determinant. */ determinant() { const e = this.elements, t = e[0], i = e[4], s = e[8], n = e[12], a = e[1], o = e[5], l = e[9], c = e[13], h = e[2], u = e[6], d = e[10], f = e[14], g = e[3], v = e[7], m = e[11], p = e[15]; return g * (+n * l * u - s * c * u - n * o * d + i * c * d + s * o * f - i * l * f) + v * (+t * l * f - t * c * d + n * a * d - s * a * f + s * c * h - n * l * h) + m * (+t * c * u - t * o * f - n * a * u + i * a * f + n * o * h - i * c * h) + p * (-s * o * h - t * l * u + t * o * d + s * a * u - i * a * d + i * l * h); } /** * Transposes this matrix in place. * * @return {Matrix4} A reference to this matrix. */ transpose() { const e = this.elements; let t; return t = e[1], e[1] = e[4], e[4] = t, t = e[2], e[2] = e[8], e[8] = t, t = e[6], e[6] = e[9], e[9] = t, t = e[3], e[3] = e[12], e[12] = t, t = e[7], e[7] = e[13], e[13] = t, t = e[11], e[11] = e[14], e[14] = t, this; } /** * Sets the position component for this matrix from the given vector, * without affecting the rest of the matrix. * * @param {number|Vector3} x - The x component of the vector or alternatively the vector object. * @param {number} y - The y component of the vector. * @param {number} z - The z component of the vector. * @return {Matrix4} A reference to this matrix. */ setPosition(e, t, i) { const s = this.elements; return e.isVector3 ? (s[12] = e.x, s[13] = e.y, s[14] = e.z) : (s[12] = e, s[13] = t, s[14] = i), this; } /** * Inverts this matrix, using the [analytic method](https://en.wikipedia.org/wiki/Invertible_matrix#Analytic_solution). * You can not invert with a determinant of zero. If you attempt this, the method produces * a zero matrix instead. * * @return {Matrix4} A reference to this matrix. */ invert() { const e = this.elements, t = e[0], i = e[1], s = e[2], n = e[3], a = e[4], o = e[5], l = e[6], c = e[7], h = e[8], u = e[9], d = e[10], f = e[11], g = e[12], v = e[13], m = e[14], p = e[15], y = u * m * c - v * d * c + v * l * f - o * m * f - u * l * p + o * d * p, _ = g * d * c - h * m * c - g * l * f + a * m * f + h * l * p - a * d * p, E = h * v * c - g * u * c + g * o * f - a * v * f - h * o * p + a * u * p, A = g * u * l - h * v * l - g * o * d + a * v * d + h * o * m - a * u * m, T = t * y + i * _ + s * E + n * A; if (T === 0) return this.set(0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0); const R = 1 / T; return e[0] = y * R, e[1] = (v * d * n - u * m * n - v * s * f + i * m * f + u * s * p - i * d * p) * R, e[2] = (o * m * n - v * l * n + v * s * c - i * m * c - o * s * p + i * l * p) * R, e[3] = (u * l * n - o * d * n - u * s * c + i * d * c + o * s * f - i * l * f) * R, e[4] = _ * R, e[5] = (h * m * n - g * d * n + g * s * f - t * m * f - h * s * p + t * d * p) * R, e[6] = (g * l * n - a * m * n - g * s * c + t * m * c + a * s * p - t * l * p) * R, e[7] = (a * d * n - h * l * n + h * s * c - t * d * c - a * s * f + t * l * f) * R, e[8] = E * R, e[9] = (g * u * n - h * v * n - g * i * f + t * v * f + h * i * p - t * u * p) * R, e[10] = (a * v * n - g * o * n + g * i * c - t * v * c - a * i * p + t * o * p) * R, e[11] = (h * o * n - a * u * n - h * i * c + t * u * c + a * i * f - t * o * f) * R, e[12] = A * R, e[13] = (h * v * s - g * u * s + g * i * d - t * v * d - h * i * m + t * u * m) * R, e[14] = (g * o * s - a * v * s - g * i * l + t * v * l + a * i * m - t * o * m) * R, e[15] = (a * u * s - h * o * s + h * i * l - t * u * l - a * i * d + t * o * d) * R, this; } /** * Multiplies the columns of this matrix by the given vector. * * @param {Vector3} v - The scale vector. * @return {Matrix4} A reference to this matrix. */ scale(e) { const t = this.elements, i = e.x, s = e.y, n = e.z; return t[0] *= i, t[4] *= s, t[8] *= n, t[1] *= i, t[5] *= s, t[9] *= n, t[2] *= i, t[6] *= s, t[10] *= n, t[3] *= i, t[7] *= s, t[11] *= n, this; } /** * Gets the maximum scale value of the three axes. * * @return {number} The maximum scale. */ getMaxScaleOnAxis() { const e = this.elements, t = e[0] * e[0] + e[1] * e[1] + e[2] * e[2], i = e[4] * e[4] + e[5] * e[5] + e[6] * e[6], s = e[8] * e[8] + e[9] * e[9] + e[10] * e[10]; return Math.sqrt(Math.max(t, i, 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(e, t, i) { return e.isVector3 ? this.set( 1, 0, 0, e.x, 0, 1, 0, e.y, 0, 0, 1, e.z, 0, 0, 0, 1 ) : this.set( 1, 0, 0, e, 0, 1, 0, t, 0, 0, 1, i, 0, 0, 0, 1 ), this; } /** * Sets this matrix as a rotational transformation around the X axis by * the given angle. * * @param {number} theta - The rotation in radians. * @return {Matrix4} A reference to this matrix. */ makeRotationX(e) { const t = Math.cos(e), i = Math.sin(e); return this.set( 1, 0, 0, 0, 0, t, -i, 0, 0, i, t, 0, 0, 0, 0, 1 ), this; } /** * Sets this matrix as a rotational transformation around the Y axis by * the given angle. * * @param {number} theta - The rotation in radians. * @return {Matrix4} A reference to this matrix. */ makeRotationY(e) { const t = Math.cos(e), i = Math.sin(e); return this.set( t, 0, i, 0, 0, 1, 0, 0, -i, 0, t, 0, 0, 0, 0, 1 ), this; } /** * Sets this matrix as a rotational transformation around the Z axis by * the given angle. * * @param {number} theta - The rotation in radians. * @return {Matrix4} A reference to this matrix. */ makeRotationZ(e) { const t = Math.cos(e), i = Math.sin(e); return this.set( t, -i, 0, 0, i, t, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1 ), this; } /** * Sets this matrix as a rotational transformation around the given axis by * the given angle. * * This is a somewhat controversial but mathematically sound alternative to * rotating via Quaternions. See the discussion [here](https://www.gamedev.net/articles/programming/math-and-physics/do-we-really-need-quaternions-r1199). * * @param {Vector3} axis - The normalized rotation axis. * @param {number} angle - The rotation in radians. * @return {Matrix4} A reference to this matrix. */ makeRotationAxis(e, t) { const i = Math.cos(t), s = Math.sin(t), n = 1 - i, a = e.x, o = e.y, l = e.z, c = n * a, h = n * o; return this.set( c * a + i, c * o - s * l, c * l + s * o, 0, c * o + s * l, h * o + i, h * l - s * a, 0, c * l - s * o, h * l + s * a, n * l * l + i, 0, 0, 0, 0, 1 ), this; } /** * Sets this matrix as a scale transformation. * * @param {number} x - The amount to scale in the X axis. * @param {number} y - The amount to scale in the Y axis. * @param {number} z - The amount to scale in the Z axis. * @return {Matrix4} A reference to this matrix. */ makeScale(e, t, i) { return this.set( e, 0, 0, 0, 0, t, 0, 0, 0, 0, i, 0, 0, 0, 0, 1 ), this; } /** * Sets this matrix as a shear transformation. * * @param {number} xy - The amount to shear X by Y. * @param {number} xz - The amount to shear X by Z. * @param {number} yx - The amount to shear Y by X. * @param {number} yz - The amount to shear Y by Z. * @param {number} zx - The amount to shear Z by X. * @param {number} zy - The amount to shear Z by Y. * @return {Matrix4} A reference to this matrix. */ makeShear(e, t, i, s, n, a) { return this.set( 1, i, n, 0, e, 1, a, 0, t, 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(e, t, i) { const s = this.elements, n = t._x, a = t._y, o = t._z, l = t._w, c = n + n, h = a + a, u = o + o, d = n * c, f = n * h, g = n * u, v = a * h, m = a * u, p = o * u, y = l * c, _ = l * h, E = l * u, A = i.x, T = i.y, R = i.z; return s[0] = (1 - (v + p)) * A, s[1] = (f + E) * A, s[2] = (g - _) * A, s[3] = 0, s[4] = (f - E) * T, s[5] = (1 - (d + p)) * T, s[6] = (m + y) * T, s[7] = 0, s[8] = (g + _) * R, s[9] = (m - y) * R, s[10] = (1 - (d + v)) * R, s[11] = 0, s[12] = e.x, s[13] = e.y, s[14] = e.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(e, t, i) { const s = this.elements; let n = br.set(s[0], s[1], s[2]).length(); const a = br.set(s[4], s[5], s[6]).length(), o = br.set(s[8], s[9], s[10]).length(); this.determinant() < 0 && (n = -n), e.x = s[12], e.y = s[13], e.z = s[14], si.copy(this); const l = 1 / n, c = 1 / a, h = 1 / o; return si.elements[0] *= l, si.elements[1] *= l, si.elements[2] *= l, si.elements[4] *= c, si.elements[5] *= c, si.elements[6] *= c, si.elements[8] *= h, si.elements[9] *= h, si.elements[10] *= h, t.setFromRotationMatrix(si), i.x = n, i.y = a, i.z = o, this; } /** * Creates a perspective projection matrix. This is used internally by * {@link PerspectiveCamera#updateProjectionMatrix}. * @param {number} left - Left boundary of the viewing frustum at the near plane. * @param {number} right - Right boundary of the viewing frustum at the near plane. * @param {number} top - Top boundary of the viewing frustum at the near plane. * @param {number} bottom - Bottom boundary of the viewing frustum at the near plane. * @param {number} near - The distance from the camera to the near plane. * @param {number} far - The distance from the camera to the far plane. * @param {(WebGLCoordinateSystem|WebGPUCoordinateSystem)} [coordinateSystem=WebGLCoordinateSystem] - The coordinate system. * @param {boolean} [reversedDepth=false] - Whether to use a reversed depth. * @return {Matrix4} A reference to this matrix. */ makePerspective(e, t, i, s, n, a, o = bi, l = !1) { const c = this.elements, h = 2 * n / (t - e), u = 2 * n / (i - s), d = (t + e) / (t - e), f = (i + s) / (i - s); let g, v; if (l) g = n / (a - n), v = a * n / (a - n); else if (o === bi) g = -(a + n) / (a - n), v = -2 * a * n / (a - n); else if (o === Tn) g = -a / (a - n), v = -a * n / (a - n); else throw new Error("THREE.Matrix4.makePerspective(): Invalid coordinate system: " + o); return c[0] = h, c[4] = 0, c[8] = d, c[12] = 0, c[1] = 0, c[5] = u, c[9] = f, c[13] = 0, c[2] = 0, c[6] = 0, c[10] = g, c[14] = v, c[3] = 0, c[7] = 0, c[11] = -1, c[15] = 0, this; } /** * Creates a orthographic projection matrix. This is used internally by * {@link OrthographicCamera#updateProjectionMatrix}. * @param {number} left - Left boundary of the viewing frustum at the near plane. * @param {number} right - Right boundary of the viewing frustum at the near plane. * @param {number} top - Top boundary of the viewing frustum at the near plane. * @param {number} bottom - Bottom boundary of the viewing frustum at the near plane. * @param {number} near - The distance from the camera to the near plane. * @param {number} far - The distance from the camera to the far plane. * @param {(WebGLCoordinateSystem|WebGPUCoordinateSystem)} [coordinateSystem=WebGLCoordinateSystem] - The coordinate system. * @param {boolean} [reversedDepth=false] - Whether to use a reversed depth. * @return {Matrix4} A reference to this matrix. */ makeOrthographic(e, t, i, s, n, a, o = bi, l = !1) { const c = this.elements, h = 2 / (t - e), u = 2 / (i - s), d = -(t + e) / (t - e), f = -(i + s) / (i - s); let g, v; if (l) g = 1 / (a - n), v = a / (a - n); else if (o === bi) g = -2 / (a - n), v = -(a + n) / (a - n); else if (o === Tn) g = -1 / (a - n), v = -n / (a - n); else throw new Error("THREE.Matrix4.makeOrthographic(): Invalid coordinate system: " + o); return c[0] = h, c[4] = 0, c[8] = 0, c[12] = d, c[1] = 0, c[5] = u, c[9] = 0, c[13] = f, c[2] = 0, c[6] = 0, c[10] = g, c[14] = v, c[3] = 0, c[7] = 0, c[11] = 0, c[15] = 1, this; } /** * Returns `true` if this matrix is equal with the given one. * * @param {Matrix4} matrix - The matrix to test for equality. * @return {boolean} Whether this matrix is equal with the given one. */ equals(e) { const t = this.elements, i = e.elements; for (let s = 0; s < 16; s++) if (t[s] !== i[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(e, t = 0) { for (let i = 0; i < 16; i++) this.elements[i] = e[i + t]; return this; } /** * Writes the elements of this matrix to the given array. If no array is provided, * the method returns a new instance. * * @param {Array} [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(e = [], t = 0) { const i = this.elements; return e[t] = i[0], e[t + 1] = i[1], e[t + 2] = i[2], e[t + 3] = i[3], e[t + 4] = i[4], e[t + 5] = i[5], e[t + 6] = i[6], e[t + 7] = i[7], e[t + 8] = i[8], e[t + 9] = i[9], e[t + 10] = i[10], e[t + 11] = i[11], e[t + 12] = i[12], e[t + 13] = i[13], e[t + 14] = i[14], e[t + 15] = i[15], e; } } const br = /* @__PURE__ */ new w(), si = /* @__PURE__ */ new Ue(), Qu = /* @__PURE__ */ new w(0, 0, 0), ed = /* @__PURE__ */ new w(1, 1, 1), ji = /* @__PURE__ */ new w(), zs = /* @__PURE__ */ new w(), jt = /* @__PURE__ */ new w(), _l = /* @__PURE__ */ new Ue(), xl = /* @__PURE__ */ new mi(); class gi { /** * Constructs a new euler instance. * * @param {number} [x=0] - The angle of the x axis in radians. * @param {number} [y=0] - The angle of the y axis in radians. * @param {number} [z=0] - The angle of the z axis in radians. * @param {string} [order=Euler.DEFAULT_ORDER] - A string representing the order that the rotations are applied. */ constructor(e = 0, t = 0, i = 0, s = gi.DEFAULT_ORDER) { this.isEuler = !0, this._x = e, this._y = t, this._z = i, this._order = s; } /** * The angle of the x axis in radians. * * @type {number} * @default 0 */ get x() { return this._x; } set x(e) { this._x = e, this._onChangeCallback(); } /** * The angle of the y axis in radians. * * @type {number} * @default 0 */ get y() { return this._y; } set y(e) { this._y = e, this._onChangeCallback(); } /** * The angle of the z axis in radians. * * @type {number} * @default 0 */ get z() { return this._z; } set z(e) { this._z = e, this._onChangeCallback(); } /** * A string representing the order that the rotations are applied. * * @type {string} * @default 'XYZ' */ get order() { return this._order; } set order(e) { this._order = e, this._onChangeCallback(); } /** * Sets the Euler components. * * @param {number} x - The angle of the x axis in radians. * @param {number} y - The angle of the y axis in radians. * @param {number} z - The angle of the z axis in radians. * @param {string} [order] - A string representing the order that the rotations are applied. * @return {Euler} A reference to this Euler instance. */ set(e, t, i, s = this._order) { return this._x = e, this._y = t, this._z = i, 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(e) { return this._x = e._x, this._y = e._y, this._z = e._z, this._order = e._order, this._onChangeCallback(), this; } /** * Sets the angles of this Euler instance from a pure rotation matrix. * * @param {Matrix4} m - A 4x4 matrix of which the upper 3x3 of matrix is a pure rotation matrix (i.e. unscaled). * @param {string} [order] - A string representing the order that the rotations are applied. * @param {boolean} [update=true] - Whether the internal `onChange` callback should be executed or not. * @return {Euler} A reference to this Euler instance. */ setFromRotationMatrix(e, t = this._order, i = !0) { const s = e.elements, n = s[0], a = s[4], o = s[8], l = s[1], c = s[5], h = s[9], u = s[2], d = s[6], f = s[10]; switch (t) { case "XYZ": this._y = Math.asin(ze(o, -1, 1)), Math.abs(o) < 0.9999999 ? (this._x = Math.atan2(-h, f), this._z = Math.atan2(-a, n)) : (this._x = Math.atan2(d, c), this._z = 0); break; case "YXZ": this._x = Math.asin(-ze(h, -1, 1)), Math.abs(h) < 0.9999999 ? (this._y = Math.atan2(o, f), this._z = Math.atan2(l, c)) : (this._y = Math.atan2(-u, n), this._z = 0); break; case "ZXY": this._x = Math.asin(ze(d, -1, 1)), Math.abs(d) < 0.9999999 ? (this._y = Math.atan2(-u, f), this._z = Math.atan2(-a, c)) : (this._y = 0, this._z = Math.atan2(l, n)); break; case "ZYX": this._y = Math.asin(-ze(u, -1, 1)), Math.abs(u) < 0.9999999 ? (this._x = Math.atan2(d, f), this._z = Math.atan2(l, n)) : (this._x = 0, this._z = Math.atan2(-a, c)); break; case "YZX": this._z = Math.asin(ze(l, -1, 1)), Math.abs(l) < 0.9999999 ? (this._x = Math.atan2(-h, c), this._y = Math.atan2(-u, n)) : (this._x = 0, this._y = Math.atan2(o, f)); break; case "XZY": this._z = Math.asin(-ze(a, -1, 1)), Math.abs(a) < 0.9999999 ? (this._x = Math.atan2(d, c), this._y = Math.atan2(o, n)) : (this._x = Math.atan2(-h, f), this._y = 0); break; default: Se("Euler: .setFromRotationMatrix() encountered an unknown order: " + t); } return this._order = t, i === !0 && this._onChangeCallback(), this; } /** * Sets the angles of this Euler instance from a normalized quaternion. * * @param {Quaternion} q - A normalized Quaternion. * @param {string} [order] - A string representing the order that the rotations are applied. * @param {boolean} [update=true] - Whether the internal `onChange` callback should be executed or not. * @return {Euler} A reference to this Euler instance. */ setFromQuaternion(e, t, i) { return _l.makeRotationFromQuaternion(e), this.setFromRotationMatrix(_l, t, i); } /** * Sets the angles of this Euler instance from the given vector. * * @param {Vector3} v - The vector. * @param {string} [order] - A string representing the order that the rotations are applied. * @return {Euler} A reference to this Euler instance. */ setFromVector3(e, t = this._order) { return this.set(e.x, e.y, e.z, t); } /** * Resets the euler angle with a new order by creating a quaternion from this * euler angle and then setting this euler angle with the quaternion and the * new order. * * Warning: This discards revolution information. * * @param {string} [newOrder] - A string representing the new order that the rotations are applied. * @return {Euler} A reference to this Euler instance. */ reorder(e) { return xl.setFromEuler(this), this.setFromQuaternion(xl, e); } /** * Returns `true` if this Euler instance is equal with the given one. * * @param {Euler} euler - The Euler instance to test for equality. * @return {boolean} Whether this Euler instance is equal with the given one. */ equals(e) { return e._x === this._x && e._y === this._y && e._z === this._z && e._order === this._order; } /** * Sets this Euler instance's components to values from the given array. The first three * entries of the array are assign to the x,y and z components. An optional fourth entry * defines the Euler order. * * @param {Array} array - An array holding the Euler component values. * @return {Euler} A reference to this Euler instance. */ fromArray(e) { return this._x = e[0], this._y = e[1], this._z = e[2], e[3] !== void 0 && (this._order = e[3]), this._onChangeCallback(), this; } /** * Writes the components of this Euler instance to the given array. If no array is provided, * the method returns a new instance. * * @param {Array} [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(e = [], t = 0) { return e[t] = this._x, e[t + 1] = this._y, e[t + 2] = this._z, e[t + 3] = this._order, e; } _onChange(e) { return this._onChangeCallback = e, this; } _onChangeCallback() { } *[Symbol.iterator]() { yield this._x, yield this._y, yield this._z, yield this._order; } } gi.DEFAULT_ORDER = "XYZ"; class Bo { /** * Constructs a new layers instance, with membership * initially set to layer `0`. */ constructor() { this.mask = 1; } /** * Sets membership to the given layer, and remove membership all other layers. * * @param {number} layer - The layer to set. */ set(e) { this.mask = (1 << e | 0) >>> 0; } /** * Adds membership of the given layer. * * @param {number} layer - The layer to enable. */ enable(e) { this.mask |= 1 << e | 0; } /** * Adds membership to all layers. */ enableAll() { this.mask = -1; } /** * Toggles the membership of the given layer. * * @param {number} layer - The layer to toggle. */ toggle(e) { this.mask ^= 1 << e | 0; } /** * Removes membership of the given layer. * * @param {number} layer - The layer to enable. */ disable(e) { this.mask &= ~(1 << e | 0); } /** * Removes the membership from all layers. */ disableAll() { this.mask = 0; } /** * Returns `true` if this and the given layers object have at least one * layer in common. * * @param {Layers} layers - The layers to test. * @return {boolean } Whether this and the given layers object have at least one layer in common or not. */ test(e) { return (this.mask & e.mask) !== 0; } /** * Returns `true` if the given layer is enabled. * * @param {number} layer - The layer to test. * @return {boolean } Whether the given layer is enabled or not. */ isEnabled(e) { return (this.mask & (1 << e | 0)) !== 0; } } let td = 0; const yl = /* @__PURE__ */ new w(), Tr = /* @__PURE__ */ new mi(), Li = /* @__PURE__ */ new Ue(), ks = /* @__PURE__ */ new w(), os = /* @__PURE__ */ new w(), id = /* @__PURE__ */ new w(), rd = /* @__PURE__ */ new mi(), Ml = /* @__PURE__ */ new w(1, 0, 0), Sl = /* @__PURE__ */ new w(0, 1, 0), bl = /* @__PURE__ */ new w(0, 0, 1), Tl = { type: "added" }, sd = { type: "removed" }, Er = { type: "childadded", child: null }, Yn = { type: "childremoved", child: null }; class dt extends gr { /** * Constructs a new 3D object. */ constructor() { super(), this.isObject3D = !0, Object.defineProperty(this, "id", { value: td++ }), this.uuid = di(), this.name = "", this.type = "Object3D", this.parent = null, this.children = [], this.up = dt.DEFAULT_UP.clone(); const e = new w(), t = new gi(), i = new mi(), s = new w(1, 1, 1); function n() { i.setFromEuler(t, !1); } function a() { t.setFromQuaternion(i, void 0, !1); } t._onChange(n), i._onChange(a), Object.defineProperties(this, { /** * Represents the object's local position. * * @name Object3D#position * @type {Vector3} * @default (0,0,0) */ position: { configurable: !0, enumerable: !0, value: e }, /** * Represents the object's local rotation as Euler angles, in radians. * * @name Object3D#rotation * @type {Euler} * @default (0,0,0) */ rotation: { configurable: !0, enumerable: !0, value: t }, /** * Represents the object's local rotation as Quaternions. * * @name Object3D#quaternion * @type {Quaternion} */ quaternion: { configurable: !0, enumerable: !0, value: i }, /** * Represents the object's local scale. * * @name Object3D#scale * @type {Vector3} * @default (1,1,1) */ scale: { configurable: !0, enumerable: !0, value: s }, /** * Represents the object's model-view matrix. * * @name Object3D#modelViewMatrix * @type {Matrix4} */ modelViewMatrix: { value: new Ue() }, /** * Represents the object's normal matrix. * * @name Object3D#normalMatrix * @type {Matrix3} */ normalMatrix: { value: new Be() } }), this.matrix = new Ue(), this.matrixWorld = new Ue(), this.matrixAutoUpdate = dt.DEFAULT_MATRIX_AUTO_UPDATE, this.matrixWorldAutoUpdate = dt.DEFAULT_MATRIX_WORLD_AUTO_UPDATE, this.matrixWorldNeedsUpdate = !1, this.layers = new Bo(), this.visible = !0, this.castShadow = !1, this.receiveShadow = !1, this.frustumCulled = !0, this.renderOrder = 0, this.animations = [], this.customDepthMaterial = void 0, this.customDistanceMaterial = void 0, this.userData = {}; } /** * A callback that is executed immediately before a 3D object is rendered to a shadow map. * * @param {Renderer|WebGLRenderer} renderer - The renderer. * @param {Object3D} object - The 3D object. * @param {Camera} camera - The camera that is used to render the scene. * @param {Camera} shadowCamera - The shadow camera. * @param {BufferGeometry} geometry - The 3D object's geometry. * @param {Material} depthMaterial - The depth material. * @param {Object} group - The geometry group data. */ onBeforeShadow() { } /** * A callback that is executed immediately after a 3D object is rendered to a shadow map. * * @param {Renderer|WebGLRenderer} renderer - The renderer. * @param {Object3D} object - The 3D object. * @param {Camera} camera - The camera that is used to render the scene. * @param {Camera} shadowCamera - The shadow camera. * @param {BufferGeometry} geometry - The 3D object's geometry. * @param {Material} depthMaterial - The depth material. * @param {Object} group - The geometry group data. */ onAfterShadow() { } /** * A callback that is executed immediately before a 3D object is rendered. * * @param {Renderer|WebGLRenderer} renderer - The renderer. * @param {Object3D} object - The 3D object. * @param {Camera} camera - The camera that is used to render the scene. * @param {BufferGeometry} geometry - The 3D object's geometry. * @param {Material} material - The 3D object's material. * @param {Object} group - The geometry group data. */ onBeforeRender() { } /** * A callback that is executed immediately after a 3D object is rendered. * * @param {Renderer|WebGLRenderer} renderer - The renderer. * @param {Object3D} object - The 3D object. * @param {Camera} camera - The camera that is used to render the scene. * @param {BufferGeometry} geometry - The 3D object's geometry. * @param {Material} material - The 3D object's material. * @param {Object} group - The geometry group data. */ onAfterRender() { } /** * Applies the given transformation matrix to the object and updates the object's position, * rotation and scale. * * @param {Matrix4} matrix - The transformation matrix. */ applyMatrix4(e) { this.matrixAutoUpdate && this.updateMatrix(), this.matrix.premultiply(e), this.matrix.decompose(this.position, this.quaternion, this.scale); } /** * Applies a rotation represented by given the quaternion to the 3D object. * * @param {Quaternion} q - The quaternion. * @return {Object3D} A reference to this instance. */ applyQuaternion(e) { return this.quaternion.premultiply(e), this; } /** * Sets the given rotation represented as an axis/angle couple to the 3D object. * * @param {Vector3} axis - The (normalized) axis vector. * @param {number} angle - The angle in radians. */ setRotationFromAxisAngle(e, t) { this.quaternion.setFromAxisAngle(e, t); } /** * Sets the given rotation represented as Euler angles to the 3D object. * * @param {Euler} euler - The Euler angles. */ setRotationFromEuler(e) { this.quaternion.setFromEuler(e, !0); } /** * Sets the given rotation represented as rotation matrix to the 3D object. * * @param {Matrix4} m - Although a 4x4 matrix is expected, the upper 3x3 portion must be * a pure rotation matrix (i.e, unscaled). */ setRotationFromMatrix(e) { this.quaternion.setFromRotationMatrix(e); } /** * Sets the given rotation represented as a Quaternion to the 3D object. * * @param {Quaternion} q - The Quaternion */ setRotationFromQuaternion(e) { this.quaternion.copy(e); } /** * Rotates the 3D object along an axis in local space. * * @param {Vector3} axis - The (normalized) axis vector. * @param {number} angle - The angle in radians. * @return {Object3D} A reference to this instance. */ rotateOnAxis(e, t) { return Tr.setFromAxisAngle(e, t), this.quaternion.multiply(Tr), this; } /** * Rotates the 3D object along an axis in world space. * * @param {Vector3} axis - The (normalized) axis vector. * @param {number} angle - The angle in radians. * @return {Object3D} A reference to this instance. */ rotateOnWorldAxis(e, t) { return Tr.setFromAxisAngle(e, t), this.quaternion.premultiply(Tr), this; } /** * Rotates the 3D object around its X axis in local space. * * @param {number} angle - The angle in radians. * @return {Object3D} A reference to this instance. */ rotateX(e) { return this.rotateOnAxis(Ml, e); } /** * Rotates the 3D object around its Y axis in local space. * * @param {number} angle - The angle in radians. * @return {Object3D} A reference to this instance. */ rotateY(e) { return this.rotateOnAxis(Sl, e); } /** * Rotates the 3D object around its Z axis in local space. * * @param {number} angle - The angle in radians. * @return {Object3D} A reference to this instance. */ rotateZ(e) { return this.rotateOnAxis(bl, e); } /** * Translate the 3D object by a distance along the given axis in local space. * * @param {Vector3} axis - The (normalized) axis vector. * @param {number} distance - The distance in world units. * @return {Object3D} A reference to this instance. */ translateOnAxis(e, t) { return yl.copy(e).applyQuaternion(this.quaternion), this.position.add(yl.multiplyScalar(t)), this; } /** * Translate the 3D object by a distance along its X-axis in local space. * * @param {number} distance - The distance in world units. * @return {Object3D} A reference to this instance. */ translateX(e) { return this.translateOnAxis(Ml, e); } /** * Translate the 3D object by a distance along its Y-axis in local space. * * @param {number} distance - The distance in world units. * @return {Object3D} A reference to this instance. */ translateY(e) { return this.translateOnAxis(Sl, e); } /** * Translate the 3D object by a distance along its Z-axis in local space. * * @param {number} distance - The distance in world units. * @return {Object3D} A reference to this instance. */ translateZ(e) { return this.translateOnAxis(bl, e); } /** * Converts the given vector from this 3D object's local space to world space. * * @param {Vector3} vector - The vector to convert. * @return {Vector3} The converted vector. */ localToWorld(e) { return this.updateWorldMatrix(!0, !1), e.applyMatrix4(this.matrixWorld); } /** * Converts the given vector from this 3D object's word space to local space. * * @param {Vector3} vector - The vector to convert. * @return {Vector3} The converted vector. */ worldToLocal(e) { return this.updateWorldMatrix(!0, !1), e.applyMatrix4(Li.copy(this.matrixWorld).invert()); } /** * Rotates the object to face a point in world space. * * This method does not support objects having non-uniformly-scaled parent(s). * * @param {number|Vector3} x - The x coordinate in world space. Alternatively, a vector representing a position in world space * @param {number} [y] - The y coordinate in world space. * @param {number} [z] - The z coordinate in world space. */ lookAt(e, t, i) { e.isVector3 ? ks.copy(e) : ks.set(e, t, i); const s = this.parent; this.updateWorldMatrix(!0, !1), os.setFromMatrixPosition(this.matrixWorld), this.isCamera || this.isLight ? Li.lookAt(os, ks, this.up) : Li.lookAt(ks, os, this.up), this.quaternion.setFromRotationMatrix(Li), s && (Li.extractRotation(s.matrixWorld), Tr.setFromRotationMatrix(Li), this.quaternion.premultiply(Tr.invert())); } /** * Adds the given 3D object as a child to this 3D object. An arbitrary number of * objects may be added. Any current parent on an object passed in here will be * removed, since an object can have at most one parent. * * @fires Object3D#added * @fires Object3D#childadded * @param {Object3D} object - The 3D object to add. * @return {Object3D} A reference to this instance. */ add(e) { if (arguments.length > 1) { for (let t = 0; t < arguments.length; t++) this.add(arguments[t]); return this; } return e === this ? (He("Object3D.add: object can't be added as a child of itself.", e), this) : (e && e.isObject3D ? (e.removeFromParent(), e.parent = this, this.children.push(e), e.dispatchEvent(Tl), Er.child = e, this.dispatchEvent(Er), Er.child = null) : He("Object3D.add: object not an instance of THREE.Object3D.", e), this); } /** * Removes the given 3D object as child from this 3D object. * An arbitrary number of objects may be removed. * * @fires Object3D#removed * @fires Object3D#childremoved * @param {Object3D} object - The 3D object to remove. * @return {Object3D} A reference to this instance. */ remove(e) { if (arguments.length > 1) { for (let i = 0; i < arguments.length; i++) this.remove(arguments[i]); return this; } const t = this.children.indexOf(e); return t !== -1 && (e.parent = null, this.children.splice(t, 1), e.dispatchEvent(sd), Yn.child = e, this.dispatchEvent(Yn), Yn.child = null), this; } /** * Removes this 3D object from its current parent. * * @fires Object3D#removed * @fires Object3D#childremoved * @return {Object3D} A reference to this instance. */ removeFromParent() { const e = this.parent; return e !== null && e.remove(this), this; } /** * Removes all child objects. * * @fires Object3D#removed * @fires Object3D#childremoved * @return {Object3D} A reference to this instance. */ clear() { return this.remove(...this.children); } /** * Adds the given 3D object as a child of this 3D object, while maintaining the object's world * transform. This method does not support scene graphs having non-uniformly-scaled nodes(s). * * @fires Object3D#added * @fires Object3D#childadded * @param {Object3D} object - The 3D object to attach. * @return {Object3D} A reference to this instance. */ attach(e) { return this.updateWorldMatrix(!0, !1), Li.copy(this.matrixWorld).invert(), e.parent !== null && (e.parent.updateWorldMatrix(!0, !1), Li.multiply(e.parent.matrixWorld)), e.applyMatrix4(Li), e.removeFromParent(), e.parent = this, this.children.push(e), e.updateWorldMatrix(!1, !0), e.dispatchEvent(Tl), Er.child = e, this.dispatchEvent(Er), Er.child = null, this; } /** * Searches through the 3D object and its children, starting with the 3D object * itself, and returns the first with a matching ID. * * @param {number} id - The id. * @return {Object3D|undefined} The found 3D object. Returns `undefined` if no 3D object has been found. */ getObjectById(e) { return this.getObjectByProperty("id", e); } /** * Searches through the 3D object and its children, starting with the 3D object * itself, and returns the first with a matching name. * * @param {string} name - The name. * @return {Object3D|undefined} The found 3D object. Returns `undefined` if no 3D object has been found. */ getObjectByName(e) { return this.getObjectByProperty("name", e); } /** * Searches through the 3D object and its children, starting with the 3D object * itself, and returns the first with a matching property value. * * @param {string} name - The name of the property. * @param {any} value - The value. * @return {Object3D|undefined} The found 3D object. Returns `undefined` if no 3D object has been found. */ getObjectByProperty(e, t) { if (this[e] === t) return this; for (let i = 0, s = this.children.length; i < s; i++) { const n = this.children[i].getObjectByProperty(e, t); if (n !== void 0) return n; } } /** * 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(e, t, i = []) { this[e] === t && i.push(this); const s = this.children; for (let n = 0, a = s.length; n < a; n++) s[n].getObjectsByProperty(e, t, i); return i; } /** * Returns a vector representing the position of the 3D object in world space. * * @param {Vector3} target - The target vector the result is stored to. * @return {Vector3} The 3D object's position in world space. */ getWorldPosition(e) { return this.updateWorldMatrix(!0, !1), e.setFromMatrixPosition(this.matrixWorld); } /** * Returns a Quaternion representing the position of the 3D object in world space. * * @param {Quaternion} target - The target Quaternion the result is stored to. * @return {Quaternion} The 3D object's rotation in world space. */ getWorldQuaternion(e) { return this.updateWorldMatrix(!0, !1), this.matrixWorld.decompose(os, e, id), e; } /** * Returns a vector representing the scale of the 3D object in world space. * * @param {Vector3} target - The target vector the result is stored to. * @return {Vector3} The 3D object's scale in world space. */ getWorldScale(e) { return this.updateWorldMatrix(!0, !1), this.matrixWorld.decompose(os, rd, e), e; } /** * Returns a vector representing the ("look") direction of the 3D object in world space. * * @param {Vector3} target - The target vector the result is stored to. * @return {Vector3} The 3D object's direction in world space. */ getWorldDirection(e) { this.updateWorldMatrix(!0, !1); const t = this.matrixWorld.elements; return e.set(t[8], t[9], t[10]).normalize(); } /** * Abstract method to get intersections between a casted ray and this * 3D object. Renderable 3D objects such as {@link Mesh}, {@link Line} or {@link Points} * implement this method in order to use raycasting. * * @abstract * @param {Raycaster} raycaster - The raycaster. * @param {Array} intersects - An array holding the result of the method. */ raycast() { } /** * Executes the callback on this 3D object and all descendants. * * Note: Modifying the scene graph inside the callback is discouraged. * * @param {Function} callback - A callback function that allows to process the current 3D object. */ traverse(e) { e(this); const t = this.children; for (let i = 0, s = t.length; i < s; i++) t[i].traverse(e); } /** * Like {@link Object3D#traverse}, but the callback will only be executed for visible 3D objects. * Descendants of invisible 3D objects are not traversed. * * Note: Modifying the scene graph inside the callback is discouraged. * * @param {Function} callback - A callback function that allows to process the current 3D object. */ traverseVisible(e) { if (this.visible === !1) return; e(this); const t = this.children; for (let i = 0, s = t.length; i < s; i++) t[i].traverseVisible(e); } /** * Like {@link Object3D#traverse}, but the callback will only be executed for all ancestors. * * Note: Modifying the scene graph inside the callback is discouraged. * * @param {Function} callback - A callback function that allows to process the current 3D object. */ traverseAncestors(e) { const t = this.parent; t !== null && (e(t), t.traverseAncestors(e)); } /** * Updates the transformation matrix in local space by computing it from the current * position, rotation and scale values. */ updateMatrix() { this.matrix.compose(this.position, this.quaternion, this.scale), this.matrixWorldNeedsUpdate = !0; } /** * Updates the transformation matrix in world space of this 3D objects and its descendants. * * To ensure correct results, this method also recomputes the 3D object's transformation matrix in * local space. The computation of the local and world matrix can be controlled with the * {@link Object3D#matrixAutoUpdate} and {@link Object3D#matrixWorldAutoUpdate} flags which are both * `true` by default. Set these flags to `false` if you need more control over the update matrix process. * * @param {boolean} [force=false] - When set to `true`, a recomputation of world matrices is forced even * when {@link Object3D#matrixWorldAutoUpdate} is set to `false`. */ updateMatrixWorld(e) { this.matrixAutoUpdate && this.updateMatrix(), (this.matrixWorldNeedsUpdate || e) && (this.matrixWorldAutoUpdate === !0 && (this.parent === null ? this.matrixWorld.copy(this.matrix) : this.matrixWorld.multiplyMatrices(this.parent.matrixWorld, this.matrix)), this.matrixWorldNeedsUpdate = !1, e = !0); const t = this.children; for (let i = 0, s = t.length; i < s; i++) t[i].updateMatrixWorld(e); } /** * An alternative version of {@link Object3D#updateMatrixWorld} with more control over the * update of ancestor and descendant nodes. * * @param {boolean} [updateParents=false] Whether ancestor nodes should be updated or not. * @param {boolean} [updateChildren=false] Whether descendant nodes should be updated or not. */ updateWorldMatrix(e, t) { const i = this.parent; if (e === !0 && i !== null && i.updateWorldMatrix(!0, !1), this.matrixAutoUpdate && this.updateMatrix(), this.matrixWorldAutoUpdate === !0 && (this.parent === null ? this.matrixWorld.copy(this.matrix) : this.matrixWorld.multiplyMatrices(this.parent.matrixWorld, this.matrix)), t === !0) { const s = this.children; for (let n = 0, a = s.length; n < a; n++) s[n].updateWorldMatrix(!1, !0); } } /** * Serializes the 3D object into JSON. * * @param {?(Object|string)} meta - An optional value holding meta information about the serialization. * @return {Object} A JSON object representing the serialized 3D object. * @see {@link ObjectLoader#parse} */ toJSON(e) { const t = e === void 0 || typeof e == "string", i = {}; t && (e = { geometries: {}, materials: {}, textures: {}, images: {}, shapes: {}, skeletons: {}, animations: {}, nodes: {} }, i.metadata = { version: 4.7, type: "Object", generator: "Object3D.toJSON" }); const 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(e), s.indirectTexture = this._indirectTexture.toJSON(e), this._colorsTexture !== null && (s.colorsTexture = this._colorsTexture.toJSON(e)), this.boundingSphere !== null && (s.boundingSphere = this.boundingSphere.toJSON()), this.boundingBox !== null && (s.boundingBox = this.boundingBox.toJSON())); function n(o, l) { return o[l.uuid] === void 0 && (o[l.uuid] = l.toJSON(e)), l.uuid; } if (this.isScene) this.background && (this.background.isColor ? s.background = this.background.toJSON() : this.background.isTexture && (s.background = this.background.toJSON(e).uuid)), this.environment && this.environment.isTexture && this.environment.isRenderTargetTexture !== !0 && (s.environment = this.environment.toJSON(e).uuid); else if (this.isMesh || this.isLine || this.isPoints) { s.geometry = n(e.geometries, this.geometry); const o = this.geometry.parameters; if (o !== void 0 && o.shapes !== void 0) { const l = o.shapes; if (Array.isArray(l)) for (let c = 0, h = l.length; c < h; c++) { const u = l[c]; n(e.shapes, u); } else n(e.shapes, l); } } if (this.isSkinnedMesh && (s.bindMode = this.bindMode, s.bindMatrix = this.bindMatrix.toArray(), this.skeleton !== void 0 && (n(e.skeletons, this.skeleton), s.skeleton = this.skeleton.uuid)), this.material !== void 0) if (Array.isArray(this.material)) { const o = []; for (let l = 0, c = this.material.length; l < c; l++) o.push(n(e.materials, this.material[l])); s.material = o; } else s.material = n(e.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(e).object); } if (this.animations.length > 0) { s.animations = []; for (let o = 0; o < this.animations.length; o++) { const l = this.animations[o]; s.animations.push(n(e.animations, l)); } } if (t) { const o = a(e.geometries), l = a(e.materials), c = a(e.textures), h = a(e.images), u = a(e.shapes), d = a(e.skeletons), f = a(e.animations), g = a(e.nodes); o.length > 0 && (i.geometries = o), l.length > 0 && (i.materials = l), c.length > 0 && (i.textures = c), h.length > 0 && (i.images = h), u.length > 0 && (i.shapes = u), d.length > 0 && (i.skeletons = d), f.length > 0 && (i.animations = f), g.length > 0 && (i.nodes = g); } return i.object = s, i; function a(o) { const l = []; for (const c in o) { const h = o[c]; delete h.metadata, l.push(h); } return l; } } /** * Returns a new 3D object with copied values from this instance. * * @param {boolean} [recursive=true] - When set to `true`, descendants of the 3D object are also cloned. * @return {Object3D} A clone of this instance. */ clone(e) { return new this.constructor().copy(this, e); } /** * Copies the values of the given 3D object to this instance. * * @param {Object3D} source - The 3D object to copy. * @param {boolean} [recursive=true] - When set to `true`, descendants of the 3D object are cloned. * @return {Object3D} A reference to this instance. */ copy(e, t = !0) { if (this.name = e.name, this.up.copy(e.up), this.position.copy(e.position), this.rotation.order = e.rotation.order, this.quaternion.copy(e.quaternion), this.scale.copy(e.scale), this.matrix.copy(e.matrix), this.matrixWorld.copy(e.matrixWorld), this.matrixAutoUpdate = e.matrixAutoUpdate, this.matrixWorldAutoUpdate = e.matrixWorldAutoUpdate, this.matrixWorldNeedsUpdate = e.matrixWorldNeedsUpdate, this.layers.mask = e.layers.mask, this.visible = e.visible, this.castShadow = e.castShadow, this.receiveShadow = e.receiveShadow, this.frustumCulled = e.frustumCulled, this.renderOrder = e.renderOrder, this.animations = e.animations.slice(), this.userData = JSON.parse(JSON.stringify(e.userData)), t === !0) for (let i = 0; i < e.children.length; i++) { const s = e.children[i]; this.add(s.clone()); } return this; } } dt.DEFAULT_UP = /* @__PURE__ */ new w(0, 1, 0); dt.DEFAULT_MATRIX_AUTO_UPDATE = !0; dt.DEFAULT_MATRIX_WORLD_AUTO_UPDATE = !0; const ni = /* @__PURE__ */ new w(), Ii = /* @__PURE__ */ new w(), Kn = /* @__PURE__ */ new w(), Ui = /* @__PURE__ */ new w(), wr = /* @__PURE__ */ new w(), Cr = /* @__PURE__ */ new w(), El = /* @__PURE__ */ new w(), Zn = /* @__PURE__ */ new w(), Jn = /* @__PURE__ */ new w(), $n = /* @__PURE__ */ new w(), Qn = /* @__PURE__ */ new Je(), ea = /* @__PURE__ */ new Je(), ta = /* @__PURE__ */ new Je(); class hi { /** * Constructs a new triangle. * * @param {Vector3} [a=(0,0,0)] - The first corner of the triangle. * @param {Vector3} [b=(0,0,0)] - The second corner of the triangle. * @param {Vector3} [c=(0,0,0)] - The third corner of the triangle. */ constructor(e = new w(), t = new w(), i = new w()) { this.a = e, this.b = t, this.c = i; } /** * Computes the normal vector of a triangle. * * @param {Vector3} a - The first corner of the triangle. * @param {Vector3} b - The second corner of the triangle. * @param {Vector3} c - The third corner of the triangle. * @param {Vector3} target - The target vector that is used to store the method's result. * @return {Vector3} The triangle's normal. */ static getNormal(e, t, i, s) { s.subVectors(i, t), ni.subVectors(e, t), s.cross(ni); const n = s.lengthSq(); return n > 0 ? s.multiplyScalar(1 / Math.sqrt(n)) : 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(e, t, i, s, n) { ni.subVectors(s, t), Ii.subVectors(i, t), Kn.subVectors(e, t); const a = ni.dot(ni), o = ni.dot(Ii), l = ni.dot(Kn), c = Ii.dot(Ii), h = Ii.dot(Kn), u = a * c - o * o; if (u === 0) return n.set(0, 0, 0), null; const d = 1 / u, f = (c * l - o * h) * d, g = (a * h - o * l) * d; return n.set(1 - f - g, g, f); } /** * Returns `true` if the given point, when projected onto the plane of the * triangle, lies within the triangle. * * @param {Vector3} point - The point in 3D space to test. * @param {Vector3} a - The first corner of the triangle. * @param {Vector3} b - The second corner of the triangle. * @param {Vector3} c - The third corner of the triangle. * @return {boolean} Whether the given point, when projected onto the plane of the * triangle, lies within the triangle or not. */ static containsPoint(e, t, i, s) { return this.getBarycoord(e, t, i, s, Ui) === null ? !1 : Ui.x >= 0 && Ui.y >= 0 && Ui.x + Ui.y <= 1; } /** * Computes the value barycentrically interpolated for the given point on the * triangle. Returns `null` if the triangle is degenerate. * * @param {Vector3} point - Position of interpolated point. * @param {Vector3} p1 - The first corner of the triangle. * @param {Vector3} p2 - The second corner of the triangle. * @param {Vector3} p3 - The third corner of the triangle. * @param {Vector3} v1 - Value to interpolate of first vertex. * @param {Vector3} v2 - Value to interpolate of second vertex. * @param {Vector3} v3 - Value to interpolate of third vertex. * @param {Vector3} target - The target vector that is used to store the method's result. * @return {?Vector3} The interpolated value. */ static getInterpolation(e, t, i, s, n, a, o, l) { return this.getBarycoord(e, t, i, s, Ui) === null ? (l.x = 0, l.y = 0, "z" in l && (l.z = 0), "w" in l && (l.w = 0), null) : (l.setScalar(0), l.addScaledVector(n, Ui.x), l.addScaledVector(a, Ui.y), l.addScaledVector(o, Ui.z), l); } /** * Computes the value barycentrically interpolated for the given attribute and indices. * * @param {BufferAttribute} attr - The attribute to interpolate. * @param {number} i1 - Index of first vertex. * @param {number} i2 - Index of second vertex. * @param {number} i3 - Index of third vertex. * @param {Vector3} barycoord - The barycoordinate value to use to interpolate. * @param {Vector3} target - The target vector that is used to store the method's result. * @return {Vector3} The interpolated attribute value. */ static getInterpolatedAttribute(e, t, i, s, n, a) { return Qn.setScalar(0), ea.setScalar(0), ta.setScalar(0), Qn.fromBufferAttribute(e, t), ea.fromBufferAttribute(e, i), ta.fromBufferAttribute(e, s), a.setScalar(0), a.addScaledVector(Qn, n.x), a.addScaledVector(ea, n.y), a.addScaledVector(ta, n.z), a; } /** * Returns `true` if the triangle is oriented towards the given direction. * * @param {Vector3} a - The first corner of the triangle. * @param {Vector3} b - The second corner of the triangle. * @param {Vector3} c - The third corner of the triangle. * @param {Vector3} direction - The (normalized) direction vector. * @return {boolean} Whether the triangle is oriented towards the given direction or not. */ static isFrontFacing(e, t, i, s) { return ni.subVectors(i, t), Ii.subVectors(e, t), ni.cross(Ii).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(e, t, i) { return this.a.copy(e), this.b.copy(t), this.c.copy(i), this; } /** * Sets the triangle's vertices by copying the given array values. * * @param {Array} points - An array with 3D points. * @param {number} i0 - The array index representing the first corner of the triangle. * @param {number} i1 - The array index representing the second corner of the triangle. * @param {number} i2 - The array index representing the third corner of the triangle. * @return {Triangle} A reference to this triangle. */ setFromPointsAndIndices(e, t, i, s) { return this.a.copy(e[t]), this.b.copy(e[i]), this.c.copy(e[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(e, t, i, s) { return this.a.fromBufferAttribute(e, t), this.b.fromBufferAttribute(e, i), this.c.fromBufferAttribute(e, 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(e) { return this.a.copy(e.a), this.b.copy(e.b), this.c.copy(e.c), this; } /** * Computes the area of the triangle. * * @return {number} The triangle's area. */ getArea() { return ni.subVectors(this.c, this.b), Ii.subVectors(this.a, this.b), ni.cross(Ii).length() * 0.5; } /** * Computes the midpoint of the triangle. * * @param {Vector3} target - The target vector that is used to store the method's result. * @return {Vector3} The triangle's midpoint. */ getMidpoint(e) { return e.addVectors(this.a, this.b).add(this.c).multiplyScalar(1 / 3); } /** * Computes the normal of the triangle. * * @param {Vector3} target - The target vector that is used to store the method's result. * @return {Vector3} The triangle's normal. */ getNormal(e) { return hi.getNormal(this.a, this.b, this.c, e); } /** * Computes a plane the triangle lies within. * * @param {Plane} target - The target vector that is used to store the method's result. * @return {Plane} The plane the triangle lies within. */ getPlane(e) { return e.setFromCoplanarPoints(this.a, this.b, this.c); } /** * Computes a barycentric coordinates from the given vector. * Returns `null` if the triangle is degenerate. * * @param {Vector3} point - A point in 3D space. * @param {Vector3} target - The target vector that is used to store the method's result. * @return {?Vector3} The barycentric coordinates for the given point */ getBarycoord(e, t) { return hi.getBarycoord(e, this.a, this.b, this.c, t); } /** * Computes the value barycentrically interpolated for the given point on the * triangle. Returns `null` if the triangle is degenerate. * * @param {Vector3} point - Position of interpolated point. * @param {Vector3} v1 - Value to interpolate of first vertex. * @param {Vector3} v2 - Value to interpolate of second vertex. * @param {Vector3} v3 - Value to interpolate of third vertex. * @param {Vector3} target - The target vector that is used to store the method's result. * @return {?Vector3} The interpolated value. */ getInterpolation(e, t, i, s, n) { return hi.getInterpolation(e, this.a, this.b, this.c, t, i, s, n); } /** * Returns `true` if the given point, when projected onto the plane of the * triangle, lies within the triangle. * * @param {Vector3} point - The point in 3D space to test. * @return {boolean} Whether the given point, when projected onto the plane of the * triangle, lies within the triangle or not. */ containsPoint(e) { return hi.containsPoint(e, this.a, this.b, this.c); } /** * Returns `true` if the triangle is oriented towards the given direction. * * @param {Vector3} direction - The (normalized) direction vector. * @return {boolean} Whether the triangle is oriented towards the given direction or not. */ isFrontFacing(e) { return hi.isFrontFacing(this.a, this.b, this.c, e); } /** * Returns `true` if this triangle intersects with the given box. * * @param {Box3} box - The box to intersect. * @return {boolean} Whether this triangle intersects with the given box or not. */ intersectsBox(e) { return e.intersectsTriangle(this); } /** * Returns the closest point on the triangle to the given point. * * @param {Vector3} p - The point to compute the closest point for. * @param {Vector3} target - The target vector that is used to store the method's result. * @return {Vector3} The closest point on the triangle. */ closestPointToPoint(e, t) { const i = this.a, s = this.b, n = this.c; let a, o; wr.subVectors(s, i), Cr.subVectors(n, i), Zn.subVectors(e, i); const l = wr.dot(Zn), c = Cr.dot(Zn); if (l <= 0 && c <= 0) return t.copy(i); Jn.subVectors(e, s); const h = wr.dot(Jn), u = Cr.dot(Jn); if (h >= 0 && u <= h) return t.copy(s); const d = l * u - h * c; if (d <= 0 && l >= 0 && h <= 0) return a = l / (l - h), t.copy(i).addScaledVector(wr, a); $n.subVectors(e, n); const f = wr.dot($n), g = Cr.dot($n); if (g >= 0 && f <= g) return t.copy(n); const v = f * c - l * g; if (v <= 0 && c >= 0 && g <= 0) return o = c / (c - g), t.copy(i).addScaledVector(Cr, o); const m = h * g - f * u; if (m <= 0 && u - h >= 0 && f - g >= 0) return El.subVectors(n, s), o = (u - h) / (u - h + (f - g)), t.copy(s).addScaledVector(El, o); const p = 1 / (m + v + d); return a = v * p, o = d * p, t.copy(i).addScaledVector(wr, a).addScaledVector(Cr, o); } /** * Returns `true` if this triangle is equal with the given one. * * @param {Triangle} triangle - The triangle to test for equality. * @return {boolean} Whether this triangle is equal with the given one. */ equals(e) { return e.a.equals(this.a) && e.b.equals(this.b) && e.c.equals(this.c); } } const nh = { 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 }, Xi = { h: 0, s: 0, l: 0 }, Hs = { h: 0, s: 0, l: 0 }; function ia(r, e, t) { return t < 0 && (t += 1), t > 1 && (t -= 1), t < 1 / 6 ? r + (e - r) * 6 * t : t < 1 / 2 ? e : t < 2 / 3 ? r + (e - r) * 6 * (2 / 3 - t) : r; } class _e { /** * Constructs a new color. * * Note that standard method of specifying color in three.js is with a hexadecimal triplet, * and that method is used throughout the rest of the documentation. * * @param {(number|string|Color)} [r] - The red component of the color. If `g` and `b` are * not provided, it can be hexadecimal triplet, a CSS-style string or another `Color` instance. * @param {number} [g] - The green component. * @param {number} [b] - The blue component. */ constructor(e, t, i) { return this.isColor = !0, this.r = 1, this.g = 1, this.b = 1, this.set(e, t, i); } /** * Sets the colors's components from the given values. * * @param {(number|string|Color)} [r] - The red component of the color. If `g` and `b` are * not provided, it can be hexadecimal triplet, a CSS-style string or another `Color` instance. * @param {number} [g] - The green component. * @param {number} [b] - The blue component. * @return {Color} A reference to this color. */ set(e, t, i) { if (t === void 0 && i === void 0) { const s = e; s && s.isColor ? this.copy(s) : typeof s == "number" ? this.setHex(s) : typeof s == "string" && this.setStyle(s); } else this.setRGB(e, t, i); return this; } /** * Sets the colors's components to the given scalar value. * * @param {number} scalar - The scalar value. * @return {Color} A reference to this color. */ setScalar(e) { return this.r = e, this.g = e, this.b = e, this; } /** * Sets this color from a hexadecimal value. * * @param {number} hex - The hexadecimal value. * @param {string} [colorSpace=SRGBColorSpace] - The color space. * @return {Color} A reference to this color. */ setHex(e, t = wt) { return e = Math.floor(e), this.r = (e >> 16 & 255) / 255, this.g = (e >> 8 & 255) / 255, this.b = (e & 255) / 255, Xe.colorSpaceToWorking(this, t), this; } /** * Sets this color from RGB values. * * @param {number} r - Red channel value between `0.0` and `1.0`. * @param {number} g - Green channel value between `0.0` and `1.0`. * @param {number} b - Blue channel value between `0.0` and `1.0`. * @param {string} [colorSpace=ColorManagement.workingColorSpace] - The color space. * @return {Color} A reference to this color. */ setRGB(e, t, i, s = Xe.workingColorSpace) { return this.r = e, this.g = t, this.b = i, Xe.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(e, t, i, s = Xe.workingColorSpace) { if (e = Uo(e, 1), t = ze(t, 0, 1), i = ze(i, 0, 1), t === 0) this.r = this.g = this.b = i; else { const n = i <= 0.5 ? i * (1 + t) : i + t - i * t, a = 2 * i - n; this.r = ia(a, n, e + 1 / 3), this.g = ia(a, n, e), this.b = ia(a, n, e - 1 / 3); } return Xe.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](https://en.wikipedia.org/wiki/X11_color_names#Color_name_chart) - * all 140 color names are supported). * * @param {string} style - Color as a CSS-style string. * @param {string} [colorSpace=SRGBColorSpace] - The color space. * @return {Color} A reference to this color. */ setStyle(e, t = wt) { function i(n) { n !== void 0 && parseFloat(n) < 1 && Se("Color: Alpha component of " + e + " will be ignored."); } let s; if (s = /^(\w+)\(([^\)]*)\)/.exec(e)) { let n; const a = s[1], o = s[2]; switch (a) { case "rgb": case "rgba": if (n = /^\s*(\d+)\s*,\s*(\d+)\s*,\s*(\d+)\s*(?:,\s*(\d*\.?\d+)\s*)?$/.exec(o)) return i(n[4]), this.setRGB( Math.min(255, parseInt(n[1], 10)) / 255, Math.min(255, parseInt(n[2], 10)) / 255, Math.min(255, parseInt(n[3], 10)) / 255, t ); if (n = /^\s*(\d+)\%\s*,\s*(\d+)\%\s*,\s*(\d+)\%\s*(?:,\s*(\d*\.?\d+)\s*)?$/.exec(o)) return i(n[4]), this.setRGB( Math.min(100, parseInt(n[1], 10)) / 100, Math.min(100, parseInt(n[2], 10)) / 100, Math.min(100, parseInt(n[3], 10)) / 100, t ); break; case "hsl": case "hsla": if (n = /^\s*(\d*\.?\d+)\s*,\s*(\d*\.?\d+)\%\s*,\s*(\d*\.?\d+)\%\s*(?:,\s*(\d*\.?\d+)\s*)?$/.exec(o)) return i(n[4]), this.setHSL( parseFloat(n[1]) / 360, parseFloat(n[2]) / 100, parseFloat(n[3]) / 100, t ); break; default: Se("Color: Unknown color model " + e); } } else if (s = /^\#([A-Fa-f\d]+)$/.exec(e)) { const n = s[1], a = n.length; if (a === 3) return this.setRGB( parseInt(n.charAt(0), 16) / 15, parseInt(n.charAt(1), 16) / 15, parseInt(n.charAt(2), 16) / 15, t ); if (a === 6) return this.setHex(parseInt(n, 16), t); Se("Color: Invalid hex color " + e); } else if (e && e.length > 0) return this.setColorName(e, t); return this; } /** * Sets this color from a color name. Faster than {@link Color#setStyle} if * you don't need the other CSS-style formats. * * For convenience, the list of names is exposed in `Color.NAMES` as a hash. * ```js * Color.NAMES.aliceblue // returns 0xF0F8FF * ``` * * @param {string} style - The color name. * @param {string} [colorSpace=SRGBColorSpace] - The color space. * @return {Color} A reference to this color. */ setColorName(e, t = wt) { const i = nh[e.toLowerCase()]; return i !== void 0 ? this.setHex(i, t) : Se("Color: Unknown color " + e), this; } /** * Returns a new color with copied values from this instance. * * @return {Color} A clone of this instance. */ clone() { return new this.constructor(this.r, this.g, this.b); } /** * Copies the values of the given color to this instance. * * @param {Color} color - The color to copy. * @return {Color} A reference to this color. */ copy(e) { return this.r = e.r, this.g = e.g, this.b = e.b, this; } /** * Copies the given color into this color, and then converts this color from * `SRGBColorSpace` to `LinearSRGBColorSpace`. * * @param {Color} color - The color to copy/convert. * @return {Color} A reference to this color. */ copySRGBToLinear(e) { return this.r = Hi(e.r), this.g = Hi(e.g), this.b = Hi(e.b), this; } /** * Copies the given color into this color, and then converts this color from * `LinearSRGBColorSpace` to `SRGBColorSpace`. * * @param {Color} color - The color to copy/convert. * @return {Color} A reference to this color. */ copyLinearToSRGB(e) { return this.r = Fr(e.r), this.g = Fr(e.g), this.b = Fr(e.b), this; } /** * Converts this color from `SRGBColorSpace` to `LinearSRGBColorSpace`. * * @return {Color} A reference to this color. */ convertSRGBToLinear() { return this.copySRGBToLinear(this), this; } /** * Converts this color from `LinearSRGBColorSpace` to `SRGBColorSpace`. * * @return {Color} A reference to this color. */ convertLinearToSRGB() { return this.copyLinearToSRGB(this), this; } /** * Returns the hexadecimal value of this color. * * @param {string} [colorSpace=SRGBColorSpace] - The color space. * @return {number} The hexadecimal value. */ getHex(e = wt) { return Xe.workingToColorSpace(It.copy(this), e), Math.round(ze(It.r * 255, 0, 255)) * 65536 + Math.round(ze(It.g * 255, 0, 255)) * 256 + Math.round(ze(It.b * 255, 0, 255)); } /** * Returns the hexadecimal value of this color as a string (for example, 'FFFFFF'). * * @param {string} [colorSpace=SRGBColorSpace] - The color space. * @return {string} The hexadecimal value as a string. */ getHexString(e = wt) { return ("000000" + this.getHex(e).toString(16)).slice(-6); } /** * Converts the colors RGB values into the HSL format and stores them into the * given target object. * * @param {{h:number,s:number,l:number}} target - The target object that is used to store the method's result. * @param {string} [colorSpace=ColorManagement.workingColorSpace] - The color space. * @return {{h:number,s:number,l:number}} The HSL representation of this color. */ getHSL(e, t = Xe.workingColorSpace) { Xe.workingToColorSpace(It.copy(this), t); const i = It.r, s = It.g, n = It.b, a = Math.max(i, s, n), o = Math.min(i, s, n); let l, c; const h = (o + a) / 2; if (o === a) l = 0, c = 0; else { const u = a - o; switch (c = h <= 0.5 ? u / (a + o) : u / (2 - a - o), a) { case i: l = (s - n) / u + (s < n ? 6 : 0); break; case s: l = (n - i) / u + 2; break; case n: l = (i - s) / u + 4; break; } l /= 6; } return e.h = l, e.s = c, e.l = h, e; } /** * Returns the RGB values of this color and stores them into the given target object. * * @param {Color} target - The target color that is used to store the method's result. * @param {string} [colorSpace=ColorManagement.workingColorSpace] - The color space. * @return {Color} The RGB representation of this color. */ getRGB(e, t = Xe.workingColorSpace) { return Xe.workingToColorSpace(It.copy(this), t), e.r = It.r, e.g = It.g, e.b = It.b, e; } /** * Returns the value of this color as a CSS style string. Example: `rgb(255,0,0)`. * * @param {string} [colorSpace=SRGBColorSpace] - The color space. * @return {string} The CSS representation of this color. */ getStyle(e = wt) { Xe.workingToColorSpace(It.copy(this), e); const t = It.r, i = It.g, s = It.b; return e !== wt ? `color(${e} ${t.toFixed(3)} ${i.toFixed(3)} ${s.toFixed(3)})` : `rgb(${Math.round(t * 255)},${Math.round(i * 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(e, t, i) { return this.getHSL(Xi), this.setHSL(Xi.h + e, Xi.s + t, Xi.l + i); } /** * Adds the RGB values of the given color to the RGB values of this color. * * @param {Color} color - The color to add. * @return {Color} A reference to this color. */ add(e) { return this.r += e.r, this.g += e.g, this.b += e.b, this; } /** * Adds the RGB values of the given colors and stores the result in this instance. * * @param {Color} color1 - The first color. * @param {Color} color2 - The second color. * @return {Color} A reference to this color. */ addColors(e, t) { return this.r = e.r + t.r, this.g = e.g + t.g, this.b = e.b + t.b, this; } /** * Adds the given scalar value to the RGB values of this color. * * @param {number} s - The scalar to add. * @return {Color} A reference to this color. */ addScalar(e) { return this.r += e, this.g += e, this.b += e, this; } /** * Subtracts the RGB values of the given color from the RGB values of this color. * * @param {Color} color - The color to subtract. * @return {Color} A reference to this color. */ sub(e) { return this.r = Math.max(0, this.r - e.r), this.g = Math.max(0, this.g - e.g), this.b = Math.max(0, this.b - e.b), this; } /** * Multiplies the RGB values of the given color with the RGB values of this color. * * @param {Color} color - The color to multiply. * @return {Color} A reference to this color. */ multiply(e) { return this.r *= e.r, this.g *= e.g, this.b *= e.b, this; } /** * Multiplies the given scalar value with the RGB values of this color. * * @param {number} s - The scalar to multiply. * @return {Color} A reference to this color. */ multiplyScalar(e) { return this.r *= e, this.g *= e, this.b *= e, this; } /** * Linearly interpolates this color's RGB values toward the RGB values of the * given color. The alpha argument can be thought of as the ratio between * the two colors, where `0.0` is this color and `1.0` is the first argument. * * @param {Color} color - The color to converge on. * @param {number} alpha - The interpolation factor in the closed interval `[0,1]`. * @return {Color} A reference to this color. */ lerp(e, t) { return this.r += (e.r - this.r) * t, this.g += (e.g - this.g) * t, this.b += (e.b - this.b) * t, this; } /** * Linearly interpolates between the given colors and stores the result in this instance. * The alpha argument can be thought of as the ratio between the two colors, where `0.0` * is the first and `1.0` is the second color. * * @param {Color} color1 - The first color. * @param {Color} color2 - The second color. * @param {number} alpha - The interpolation factor in the closed interval `[0,1]`. * @return {Color} A reference to this color. */ lerpColors(e, t, i) { return this.r = e.r + (t.r - e.r) * i, this.g = e.g + (t.g - e.g) * i, this.b = e.b + (t.b - e.b) * i, this; } /** * Linearly interpolates this color's HSL values toward the HSL values of the * given color. It differs from {@link Color#lerp} by not interpolating straight * from one color to the other, but instead going through all the hues in between * those two colors. The alpha argument can be thought of as the ratio between * the two colors, where 0.0 is this color and 1.0 is the first argument. * * @param {Color} color - The color to converge on. * @param {number} alpha - The interpolation factor in the closed interval `[0,1]`. * @return {Color} A reference to this color. */ lerpHSL(e, t) { this.getHSL(Xi), e.getHSL(Hs); const i = ys(Xi.h, Hs.h, t), s = ys(Xi.s, Hs.s, t), n = ys(Xi.l, Hs.l, t); return this.setHSL(i, s, n), this; } /** * Sets the color's RGB components from the given 3D vector. * * @param {Vector3} v - The vector to set. * @return {Color} A reference to this color. */ setFromVector3(e) { return this.r = e.x, this.g = e.y, this.b = e.z, this; } /** * Transforms this color with the given 3x3 matrix. * * @param {Matrix3} m - The matrix. * @return {Color} A reference to this color. */ applyMatrix3(e) { const t = this.r, i = this.g, s = this.b, n = e.elements; return this.r = n[0] * t + n[3] * i + n[6] * s, this.g = n[1] * t + n[4] * i + n[7] * s, this.b = n[2] * t + n[5] * i + n[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(e) { return e.r === this.r && e.g === this.g && e.b === this.b; } /** * Sets this color's RGB components from the given array. * * @param {Array} array - An array holding the RGB values. * @param {number} [offset=0] - The offset into the array. * @return {Color} A reference to this color. */ fromArray(e, t = 0) { return this.r = e[t], this.g = e[t + 1], this.b = e[t + 2], this; } /** * Writes the RGB components of this color to the given array. If no array is provided, * the method returns a new instance. * * @param {Array} [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(e = [], t = 0) { return e[t] = this.r, e[t + 1] = this.g, e[t + 2] = this.b, e; } /** * Sets the components of this color from the given buffer attribute. * * @param {BufferAttribute} attribute - The buffer attribute holding color data. * @param {number} index - The index into the attribute. * @return {Color} A reference to this color. */ fromBufferAttribute(e, t) { return this.r = e.getX(t), this.g = e.getY(t), this.b = e.getZ(t), this; } /** * This methods defines the serialization result of this class. Returns the color * as a hexadecimal value. * * @return {number} The hexadecimal value. */ toJSON() { return this.getHex(); } *[Symbol.iterator]() { yield this.r, yield this.g, yield this.b; } } const It = /* @__PURE__ */ new _e(); _e.NAMES = nh; let nd = 0; class $t extends gr { /** * Constructs a new material. */ constructor() { super(), this.isMaterial = !0, Object.defineProperty(this, "id", { value: nd++ }), this.uuid = di(), this.name = "", this.type = "Material", this.blending = Br, this.side = Ti, this.vertexColors = !1, this.opacity = 1, this.transparent = !1, this.alphaHash = !1, this.blendSrc = Ta, this.blendDst = Ea, this.blendEquation = li, this.blendSrcAlpha = null, this.blendDstAlpha = null, this.blendEquationAlpha = null, this.blendColor = new _e(0, 0, 0), this.blendAlpha = 0, this.depthFunc = Vr, this.depthTest = !0, this.depthWrite = !0, this.stencilWriteMask = 255, this.stencilFunc = uo, this.stencilRef = 0, this.stencilFuncMask = 255, this.stencilFail = _r, this.stencilZFail = _r, this.stencilZPass = _r, this.stencilWrite = !1, this.clippingPlanes = null, this.clipIntersection = !1, this.clipShadows = !1, this.shadowSide = null, this.colorWrite = !0, this.precision = null, this.polygonOffset = !1, this.polygonOffsetFactor = 0, this.polygonOffsetUnits = 0, this.dithering = !1, this.alphaToCoverage = !1, this.premultipliedAlpha = !1, this.forceSinglePass = !1, this.allowOverride = !0, this.visible = !0, this.toneMapped = !0, this.userData = {}, this.version = 0, this._alphaTest = 0; } /** * Sets the alpha value to be used when running an alpha test. The material * will not be rendered if the opacity is lower than this value. * * @type {number} * @readonly * @default 0 */ get alphaTest() { return this._alphaTest; } set alphaTest(e) { this._alphaTest > 0 != e > 0 && this.version++, this._alphaTest = e; } /** * An optional callback that is executed immediately before the material is used to render a 3D object. * * This method can only be used when rendering with {@link WebGLRenderer}. * * @param {WebGLRenderer} renderer - The renderer. * @param {Scene} scene - The scene. * @param {Camera} camera - The camera that is used to render the scene. * @param {BufferGeometry} geometry - The 3D object's geometry. * @param {Object3D} object - The 3D object. * @param {Object} group - The geometry group data. */ onBeforeRender() { } /** * An optional callback that is executed immediately before the shader * program is compiled. This function is called with the shader source code * as a parameter. Useful for the modification of built-in materials. * * This method can only be used when rendering with {@link WebGLRenderer}. The * recommended approach when customizing materials is to use `WebGPURenderer` with the new * Node Material system and [TSL](https://github.com/mrdoob/three.js/wiki/Three.js-Shading-Language). * * @param {{vertexShader:string,fragmentShader:string,uniforms:Object}} shaderobject - The object holds the uniforms and the vertex and fragment shader source. * @param {WebGLRenderer} renderer - A reference to the renderer. */ onBeforeCompile() { } /** * In case {@link Material#onBeforeCompile} is used, this callback can be used to identify * values of settings used in `onBeforeCompile()`, so three.js can reuse a cached * shader or recompile the shader for this material as needed. * * This method can only be used when rendering with {@link WebGLRenderer}. * * @return {string} The custom program cache key. */ customProgramCacheKey() { return this.onBeforeCompile.toString(); } /** * This method can be used to set default values from parameter objects. * It is a generic implementation so it can be used with different types * of materials. * * @param {Object} [values] - The material values to set. */ setValues(e) { if (e !== void 0) for (const t in e) { const i = e[t]; if (i === void 0) { Se(`Material: parameter '${t}' has value of undefined.`); continue; } const s = this[t]; if (s === void 0) { Se(`Material: '${t}' is not a property of THREE.${this.type}.`); continue; } s && s.isColor ? s.set(i) : s && s.isVector3 && i && i.isVector3 ? s.copy(i) : this[t] = i; } } /** * Serializes the material into JSON. * * @param {?(Object|string)} meta - An optional value holding meta information about the serialization. * @return {Object} A JSON object representing the serialized material. * @see {@link ObjectLoader#parse} */ toJSON(e) { const t = e === void 0 || typeof e == "string"; t && (e = { textures: {}, images: {} }); const i = { metadata: { version: 4.7, type: "Material", generator: "Material.toJSON" } }; i.uuid = this.uuid, i.type = this.type, this.name !== "" && (i.name = this.name), this.color && this.color.isColor && (i.color = this.color.getHex()), this.roughness !== void 0 && (i.roughness = this.roughness), this.metalness !== void 0 && (i.metalness = this.metalness), this.sheen !== void 0 && (i.sheen = this.sheen), this.sheenColor && this.sheenColor.isColor && (i.sheenColor = this.sheenColor.getHex()), this.sheenRoughness !== void 0 && (i.sheenRoughness = this.sheenRoughness), this.emissive && this.emissive.isColor && (i.emissive = this.emissive.getHex()), this.emissiveIntensity !== void 0 && this.emissiveIntensity !== 1 && (i.emissiveIntensity = this.emissiveIntensity), this.specular && this.specular.isColor && (i.specular = this.specular.getHex()), this.specularIntensity !== void 0 && (i.specularIntensity = this.specularIntensity), this.specularColor && this.specularColor.isColor && (i.specularColor = this.specularColor.getHex()), this.shininess !== void 0 && (i.shininess = this.shininess), this.clearcoat !== void 0 && (i.clearcoat = this.clearcoat), this.clearcoatRoughness !== void 0 && (i.clearcoatRoughness = this.clearcoatRoughness), this.clearcoatMap && this.clearcoatMap.isTexture && (i.clearcoatMap = this.clearcoatMap.toJSON(e).uuid), this.clearcoatRoughnessMap && this.clearcoatRoughnessMap.isTexture && (i.clearcoatRoughnessMap = this.clearcoatRoughnessMap.toJSON(e).uuid), this.clearcoatNormalMap && this.clearcoatNormalMap.isTexture && (i.clearcoatNormalMap = this.clearcoatNormalMap.toJSON(e).uuid, i.clearcoatNormalScale = this.clearcoatNormalScale.toArray()), this.sheenColorMap && this.sheenColorMap.isTexture && (i.sheenColorMap = this.sheenColorMap.toJSON(e).uuid), this.sheenRoughnessMap && this.sheenRoughnessMap.isTexture && (i.sheenRoughnessMap = this.sheenRoughnessMap.toJSON(e).uuid), this.dispersion !== void 0 && (i.dispersion = this.dispersion), this.iridescence !== void 0 && (i.iridescence = this.iridescence), this.iridescenceIOR !== void 0 && (i.iridescenceIOR = this.iridescenceIOR), this.iridescenceThicknessRange !== void 0 && (i.iridescenceThicknessRange = this.iridescenceThicknessRange), this.iridescenceMap && this.iridescenceMap.isTexture && (i.iridescenceMap = this.iridescenceMap.toJSON(e).uuid), this.iridescenceThicknessMap && this.iridescenceThicknessMap.isTexture && (i.iridescenceThicknessMap = this.iridescenceThicknessMap.toJSON(e).uuid), this.anisotropy !== void 0 && (i.anisotropy = this.anisotropy), this.anisotropyRotation !== void 0 && (i.anisotropyRotation = this.anisotropyRotation), this.anisotropyMap && this.anisotropyMap.isTexture && (i.anisotropyMap = this.anisotropyMap.toJSON(e).uuid), this.map && this.map.isTexture && (i.map = this.map.toJSON(e).uuid), this.matcap && this.matcap.isTexture && (i.matcap = this.matcap.toJSON(e).uuid), this.alphaMap && this.alphaMap.isTexture && (i.alphaMap = this.alphaMap.toJSON(e).uuid), this.lightMap && this.lightMap.isTexture && (i.lightMap = this.lightMap.toJSON(e).uuid, i.lightMapIntensity = this.lightMapIntensity), this.aoMap && this.aoMap.isTexture && (i.aoMap = this.aoMap.toJSON(e).uuid, i.aoMapIntensity = this.aoMapIntensity), this.bumpMap && this.bumpMap.isTexture && (i.bumpMap = this.bumpMap.toJSON(e).uuid, i.bumpScale = this.bumpScale), this.normalMap && this.normalMap.isTexture && (i.normalMap = this.normalMap.toJSON(e).uuid, i.normalMapType = this.normalMapType, i.normalScale = this.normalScale.toArray()), this.displacementMap && this.displacementMap.isTexture && (i.displacementMap = this.displacementMap.toJSON(e).uuid, i.displacementScale = this.displacementScale, i.displacementBias = this.displacementBias), this.roughnessMap && this.roughnessMap.isTexture && (i.roughnessMap = this.roughnessMap.toJSON(e).uuid), this.metalnessMap && this.metalnessMap.isTexture && (i.metalnessMap = this.metalnessMap.toJSON(e).uuid), this.emissiveMap && this.emissiveMap.isTexture && (i.emissiveMap = this.emissiveMap.toJSON(e).uuid), this.specularMap && this.specularMap.isTexture && (i.specularMap = this.specularMap.toJSON(e).uuid), this.specularIntensityMap && this.specularIntensityMap.isTexture && (i.specularIntensityMap = this.specularIntensityMap.toJSON(e).uuid), this.specularColorMap && this.specularColorMap.isTexture && (i.specularColorMap = this.specularColorMap.toJSON(e).uuid), this.envMap && this.envMap.isTexture && (i.envMap = this.envMap.toJSON(e).uuid, this.combine !== void 0 && (i.combine = this.combine)), this.envMapRotation !== void 0 && (i.envMapRotation = this.envMapRotation.toArray()), this.envMapIntensity !== void 0 && (i.envMapIntensity = this.envMapIntensity), this.reflectivity !== void 0 && (i.reflectivity = this.reflectivity), this.refractionRatio !== void 0 && (i.refractionRatio = this.refractionRatio), this.gradientMap && this.gradientMap.isTexture && (i.gradientMap = this.gradientMap.toJSON(e).uuid), this.transmission !== void 0 && (i.transmission = this.transmission), this.transmissionMap && this.transmissionMap.isTexture && (i.transmissionMap = this.transmissionMap.toJSON(e).uuid), this.thickness !== void 0 && (i.thickness = this.thickness), this.thicknessMap && this.thicknessMap.isTexture && (i.thicknessMap = this.thicknessMap.toJSON(e).uuid), this.attenuationDistance !== void 0 && this.attenuationDistance !== 1 / 0 && (i.attenuationDistance = this.attenuationDistance), this.attenuationColor !== void 0 && (i.attenuationColor = this.attenuationColor.getHex()), this.size !== void 0 && (i.size = this.size), this.shadowSide !== null && (i.shadowSide = this.shadowSide), this.sizeAttenuation !== void 0 && (i.sizeAttenuation = this.sizeAttenuation), this.blending !== Br && (i.blending = this.blending), this.side !== Ti && (i.side = this.side), this.vertexColors === !0 && (i.vertexColors = !0), this.opacity < 1 && (i.opacity = this.opacity), this.transparent === !0 && (i.transparent = !0), this.blendSrc !== Ta && (i.blendSrc = this.blendSrc), this.blendDst !== Ea && (i.blendDst = this.blendDst), this.blendEquation !== li && (i.blendEquation = this.blendEquation), this.blendSrcAlpha !== null && (i.blendSrcAlpha = this.blendSrcAlpha), this.blendDstAlpha !== null && (i.blendDstAlpha = this.blendDstAlpha), this.blendEquationAlpha !== null && (i.blendEquationAlpha = this.blendEquationAlpha), this.blendColor && this.blendColor.isColor && (i.blendColor = this.blendColor.getHex()), this.blendAlpha !== 0 && (i.blendAlpha = this.blendAlpha), this.depthFunc !== Vr && (i.depthFunc = this.depthFunc), this.depthTest === !1 && (i.depthTest = this.depthTest), this.depthWrite === !1 && (i.depthWrite = this.depthWrite), this.colorWrite === !1 && (i.colorWrite = this.colorWrite), this.stencilWriteMask !== 255 && (i.stencilWriteMask = this.stencilWriteMask), this.stencilFunc !== uo && (i.stencilFunc = this.stencilFunc), this.stencilRef !== 0 && (i.stencilRef = this.stencilRef), this.stencilFuncMask !== 255 && (i.stencilFuncMask = this.stencilFuncMask), this.stencilFail !== _r && (i.stencilFail = this.stencilFail), this.stencilZFail !== _r && (i.stencilZFail = this.stencilZFail), this.stencilZPass !== _r && (i.stencilZPass = this.stencilZPass), this.stencilWrite === !0 && (i.stencilWrite = this.stencilWrite), this.rotation !== void 0 && this.rotation !== 0 && (i.rotation = this.rotation), this.polygonOffset === !0 && (i.polygonOffset = !0), this.polygonOffsetFactor !== 0 && (i.polygonOffsetFactor = this.polygonOffsetFactor), this.polygonOffsetUnits !== 0 && (i.polygonOffsetUnits = this.polygonOffsetUnits), this.linewidth !== void 0 && this.linewidth !== 1 && (i.linewidth = this.linewidth), this.dashSize !== void 0 && (i.dashSize = this.dashSize), this.gapSize !== void 0 && (i.gapSize = this.gapSize), this.scale !== void 0 && (i.scale = this.scale), this.dithering === !0 && (i.dithering = !0), this.alphaTest > 0 && (i.alphaTest = this.alphaTest), this.alphaHash === !0 && (i.alphaHash = !0), this.alphaToCoverage === !0 && (i.alphaToCoverage = !0), this.premultipliedAlpha === !0 && (i.premultipliedAlpha = !0), this.forceSinglePass === !0 && (i.forceSinglePass = !0), this.wireframe === !0 && (i.wireframe = !0), this.wireframeLinewidth > 1 && (i.wireframeLinewidth = this.wireframeLinewidth), this.wireframeLinecap !== "round" && (i.wireframeLinecap = this.wireframeLinecap), this.wireframeLinejoin !== "round" && (i.wireframeLinejoin = this.wireframeLinejoin), this.flatShading === !0 && (i.flatShading = !0), this.visible === !1 && (i.visible = !1), this.toneMapped === !1 && (i.toneMapped = !1), this.fog === !1 && (i.fog = !1), Object.keys(this.userData).length > 0 && (i.userData = this.userData); function s(n) { const a = []; for (const o in n) { const l = n[o]; delete l.metadata, a.push(l); } return a; } if (t) { const n = s(e.textures), a = s(e.images); n.length > 0 && (i.textures = n), a.length > 0 && (i.images = a); } return i; } /** * Returns a new material with copied values from this instance. * * @return {Material} A clone of this instance. */ clone() { return new this.constructor().copy(this); } /** * Copies the values of the given material to this instance. * * @param {Material} source - The material to copy. * @return {Material} A reference to this instance. */ copy(e) { this.name = e.name, this.blending = e.blending, this.side = e.side, this.vertexColors = e.vertexColors, this.opacity = e.opacity, this.transparent = e.transparent, this.blendSrc = e.blendSrc, this.blendDst = e.blendDst, this.blendEquation = e.blendEquation, this.blendSrcAlpha = e.blendSrcAlpha, this.blendDstAlpha = e.blendDstAlpha, this.blendEquationAlpha = e.blendEquationAlpha, this.blendColor.copy(e.blendColor), this.blendAlpha = e.blendAlpha, this.depthFunc = e.depthFunc, this.depthTest = e.depthTest, this.depthWrite = e.depthWrite, this.stencilWriteMask = e.stencilWriteMask, this.stencilFunc = e.stencilFunc, this.stencilRef = e.stencilRef, this.stencilFuncMask = e.stencilFuncMask, this.stencilFail = e.stencilFail, this.stencilZFail = e.stencilZFail, this.stencilZPass = e.stencilZPass, this.stencilWrite = e.stencilWrite; const t = e.clippingPlanes; let i = null; if (t !== null) { const s = t.length; i = new Array(s); for (let n = 0; n !== s; ++n) i[n] = t[n].clone(); } return this.clippingPlanes = i, this.clipIntersection = e.clipIntersection, this.clipShadows = e.clipShadows, this.shadowSide = e.shadowSide, this.colorWrite = e.colorWrite, this.precision = e.precision, this.polygonOffset = e.polygonOffset, this.polygonOffsetFactor = e.polygonOffsetFactor, this.polygonOffsetUnits = e.polygonOffsetUnits, this.dithering = e.dithering, this.alphaTest = e.alphaTest, this.alphaHash = e.alphaHash, this.alphaToCoverage = e.alphaToCoverage, this.premultipliedAlpha = e.premultipliedAlpha, this.forceSinglePass = e.forceSinglePass, this.visible = e.visible, this.toneMapped = e.toneMapped, this.userData = JSON.parse(JSON.stringify(e.userData)), this; } /** * Frees the GPU-related resources allocated by this instance. Call this * method whenever this instance is no longer used in your app. * * @fires Material#dispose */ dispose() { this.dispatchEvent({ type: "dispose" }); } /** * Setting this property to `true` indicates the engine the material * needs to be recompiled. * * @type {boolean} * @default false * @param {boolean} value */ set needsUpdate(e) { e === !0 && this.version++; } } class Bt extends $t { /** * Constructs a new mesh basic material. * * @param {Object} [parameters] - An object with one or more properties * defining the material's appearance. Any property of the material * (including any property from inherited materials) can be passed * in here. Color values can be passed any type of value accepted * by {@link Color#set}. */ constructor(e) { super(), this.isMeshBasicMaterial = !0, this.type = "MeshBasicMaterial", this.color = new _e(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 gi(), this.combine = To, this.reflectivity = 1, this.refractionRatio = 0.98, this.wireframe = !1, this.wireframeLinewidth = 1, this.wireframeLinecap = "round", this.wireframeLinejoin = "round", this.fog = !0, this.setValues(e); } copy(e) { return super.copy(e), this.color.copy(e.color), this.map = e.map, this.lightMap = e.lightMap, this.lightMapIntensity = e.lightMapIntensity, this.aoMap = e.aoMap, this.aoMapIntensity = e.aoMapIntensity, this.specularMap = e.specularMap, this.alphaMap = e.alphaMap, this.envMap = e.envMap, this.envMapRotation.copy(e.envMapRotation), this.combine = e.combine, this.reflectivity = e.reflectivity, this.refractionRatio = e.refractionRatio, this.wireframe = e.wireframe, this.wireframeLinewidth = e.wireframeLinewidth, this.wireframeLinecap = e.wireframeLinecap, this.wireframeLinejoin = e.wireframeLinejoin, this.fog = e.fog, this; } } const Fi = /* @__PURE__ */ ad(); function ad() { const r = new ArrayBuffer(4), e = new Float32Array(r), t = new Uint32Array(r), i = new Uint32Array(512), s = new Uint32Array(512); for (let l = 0; l < 256; ++l) { const c = l - 127; c < -27 ? (i[l] = 0, i[l | 256] = 32768, s[l] = 24, s[l | 256] = 24) : c < -14 ? (i[l] = 1024 >> -c - 14, i[l | 256] = 1024 >> -c - 14 | 32768, s[l] = -c - 1, s[l | 256] = -c - 1) : c <= 15 ? (i[l] = c + 15 << 10, i[l | 256] = c + 15 << 10 | 32768, s[l] = 13, s[l | 256] = 13) : c < 128 ? (i[l] = 31744, i[l | 256] = 64512, s[l] = 24, s[l | 256] = 24) : (i[l] = 31744, i[l | 256] = 64512, s[l] = 13, s[l | 256] = 13); } const n = new Uint32Array(2048), a = new Uint32Array(64), o = new Uint32Array(64); for (let l = 1; l < 1024; ++l) { let c = l << 13, h = 0; for (; (c & 8388608) === 0; ) c <<= 1, h -= 8388608; c &= -8388609, h += 947912704, n[l] = c | h; } for (let l = 1024; l < 2048; ++l) n[l] = 939524096 + (l - 1024 << 13); for (let l = 1; l < 31; ++l) a[l] = l << 23; a[31] = 1199570944, a[32] = 2147483648; for (let l = 33; l < 63; ++l) a[l] = 2147483648 + (l - 32 << 23); a[63] = 3347054592; for (let l = 1; l < 64; ++l) l !== 32 && (o[l] = 1024); return { floatView: e, uint32View: t, baseTable: i, shiftTable: s, mantissaTable: n, exponentTable: a, offsetTable: o }; } function od(r) { Math.abs(r) > 65504 && Se("DataUtils.toHalfFloat(): Value out of range."), r = ze(r, -65504, 65504), Fi.floatView[0] = r; const e = Fi.uint32View[0], t = e >> 23 & 511; return Fi.baseTable[t] + ((e & 8388607) >> Fi.shiftTable[t]); } function ld(r) { const e = r >> 10; return Fi.uint32View[0] = Fi.mantissaTable[Fi.offsetTable[e] + (r & 1023)] + Fi.exponentTable[e], Fi.floatView[0]; } class Vs { /** * Returns a half precision floating point value (FP16) from the given single * precision floating point value (FP32). * * @param {number} val - A single precision floating point value. * @return {number} The FP16 value. */ static toHalfFloat(e) { return od(e); } /** * Returns a single precision floating point value (FP32) from the given half * precision floating point value (FP16). * * @param {number} val - A half precision floating point value. * @return {number} The FP32 value. */ static fromHalfFloat(e) { return ld(e); } } const gt = /* @__PURE__ */ new w(), Gs = /* @__PURE__ */ new oe(); let cd = 0; class zt { /** * Constructs a new buffer attribute. * * @param {TypedArray} array - The array holding the attribute data. * @param {number} itemSize - The item size. * @param {boolean} [normalized=false] - Whether the data are normalized or not. */ constructor(e, t, i = !1) { if (Array.isArray(e)) throw new TypeError("THREE.BufferAttribute: array should be a Typed Array."); this.isBufferAttribute = !0, Object.defineProperty(this, "id", { value: cd++ }), this.name = "", this.array = e, this.itemSize = t, this.count = e !== void 0 ? e.length / t : 0, this.normalized = i, this.usage = po, this.updateRanges = [], this.gpuType = Gt, this.version = 0; } /** * A callback function that is executed after the renderer has transferred the attribute * array data to the GPU. */ onUploadCallback() { } /** * Flag to indicate that this attribute has changed and should be re-sent to * the GPU. Set this to `true` when you modify the value of the array. * * @type {number} * @default false * @param {boolean} value */ set needsUpdate(e) { e === !0 && this.version++; } /** * Sets the usage of this buffer attribute. * * @param {(StaticDrawUsage|DynamicDrawUsage|StreamDrawUsage|StaticReadUsage|DynamicReadUsage|StreamReadUsage|StaticCopyUsage|DynamicCopyUsage|StreamCopyUsage)} value - The usage to set. * @return {BufferAttribute} A reference to this buffer attribute. */ setUsage(e) { return this.usage = e, this; } /** * Adds a range of data in the data array to be updated on the GPU. * * @param {number} start - Position at which to start update. * @param {number} count - The number of components to update. */ addUpdateRange(e, t) { this.updateRanges.push({ start: e, count: t }); } /** * Clears the update ranges. */ clearUpdateRanges() { this.updateRanges.length = 0; } /** * Copies the values of the given buffer attribute to this instance. * * @param {BufferAttribute} source - The buffer attribute to copy. * @return {BufferAttribute} A reference to this instance. */ copy(e) { return this.name = e.name, this.array = new e.array.constructor(e.array), this.itemSize = e.itemSize, this.count = e.count, this.normalized = e.normalized, this.usage = e.usage, this.gpuType = e.gpuType, this; } /** * Copies a vector from the given buffer attribute to this one. The start * and destination position in the attribute buffers are represented by the * given indices. * * @param {number} index1 - The destination index into this buffer attribute. * @param {BufferAttribute} attribute - The buffer attribute to copy from. * @param {number} index2 - The source index into the given buffer attribute. * @return {BufferAttribute} A reference to this instance. */ copyAt(e, t, i) { e *= this.itemSize, i *= t.itemSize; for (let s = 0, n = this.itemSize; s < n; s++) this.array[e + s] = t.array[i + 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(e) { return this.array.set(e), this; } /** * Applies the given 3x3 matrix to the given attribute. Works with * item size `2` and `3`. * * @param {Matrix3} m - The matrix to apply. * @return {BufferAttribute} A reference to this instance. */ applyMatrix3(e) { if (this.itemSize === 2) for (let t = 0, i = this.count; t < i; t++) Gs.fromBufferAttribute(this, t), Gs.applyMatrix3(e), this.setXY(t, Gs.x, Gs.y); else if (this.itemSize === 3) for (let t = 0, i = this.count; t < i; t++) gt.fromBufferAttribute(this, t), gt.applyMatrix3(e), this.setXYZ(t, gt.x, gt.y, gt.z); return this; } /** * Applies the given 4x4 matrix to the given attribute. Only works with * item size `3`. * * @param {Matrix4} m - The matrix to apply. * @return {BufferAttribute} A reference to this instance. */ applyMatrix4(e) { for (let t = 0, i = this.count; t < i; t++) gt.fromBufferAttribute(this, t), gt.applyMatrix4(e), this.setXYZ(t, gt.x, gt.y, gt.z); return this; } /** * Applies the given 3x3 normal matrix to the given attribute. Only works with * item size `3`. * * @param {Matrix3} m - The normal matrix to apply. * @return {BufferAttribute} A reference to this instance. */ applyNormalMatrix(e) { for (let t = 0, i = this.count; t < i; t++) gt.fromBufferAttribute(this, t), gt.applyNormalMatrix(e), this.setXYZ(t, gt.x, gt.y, gt.z); return this; } /** * Applies the given 4x4 matrix to the given attribute. Only works with * item size `3` and with direction vectors. * * @param {Matrix4} m - The matrix to apply. * @return {BufferAttribute} A reference to this instance. */ transformDirection(e) { for (let t = 0, i = this.count; t < i; t++) gt.fromBufferAttribute(this, t), gt.transformDirection(e), this.setXYZ(t, gt.x, gt.y, gt.z); return this; } /** * Sets the given array data in the buffer attribute. * * @param {(TypedArray|Array)} value - The array data to set. * @param {number} [offset=0] - The offset in this buffer attribute's array. * @return {BufferAttribute} A reference to this instance. */ set(e, t = 0) { return this.array.set(e, t), this; } /** * Returns the given component of the vector at the given index. * * @param {number} index - The index into the buffer attribute. * @param {number} component - The component index. * @return {number} The returned value. */ getComponent(e, t) { let i = this.array[e * this.itemSize + t]; return this.normalized && (i = ci(i, this.array)), i; } /** * Sets the given value to the given component of the vector at the given index. * * @param {number} index - The index into the buffer attribute. * @param {number} component - The component index. * @param {number} value - The value to set. * @return {BufferAttribute} A reference to this instance. */ setComponent(e, t, i) { return this.normalized && (i = tt(i, this.array)), this.array[e * this.itemSize + t] = i, this; } /** * Returns the x component of the vector at the given index. * * @param {number} index - The index into the buffer attribute. * @return {number} The x component. */ getX(e) { let t = this.array[e * this.itemSize]; return this.normalized && (t = ci(t, this.array)), t; } /** * Sets the x component of the vector at the given index. * * @param {number} index - The index into the buffer attribute. * @param {number} x - The value to set. * @return {BufferAttribute} A reference to this instance. */ setX(e, t) { return this.normalized && (t = tt(t, this.array)), this.array[e * this.itemSize] = t, this; } /** * Returns the y component of the vector at the given index. * * @param {number} index - The index into the buffer attribute. * @return {number} The y component. */ getY(e) { let t = this.array[e * this.itemSize + 1]; return this.normalized && (t = ci(t, this.array)), t; } /** * Sets the y component of the vector at the given index. * * @param {number} index - The index into the buffer attribute. * @param {number} y - The value to set. * @return {BufferAttribute} A reference to this instance. */ setY(e, t) { return this.normalized && (t = tt(t, this.array)), this.array[e * this.itemSize + 1] = t, this; } /** * Returns the z component of the vector at the given index. * * @param {number} index - The index into the buffer attribute. * @return {number} The z component. */ getZ(e) { let t = this.array[e * this.itemSize + 2]; return this.normalized && (t = ci(t, this.array)), t; } /** * Sets the z component of the vector at the given index. * * @param {number} index - The index into the buffer attribute. * @param {number} z - The value to set. * @return {BufferAttribute} A reference to this instance. */ setZ(e, t) { return this.normalized && (t = tt(t, this.array)), this.array[e * this.itemSize + 2] = t, this; } /** * Returns the w component of the vector at the given index. * * @param {number} index - The index into the buffer attribute. * @return {number} The w component. */ getW(e) { let t = this.array[e * this.itemSize + 3]; return this.normalized && (t = ci(t, this.array)), t; } /** * Sets the w component of the vector at the given index. * * @param {number} index - The index into the buffer attribute. * @param {number} w - The value to set. * @return {BufferAttribute} A reference to this instance. */ setW(e, t) { return this.normalized && (t = tt(t, this.array)), this.array[e * this.itemSize + 3] = t, this; } /** * Sets the x and y component of the vector at the given index. * * @param {number} index - The index into the buffer attribute. * @param {number} x - The value for the x component to set. * @param {number} y - The value for the y component to set. * @return {BufferAttribute} A reference to this instance. */ setXY(e, t, i) { return e *= this.itemSize, this.normalized && (t = tt(t, this.array), i = tt(i, this.array)), this.array[e + 0] = t, this.array[e + 1] = i, this; } /** * Sets the x, y and z component of the vector at the given index. * * @param {number} index - The index into the buffer attribute. * @param {number} x - The value for the x component to set. * @param {number} y - The value for the y component to set. * @param {number} z - The value for the z component to set. * @return {BufferAttribute} A reference to this instance. */ setXYZ(e, t, i, s) { return e *= this.itemSize, this.normalized && (t = tt(t, this.array), i = tt(i, this.array), s = tt(s, this.array)), this.array[e + 0] = t, this.array[e + 1] = i, this.array[e + 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(e, t, i, s, n) { return e *= this.itemSize, this.normalized && (t = tt(t, this.array), i = tt(i, this.array), s = tt(s, this.array), n = tt(n, this.array)), this.array[e + 0] = t, this.array[e + 1] = i, this.array[e + 2] = s, this.array[e + 3] = n, this; } /** * Sets the given callback function that is executed after the Renderer has transferred * the attribute array data to the GPU. Can be used to perform clean-up operations after * the upload when attribute data are not needed anymore on the CPU side. * * @param {Function} callback - The `onUpload()` callback. * @return {BufferAttribute} A reference to this instance. */ onUpload(e) { return this.onUploadCallback = e, this; } /** * Returns a new buffer attribute with copied values from this instance. * * @return {BufferAttribute} A clone of this instance. */ clone() { return new this.constructor(this.array, this.itemSize).copy(this); } /** * Serializes the buffer attribute into JSON. * * @return {Object} A JSON object representing the serialized buffer attribute. */ toJSON() { const e = { itemSize: this.itemSize, type: this.array.constructor.name, array: Array.from(this.array), normalized: this.normalized }; return this.name !== "" && (e.name = this.name), this.usage !== po && (e.usage = this.usage), e; } } class ah extends zt { /** * 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(e, t, i) { super(new Uint16Array(e), t, i); } } class oh extends zt { /** * 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(e, t, i) { super(new Uint32Array(e), t, i); } } class pi extends zt { /** * 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(e, t, i) { super(new Float32Array(e), t, i); } } let hd = 0; const Kt = /* @__PURE__ */ new Ue(), ra = /* @__PURE__ */ new dt(), Rr = /* @__PURE__ */ new w(), Xt = /* @__PURE__ */ new Rt(), ls = /* @__PURE__ */ new Rt(), Et = /* @__PURE__ */ new w(); class Qt extends gr { /** * Constructs a new geometry. */ constructor() { super(), this.isBufferGeometry = !0, Object.defineProperty(this, "id", { value: hd++ }), this.uuid = di(), 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(e) { return Array.isArray(e) ? this.index = new (rh(e) ? oh : ah)(e, 1) : this.index = e, this; } /** * Sets the given indirect attribute to this geometry. * * @param {BufferAttribute} indirect - The attribute holding indirect draw calls. * @return {BufferGeometry} A reference to this instance. */ setIndirect(e) { return this.indirect = e, this; } /** * Returns the indirect attribute of this geometry. * * @return {?BufferAttribute} The indirect attribute. Returns `null` if no indirect attribute is defined. */ getIndirect() { return this.indirect; } /** * Returns the buffer attribute for the given name. * * @param {string} name - The attribute name. * @return {BufferAttribute|InterleavedBufferAttribute|undefined} The buffer attribute. * Returns `undefined` if not attribute has been found. */ getAttribute(e) { return this.attributes[e]; } /** * Sets the given attribute for the given name. * * @param {string} name - The attribute name. * @param {BufferAttribute|InterleavedBufferAttribute} attribute - The attribute to set. * @return {BufferGeometry} A reference to this instance. */ setAttribute(e, t) { return this.attributes[e] = t, this; } /** * Deletes the attribute for the given name. * * @param {string} name - The attribute name to delete. * @return {BufferGeometry} A reference to this instance. */ deleteAttribute(e) { return delete this.attributes[e], this; } /** * Returns `true` if this geometry has an attribute for the given name. * * @param {string} name - The attribute name. * @return {boolean} Whether this geometry has an attribute for the given name or not. */ hasAttribute(e) { return this.attributes[e] !== void 0; } /** * Adds a group to this geometry. * * @param {number} start - The first element in this draw call. That is the first * vertex for non-indexed geometry, otherwise the first triangle index. * @param {number} count - Specifies how many vertices (or indices) are part of this group. * @param {number} [materialIndex=0] - The material array index to use. */ addGroup(e, t, i = 0) { this.groups.push({ start: e, count: t, materialIndex: i }); } /** * Clears all groups. */ clearGroups() { this.groups = []; } /** * Sets the draw range for this geometry. * * @param {number} start - The first vertex for non-indexed geometry, otherwise the first triangle index. * @param {number} count - For non-indexed BufferGeometry, `count` is the number of vertices to render. * For indexed BufferGeometry, `count` is the number of indices to render. */ setDrawRange(e, t) { this.drawRange.start = e, this.drawRange.count = t; } /** * Applies the given 4x4 transformation matrix to the geometry. * * @param {Matrix4} matrix - The matrix to apply. * @return {BufferGeometry} A reference to this instance. */ applyMatrix4(e) { const t = this.attributes.position; t !== void 0 && (t.applyMatrix4(e), t.needsUpdate = !0); const i = this.attributes.normal; if (i !== void 0) { const n = new Be().getNormalMatrix(e); i.applyNormalMatrix(n), i.needsUpdate = !0; } const s = this.attributes.tangent; return s !== void 0 && (s.transformDirection(e), 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(e) { return Kt.makeRotationFromQuaternion(e), this.applyMatrix4(Kt), this; } /** * Rotates the geometry about the X axis. This is typically done as a one time * operation, and not during a loop. Use {@link Object3D#rotation} for typical * real-time mesh rotation. * * @param {number} angle - The angle in radians. * @return {BufferGeometry} A reference to this instance. */ rotateX(e) { return Kt.makeRotationX(e), this.applyMatrix4(Kt), this; } /** * Rotates the geometry about the Y axis. This is typically done as a one time * operation, and not during a loop. Use {@link Object3D#rotation} for typical * real-time mesh rotation. * * @param {number} angle - The angle in radians. * @return {BufferGeometry} A reference to this instance. */ rotateY(e) { return Kt.makeRotationY(e), this.applyMatrix4(Kt), this; } /** * Rotates the geometry about the Z axis. This is typically done as a one time * operation, and not during a loop. Use {@link Object3D#rotation} for typical * real-time mesh rotation. * * @param {number} angle - The angle in radians. * @return {BufferGeometry} A reference to this instance. */ rotateZ(e) { return Kt.makeRotationZ(e), this.applyMatrix4(Kt), this; } /** * Translates the geometry. This is typically done as a one time * operation, and not during a loop. Use {@link Object3D#position} for typical * real-time mesh rotation. * * @param {number} x - The x offset. * @param {number} y - The y offset. * @param {number} z - The z offset. * @return {BufferGeometry} A reference to this instance. */ translate(e, t, i) { return Kt.makeTranslation(e, t, i), this.applyMatrix4(Kt), this; } /** * Scales the geometry. This is typically done as a one time * operation, and not during a loop. Use {@link Object3D#scale} for typical * real-time mesh rotation. * * @param {number} x - The x scale. * @param {number} y - The y scale. * @param {number} z - The z scale. * @return {BufferGeometry} A reference to this instance. */ scale(e, t, i) { return Kt.makeScale(e, t, i), this.applyMatrix4(Kt), this; } /** * Rotates the geometry to face a point in 3D space. This is typically done as a one time * operation, and not during a loop. Use {@link Object3D#lookAt} for typical * real-time mesh rotation. * * @param {Vector3} vector - The target point. * @return {BufferGeometry} A reference to this instance. */ lookAt(e) { return ra.lookAt(e), ra.updateMatrix(), this.applyMatrix4(ra.matrix), this; } /** * Center the geometry based on its bounding box. * * @return {BufferGeometry} A reference to this instance. */ center() { return this.computeBoundingBox(), this.boundingBox.getCenter(Rr).negate(), this.translate(Rr.x, Rr.y, Rr.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(e) { const t = this.getAttribute("position"); if (t === void 0) { const i = []; for (let s = 0, n = e.length; s < n; s++) { const a = e[s]; i.push(a.x, a.y, a.z || 0); } this.setAttribute("position", new pi(i, 3)); } else { const i = Math.min(e.length, t.count); for (let s = 0; s < i; s++) { const n = e[s]; t.setXYZ(s, n.x, n.y, n.z || 0); } e.length > t.count && Se("BufferGeometry: Buffer size too small for points data. Use .dispose() and create a new geometry."), t.needsUpdate = !0; } return this; } /** * Computes the bounding box of the geometry, and updates the `boundingBox` member. * The bounding box is not computed by the engine; it must be computed by your app. * You may need to recompute the bounding box if the geometry vertices are modified. */ computeBoundingBox() { this.boundingBox === null && (this.boundingBox = new Rt()); const e = this.attributes.position, t = this.morphAttributes.position; if (e && e.isGLBufferAttribute) { He("BufferGeometry.computeBoundingBox(): GLBufferAttribute requires a manual bounding box.", this), this.boundingBox.set( new w(-1 / 0, -1 / 0, -1 / 0), new w(1 / 0, 1 / 0, 1 / 0) ); return; } if (e !== void 0) { if (this.boundingBox.setFromBufferAttribute(e), t) for (let i = 0, s = t.length; i < s; i++) { const n = t[i]; Xt.setFromBufferAttribute(n), this.morphTargetsRelative ? (Et.addVectors(this.boundingBox.min, Xt.min), this.boundingBox.expandByPoint(Et), Et.addVectors(this.boundingBox.max, Xt.max), this.boundingBox.expandByPoint(Et)) : (this.boundingBox.expandByPoint(Xt.min), this.boundingBox.expandByPoint(Xt.max)); } } else this.boundingBox.makeEmpty(); (isNaN(this.boundingBox.min.x) || isNaN(this.boundingBox.min.y) || isNaN(this.boundingBox.min.z)) && He('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 Ci()); const e = this.attributes.position, t = this.morphAttributes.position; if (e && e.isGLBufferAttribute) { He("BufferGeometry.computeBoundingSphere(): GLBufferAttribute requires a manual bounding sphere.", this), this.boundingSphere.set(new w(), 1 / 0); return; } if (e) { const i = this.boundingSphere.center; if (Xt.setFromBufferAttribute(e), t) for (let n = 0, a = t.length; n < a; n++) { const o = t[n]; ls.setFromBufferAttribute(o), this.morphTargetsRelative ? (Et.addVectors(Xt.min, ls.min), Xt.expandByPoint(Et), Et.addVectors(Xt.max, ls.max), Xt.expandByPoint(Et)) : (Xt.expandByPoint(ls.min), Xt.expandByPoint(ls.max)); } Xt.getCenter(i); let s = 0; for (let n = 0, a = e.count; n < a; n++) Et.fromBufferAttribute(e, n), s = Math.max(s, i.distanceToSquared(Et)); if (t) for (let n = 0, a = t.length; n < a; n++) { const o = t[n], l = this.morphTargetsRelative; for (let c = 0, h = o.count; c < h; c++) Et.fromBufferAttribute(o, c), l && (Rr.fromBufferAttribute(e, c), Et.add(Rr)), s = Math.max(s, i.distanceToSquared(Et)); } this.boundingSphere.radius = Math.sqrt(s), isNaN(this.boundingSphere.radius) && He('BufferGeometry.computeBoundingSphere(): Computed radius is NaN. The "position" attribute is likely to have NaN values.', this); } } /** * Calculates and adds a tangent attribute to this geometry. * * The computation is only supported for indexed geometries and if position, normal, and uv attributes * are defined. When using a tangent space normal map, prefer the MikkTSpace algorithm provided by * {@link BufferGeometryUtils#computeMikkTSpaceTangents} instead. */ computeTangents() { const e = this.index, t = this.attributes; if (e === null || t.position === void 0 || t.normal === void 0 || t.uv === void 0) { He("BufferGeometry: .computeTangents() failed. Missing required attributes (index, position, normal or uv)"); return; } const i = t.position, s = t.normal, n = t.uv; this.hasAttribute("tangent") === !1 && this.setAttribute("tangent", new zt(new Float32Array(4 * i.count), 4)); const a = this.getAttribute("tangent"), o = [], l = []; for (let I = 0; I < i.count; I++) o[I] = new w(), l[I] = new w(); const c = new w(), h = new w(), u = new w(), d = new oe(), f = new oe(), g = new oe(), v = new w(), m = new w(); function p(I, b, S) { c.fromBufferAttribute(i, I), h.fromBufferAttribute(i, b), u.fromBufferAttribute(i, S), d.fromBufferAttribute(n, I), f.fromBufferAttribute(n, b), g.fromBufferAttribute(n, S), h.sub(c), u.sub(c), f.sub(d), g.sub(d); const D = 1 / (f.x * g.y - g.x * f.y); isFinite(D) && (v.copy(h).multiplyScalar(g.y).addScaledVector(u, -f.y).multiplyScalar(D), m.copy(u).multiplyScalar(f.x).addScaledVector(h, -g.x).multiplyScalar(D), o[I].add(v), o[b].add(v), o[S].add(v), l[I].add(m), l[b].add(m), l[S].add(m)); } let y = this.groups; y.length === 0 && (y = [{ start: 0, count: e.count }]); for (let I = 0, b = y.length; I < b; ++I) { const S = y[I], D = S.start, N = S.count; for (let k = D, H = D + N; k < H; k += 3) p( e.getX(k + 0), e.getX(k + 1), e.getX(k + 2) ); } const _ = new w(), E = new w(), A = new w(), T = new w(); function R(I) { A.fromBufferAttribute(s, I), T.copy(A); const b = o[I]; _.copy(b), _.sub(A.multiplyScalar(A.dot(b))).normalize(), E.crossVectors(T, b); const S = E.dot(l[I]) < 0 ? -1 : 1; a.setXYZW(I, _.x, _.y, _.z, S); } for (let I = 0, b = y.length; I < b; ++I) { const S = y[I], D = S.start, N = S.count; for (let k = D, H = D + N; k < H; k += 3) R(e.getX(k + 0)), R(e.getX(k + 1)), R(e.getX(k + 2)); } } /** * Computes vertex normals for the given vertex data. For indexed geometries, the method sets * each vertex normal to be the average of the face normals of the faces that share that vertex. * For non-indexed geometries, vertices are not shared, and the method sets each vertex normal * to be the same as the face normal. */ computeVertexNormals() { const e = this.index, t = this.getAttribute("position"); if (t !== void 0) { let i = this.getAttribute("normal"); if (i === void 0) i = new zt(new Float32Array(t.count * 3), 3), this.setAttribute("normal", i); else for (let d = 0, f = i.count; d < f; d++) i.setXYZ(d, 0, 0, 0); const s = new w(), n = new w(), a = new w(), o = new w(), l = new w(), c = new w(), h = new w(), u = new w(); if (e) for (let d = 0, f = e.count; d < f; d += 3) { const g = e.getX(d + 0), v = e.getX(d + 1), m = e.getX(d + 2); s.fromBufferAttribute(t, g), n.fromBufferAttribute(t, v), a.fromBufferAttribute(t, m), h.subVectors(a, n), u.subVectors(s, n), h.cross(u), o.fromBufferAttribute(i, g), l.fromBufferAttribute(i, v), c.fromBufferAttribute(i, m), o.add(h), l.add(h), c.add(h), i.setXYZ(g, o.x, o.y, o.z), i.setXYZ(v, l.x, l.y, l.z), i.setXYZ(m, c.x, c.y, c.z); } else for (let d = 0, f = t.count; d < f; d += 3) s.fromBufferAttribute(t, d + 0), n.fromBufferAttribute(t, d + 1), a.fromBufferAttribute(t, d + 2), h.subVectors(a, n), u.subVectors(s, n), h.cross(u), i.setXYZ(d + 0, h.x, h.y, h.z), i.setXYZ(d + 1, h.x, h.y, h.z), i.setXYZ(d + 2, h.x, h.y, h.z); this.normalizeNormals(), i.needsUpdate = !0; } } /** * Ensures every normal vector in a geometry will have a magnitude of `1`. This will * correct lighting on the geometry surfaces. */ normalizeNormals() { const e = this.attributes.normal; for (let t = 0, i = e.count; t < i; t++) Et.fromBufferAttribute(e, t), Et.normalize(), e.setXYZ(t, Et.x, Et.y, Et.z); } /** * Return a new non-index version of this indexed geometry. If the geometry * is already non-indexed, the method is a NOOP. * * @return {BufferGeometry} The non-indexed version of this indexed geometry. */ toNonIndexed() { function e(o, l) { const c = o.array, h = o.itemSize, u = o.normalized, d = new c.constructor(l.length * h); let f = 0, g = 0; for (let v = 0, m = l.length; v < m; v++) { o.isInterleavedBufferAttribute ? f = l[v] * o.data.stride + o.offset : f = l[v] * h; for (let p = 0; p < h; p++) d[g++] = c[f++]; } return new zt(d, h, u); } if (this.index === null) return Se("BufferGeometry.toNonIndexed(): BufferGeometry is already non-indexed."), this; const t = new Qt(), i = this.index.array, s = this.attributes; for (const o in s) { const l = s[o], c = e(l, i); t.setAttribute(o, c); } const n = this.morphAttributes; for (const o in n) { const l = [], c = n[o]; for (let h = 0, u = c.length; h < u; h++) { const d = c[h], f = e(d, i); l.push(f); } t.morphAttributes[o] = l; } t.morphTargetsRelative = this.morphTargetsRelative; const a = this.groups; for (let o = 0, l = a.length; o < l; o++) { const c = a[o]; t.addGroup(c.start, c.count, c.materialIndex); } return t; } /** * Serializes the geometry into JSON. * * @return {Object} A JSON object representing the serialized geometry. */ toJSON() { const e = { metadata: { version: 4.7, type: "BufferGeometry", generator: "BufferGeometry.toJSON" } }; if (e.uuid = this.uuid, e.type = this.type, this.name !== "" && (e.name = this.name), Object.keys(this.userData).length > 0 && (e.userData = this.userData), this.parameters !== void 0) { const l = this.parameters; for (const c in l) l[c] !== void 0 && (e[c] = l[c]); return e; } e.data = { attributes: {} }; const t = this.index; t !== null && (e.data.index = { type: t.array.constructor.name, array: Array.prototype.slice.call(t.array) }); const i = this.attributes; for (const l in i) { const c = i[l]; e.data.attributes[l] = c.toJSON(e.data); } const s = {}; let n = !1; for (const l in this.morphAttributes) { const c = this.morphAttributes[l], h = []; for (let u = 0, d = c.length; u < d; u++) { const f = c[u]; h.push(f.toJSON(e.data)); } h.length > 0 && (s[l] = h, n = !0); } n && (e.data.morphAttributes = s, e.data.morphTargetsRelative = this.morphTargetsRelative); const a = this.groups; a.length > 0 && (e.data.groups = JSON.parse(JSON.stringify(a))); const o = this.boundingSphere; return o !== null && (e.data.boundingSphere = o.toJSON()), e; } /** * Returns a new geometry with copied values from this instance. * * @return {BufferGeometry} A clone of this instance. */ clone() { return new this.constructor().copy(this); } /** * Copies the values of the given geometry to this instance. * * @param {BufferGeometry} source - The geometry to copy. * @return {BufferGeometry} A reference to this instance. */ copy(e) { this.index = null, this.attributes = {}, this.morphAttributes = {}, this.groups = [], this.boundingBox = null, this.boundingSphere = null; const t = {}; this.name = e.name; const i = e.index; i !== null && this.setIndex(i.clone()); const s = e.attributes; for (const c in s) { const h = s[c]; this.setAttribute(c, h.clone(t)); } const n = e.morphAttributes; for (const c in n) { const h = [], u = n[c]; for (let d = 0, f = u.length; d < f; d++) h.push(u[d].clone(t)); this.morphAttributes[c] = h; } this.morphTargetsRelative = e.morphTargetsRelative; const a = e.groups; for (let c = 0, h = a.length; c < h; c++) { const u = a[c]; this.addGroup(u.start, u.count, u.materialIndex); } const o = e.boundingBox; o !== null && (this.boundingBox = o.clone()); const l = e.boundingSphere; return l !== null && (this.boundingSphere = l.clone()), this.drawRange.start = e.drawRange.start, this.drawRange.count = e.drawRange.count, this.userData = e.userData, this; } /** * Frees the GPU-related resources allocated by this instance. Call this * method whenever this instance is no longer used in your app. * * @fires BufferGeometry#dispose */ dispose() { this.dispatchEvent({ type: "dispose" }); } } const wl = /* @__PURE__ */ new Ue(), ar = /* @__PURE__ */ new Qr(), Ws = /* @__PURE__ */ new Ci(), Cl = /* @__PURE__ */ new w(), js = /* @__PURE__ */ new w(), Xs = /* @__PURE__ */ new w(), qs = /* @__PURE__ */ new w(), sa = /* @__PURE__ */ new w(), Ys = /* @__PURE__ */ new w(), Rl = /* @__PURE__ */ new w(), Ks = /* @__PURE__ */ new w(); class nt extends dt { /** * Constructs a new mesh. * * @param {BufferGeometry} [geometry] - The mesh geometry. * @param {Material|Array} [material] - The mesh material. */ constructor(e = new Qt(), t = new Bt()) { super(), this.isMesh = !0, this.type = "Mesh", this.geometry = e, this.material = t, this.morphTargetDictionary = void 0, this.morphTargetInfluences = void 0, this.count = 1, this.updateMorphTargets(); } copy(e, t) { return super.copy(e, t), e.morphTargetInfluences !== void 0 && (this.morphTargetInfluences = e.morphTargetInfluences.slice()), e.morphTargetDictionary !== void 0 && (this.morphTargetDictionary = Object.assign({}, e.morphTargetDictionary)), this.material = Array.isArray(e.material) ? e.material.slice() : e.material, this.geometry = e.geometry, this; } /** * Sets the values of {@link Mesh#morphTargetDictionary} and {@link Mesh#morphTargetInfluences} * to make sure existing morph targets can influence this 3D object. */ updateMorphTargets() { const e = this.geometry.morphAttributes, t = Object.keys(e); if (t.length > 0) { const i = e[t[0]]; if (i !== void 0) { this.morphTargetInfluences = [], this.morphTargetDictionary = {}; for (let s = 0, n = i.length; s < n; s++) { const a = i[s].name || String(s); this.morphTargetInfluences.push(0), this.morphTargetDictionary[a] = s; } } } } /** * Returns the local-space position of the vertex at the given index, taking into * account the current animation state of both morph targets and skinning. * * @param {number} index - The vertex index. * @param {Vector3} target - The target object that is used to store the method's result. * @return {Vector3} The vertex position in local space. */ getVertexPosition(e, t) { const i = this.geometry, s = i.attributes.position, n = i.morphAttributes.position, a = i.morphTargetsRelative; t.fromBufferAttribute(s, e); const o = this.morphTargetInfluences; if (n && o) { Ys.set(0, 0, 0); for (let l = 0, c = n.length; l < c; l++) { const h = o[l], u = n[l]; h !== 0 && (sa.fromBufferAttribute(u, e), a ? Ys.addScaledVector(sa, h) : Ys.addScaledVector(sa.sub(t), h)); } t.add(Ys); } return t; } /** * 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(e, t) { const i = this.geometry, s = this.material, n = this.matrixWorld; s !== void 0 && (i.boundingSphere === null && i.computeBoundingSphere(), Ws.copy(i.boundingSphere), Ws.applyMatrix4(n), ar.copy(e.ray).recast(e.near), !(Ws.containsPoint(ar.origin) === !1 && (ar.intersectSphere(Ws, Cl) === null || ar.origin.distanceToSquared(Cl) > (e.far - e.near) ** 2)) && (wl.copy(n).invert(), ar.copy(e.ray).applyMatrix4(wl), !(i.boundingBox !== null && ar.intersectsBox(i.boundingBox) === !1) && this._computeIntersections(e, t, ar))); } _computeIntersections(e, t, i) { let s; const n = this.geometry, a = this.material, o = n.index, l = n.attributes.position, c = n.attributes.uv, h = n.attributes.uv1, u = n.attributes.normal, d = n.groups, f = n.drawRange; if (o !== null) if (Array.isArray(a)) for (let g = 0, v = d.length; g < v; g++) { const m = d[g], p = a[m.materialIndex], y = Math.max(m.start, f.start), _ = Math.min(o.count, Math.min(m.start + m.count, f.start + f.count)); for (let E = y, A = _; E < A; E += 3) { const T = o.getX(E), R = o.getX(E + 1), I = o.getX(E + 2); s = Zs(this, p, e, i, c, h, u, T, R, I), s && (s.faceIndex = Math.floor(E / 3), s.face.materialIndex = m.materialIndex, t.push(s)); } } else { const g = Math.max(0, f.start), v = Math.min(o.count, f.start + f.count); for (let m = g, p = v; m < p; m += 3) { const y = o.getX(m), _ = o.getX(m + 1), E = o.getX(m + 2); s = Zs(this, a, e, i, c, h, u, y, _, E), s && (s.faceIndex = Math.floor(m / 3), t.push(s)); } } else if (l !== void 0) if (Array.isArray(a)) for (let g = 0, v = d.length; g < v; g++) { const m = d[g], p = a[m.materialIndex], y = Math.max(m.start, f.start), _ = Math.min(l.count, Math.min(m.start + m.count, f.start + f.count)); for (let E = y, A = _; E < A; E += 3) { const T = E, R = E + 1, I = E + 2; s = Zs(this, p, e, i, c, h, u, T, R, I), s && (s.faceIndex = Math.floor(E / 3), s.face.materialIndex = m.materialIndex, t.push(s)); } } else { const g = Math.max(0, f.start), v = Math.min(l.count, f.start + f.count); for (let m = g, p = v; m < p; m += 3) { const y = m, _ = m + 1, E = m + 2; s = Zs(this, a, e, i, c, h, u, y, _, E), s && (s.faceIndex = Math.floor(m / 3), t.push(s)); } } } } function ud(r, e, t, i, s, n, a, o) { let l; if (e.side === Ft ? l = i.intersectTriangle(a, n, s, !0, o) : l = i.intersectTriangle(s, n, a, e.side === Ti, o), l === null) return null; Ks.copy(o), Ks.applyMatrix4(r.matrixWorld); const c = t.ray.origin.distanceTo(Ks); return c < t.near || c > t.far ? null : { distance: c, point: Ks.clone(), object: r }; } function Zs(r, e, t, i, s, n, a, o, l, c) { r.getVertexPosition(o, js), r.getVertexPosition(l, Xs), r.getVertexPosition(c, qs); const h = ud(r, e, t, i, js, Xs, qs, Rl); if (h) { const u = new w(); hi.getBarycoord(Rl, js, Xs, qs, u), s && (h.uv = hi.getInterpolatedAttribute(s, o, l, c, u, new oe())), n && (h.uv1 = hi.getInterpolatedAttribute(n, o, l, c, u, new oe())), a && (h.normal = hi.getInterpolatedAttribute(a, o, l, c, u, new w()), h.normal.dot(i.direction) > 0 && h.normal.multiplyScalar(-1)); const d = { a: o, b: l, c, normal: new w(), materialIndex: 0 }; hi.getNormal(js, Xs, qs, d.normal), h.face = d, h.barycoord = u; } return h; } class fr extends Qt { /** * Constructs a new box geometry. * * @param {number} [width=1] - The width. That is, the length of the edges parallel to the X axis. * @param {number} [height=1] - The height. That is, the length of the edges parallel to the Y axis. * @param {number} [depth=1] - The depth. That is, the length of the edges parallel to the Z axis. * @param {number} [widthSegments=1] - Number of segmented rectangular faces along the width of the sides. * @param {number} [heightSegments=1] - Number of segmented rectangular faces along the height of the sides. * @param {number} [depthSegments=1] - Number of segmented rectangular faces along the depth of the sides. */ constructor(e = 1, t = 1, i = 1, s = 1, n = 1, a = 1) { super(), this.type = "BoxGeometry", this.parameters = { width: e, height: t, depth: i, widthSegments: s, heightSegments: n, depthSegments: a }; const o = this; s = Math.floor(s), n = Math.floor(n), a = Math.floor(a); const l = [], c = [], h = [], u = []; let d = 0, f = 0; g("z", "y", "x", -1, -1, i, t, e, a, n, 0), g("z", "y", "x", 1, -1, i, t, -e, a, n, 1), g("x", "z", "y", 1, 1, e, i, t, s, a, 2), g("x", "z", "y", 1, -1, e, i, -t, s, a, 3), g("x", "y", "z", 1, -1, e, t, i, s, n, 4), g("x", "y", "z", -1, -1, e, t, -i, s, n, 5), this.setIndex(l), this.setAttribute("position", new pi(c, 3)), this.setAttribute("normal", new pi(h, 3)), this.setAttribute("uv", new pi(u, 2)); function g(v, m, p, y, _, E, A, T, R, I, b) { const S = E / R, D = A / I, N = E / 2, k = A / 2, H = T / 2, j = R + 1, q = I + 1; let te = 0, G = 0; const Z = new w(); for (let se = 0; se < q; se++) { const Pe = se * D - k; for (let ke = 0; ke < j; ke++) { const qe = ke * S - N; Z[v] = qe * y, Z[m] = Pe * _, Z[p] = H, c.push(Z.x, Z.y, Z.z), Z[v] = 0, Z[m] = 0, Z[p] = T > 0 ? 1 : -1, h.push(Z.x, Z.y, Z.z), u.push(ke / R), u.push(1 - se / I), te += 1; } } for (let se = 0; se < I; se++) for (let Pe = 0; Pe < R; Pe++) { const ke = d + Pe + j * se, qe = d + Pe + j * (se + 1), Ke = d + (Pe + 1) + j * (se + 1), Ze = d + (Pe + 1) + j * se; l.push(ke, qe, Ze), l.push(qe, Ke, Ze), G += 6; } o.addGroup(f, G, b), f += G, d += te; } } copy(e) { return super.copy(e), this.parameters = Object.assign({}, e.parameters), this; } /** * Factory method for creating an instance of this class from the given * JSON object. * * @param {Object} data - A JSON object representing the serialized geometry. * @return {BoxGeometry} A new instance. */ static fromJSON(e) { return new fr(e.width, e.height, e.depth, e.widthSegments, e.heightSegments, e.depthSegments); } } function Yr(r) { const e = {}; for (const t in r) { e[t] = {}; for (const i in r[t]) { const s = r[t][i]; s && (s.isColor || s.isMatrix3 || s.isMatrix4 || s.isVector2 || s.isVector3 || s.isVector4 || s.isTexture || s.isQuaternion) ? s.isRenderTargetTexture ? (Se("UniformsUtils: Textures of render targets cannot be cloned via cloneUniforms() or mergeUniforms()."), e[t][i] = null) : e[t][i] = s.clone() : Array.isArray(s) ? e[t][i] = s.slice() : e[t][i] = s; } } return e; } function Ot(r) { const e = {}; for (let t = 0; t < r.length; t++) { const i = Yr(r[t]); for (const s in i) e[s] = i[s]; } return e; } function dd(r) { const e = []; for (let t = 0; t < r.length; t++) e.push(r[t].clone()); return e; } function lh(r) { const e = r.getRenderTarget(); return e === null ? r.outputColorSpace : e.isXRRenderTarget === !0 ? e.texture.colorSpace : Xe.workingColorSpace; } const ui = { clone: Yr, merge: Ot }; var pd = `void main() { gl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 ); }`, fd = `void main() { gl_FragColor = vec4( 1.0, 0.0, 0.0, 1.0 ); }`; class ct extends $t { /** * Constructs a new shader material. * * @param {Object} [parameters] - An object with one or more properties * defining the material's appearance. Any property of the material * (including any property from inherited materials) can be passed * in here. Color values can be passed any type of value accepted * by {@link Color#set}. */ constructor(e) { super(), this.isShaderMaterial = !0, this.type = "ShaderMaterial", this.defines = {}, this.uniforms = {}, this.uniformsGroups = [], this.vertexShader = pd, this.fragmentShader = fd, this.linewidth = 1, this.wireframe = !1, this.wireframeLinewidth = 1, this.fog = !1, this.lights = !1, this.clipping = !1, this.forceSinglePass = !0, this.extensions = { clipCullDistance: !1, // set to use vertex shader clipping multiDraw: !1 // set to use vertex shader multi_draw / enable gl_DrawID }, this.defaultAttributeValues = { color: [1, 1, 1], uv: [0, 0], uv1: [0, 0] }, this.index0AttributeName = void 0, this.uniformsNeedUpdate = !1, this.glslVersion = null, e !== void 0 && this.setValues(e); } copy(e) { return super.copy(e), this.fragmentShader = e.fragmentShader, this.vertexShader = e.vertexShader, this.uniforms = Yr(e.uniforms), this.uniformsGroups = dd(e.uniformsGroups), this.defines = Object.assign({}, e.defines), this.wireframe = e.wireframe, this.wireframeLinewidth = e.wireframeLinewidth, this.fog = e.fog, this.lights = e.lights, this.clipping = e.clipping, this.extensions = Object.assign({}, e.extensions), this.glslVersion = e.glslVersion, this; } toJSON(e) { const t = super.toJSON(e); t.glslVersion = this.glslVersion, t.uniforms = {}; for (const s in this.uniforms) { const n = this.uniforms[s].value; n && n.isTexture ? t.uniforms[s] = { type: "t", value: n.toJSON(e).uuid } : n && n.isColor ? t.uniforms[s] = { type: "c", value: n.getHex() } : n && n.isVector2 ? t.uniforms[s] = { type: "v2", value: n.toArray() } : n && n.isVector3 ? t.uniforms[s] = { type: "v3", value: n.toArray() } : n && n.isVector4 ? t.uniforms[s] = { type: "v4", value: n.toArray() } : n && n.isMatrix3 ? t.uniforms[s] = { type: "m3", value: n.toArray() } : n && n.isMatrix4 ? t.uniforms[s] = { type: "m4", value: n.toArray() } : t.uniforms[s] = { value: n }; } Object.keys(this.defines).length > 0 && (t.defines = this.defines), t.vertexShader = this.vertexShader, t.fragmentShader = this.fragmentShader, t.lights = this.lights, t.clipping = this.clipping; const i = {}; for (const s in this.extensions) this.extensions[s] === !0 && (i[s] = !0); return Object.keys(i).length > 0 && (t.extensions = i), t; } } class ch extends dt { /** * Constructs a new camera. */ constructor() { super(), this.isCamera = !0, this.type = "Camera", this.matrixWorldInverse = new Ue(), this.projectionMatrix = new Ue(), this.projectionMatrixInverse = new Ue(), this.coordinateSystem = bi, this._reversedDepth = !1; } /** * The flag that indicates whether the camera uses a reversed depth buffer. * * @type {boolean} * @default false */ get reversedDepth() { return this._reversedDepth; } copy(e, t) { return super.copy(e, t), this.matrixWorldInverse.copy(e.matrixWorldInverse), this.projectionMatrix.copy(e.projectionMatrix), this.projectionMatrixInverse.copy(e.projectionMatrixInverse), this.coordinateSystem = e.coordinateSystem, this; } /** * Returns a vector representing the ("look") direction of the 3D object in world space. * * This method is overwritten since cameras have a different forward vector compared to other * 3D objects. A camera looks down its local, negative z-axis by default. * * @param {Vector3} target - The target vector the result is stored to. * @return {Vector3} The 3D object's direction in world space. */ getWorldDirection(e) { return super.getWorldDirection(e).negate(); } updateMatrixWorld(e) { super.updateMatrixWorld(e), this.matrixWorldInverse.copy(this.matrixWorld).invert(); } updateWorldMatrix(e, t) { super.updateWorldMatrix(e, t), this.matrixWorldInverse.copy(this.matrixWorld).invert(); } clone() { return new this.constructor().copy(this); } } const qi = /* @__PURE__ */ new w(), Al = /* @__PURE__ */ new oe(), Pl = /* @__PURE__ */ new oe(); class Mt extends ch { /** * Constructs a new perspective camera. * * @param {number} [fov=50] - The vertical field of view. * @param {number} [aspect=1] - The aspect ratio. * @param {number} [near=0.1] - The camera's near plane. * @param {number} [far=2000] - The camera's far plane. */ constructor(e = 50, t = 1, i = 0.1, s = 2e3) { super(), this.isPerspectiveCamera = !0, this.type = "PerspectiveCamera", this.fov = e, this.zoom = 1, this.near = i, this.far = s, this.focus = 10, this.aspect = t, this.view = null, this.filmGauge = 35, this.filmOffset = 0, this.updateProjectionMatrix(); } copy(e, t) { return super.copy(e, t), this.fov = e.fov, this.zoom = e.zoom, this.near = e.near, this.far = e.far, this.focus = e.focus, this.aspect = e.aspect, this.view = e.view === null ? null : Object.assign({}, e.view), this.filmGauge = e.filmGauge, this.filmOffset = e.filmOffset, this; } /** * Sets the FOV by focal length in respect to the current {@link PerspectiveCamera#filmGauge}. * * The default film gauge is 35, so that the focal length can be specified for * a 35mm (full frame) camera. * * @param {number} focalLength - Values for focal length and film gauge must have the same unit. */ setFocalLength(e) { const t = 0.5 * this.getFilmHeight() / e; this.fov = qr * 2 * Math.atan(t), this.updateProjectionMatrix(); } /** * Returns the focal length from the current {@link PerspectiveCamera#fov} and * {@link PerspectiveCamera#filmGauge}. * * @return {number} The computed focal length. */ getFocalLength() { const e = Math.tan(xs * 0.5 * this.fov); return 0.5 * this.getFilmHeight() / e; } /** * Returns the current vertical field of view angle in degrees considering {@link PerspectiveCamera#zoom}. * * @return {number} The effective FOV. */ getEffectiveFOV() { return qr * 2 * Math.atan( Math.tan(xs * 0.5 * this.fov) / this.zoom ); } /** * Returns the width of the image on the film. If {@link PerspectiveCamera#aspect} is greater than or * equal to one (landscape format), the result equals {@link PerspectiveCamera#filmGauge}. * * @return {number} The film width. */ getFilmWidth() { return this.filmGauge * Math.min(this.aspect, 1); } /** * Returns the height of the image on the film. If {@link PerspectiveCamera#aspect} is greater than or * equal to one (landscape format), the result equals {@link PerspectiveCamera#filmGauge}. * * @return {number} The film width. */ getFilmHeight() { return this.filmGauge / Math.max(this.aspect, 1); } /** * Computes the 2D bounds of the camera's viewable rectangle at a given distance along the viewing direction. * Sets `minTarget` and `maxTarget` to the coordinates of the lower-left and upper-right corners of the view rectangle. * * @param {number} distance - The viewing distance. * @param {Vector2} minTarget - The lower-left corner of the view rectangle is written into this vector. * @param {Vector2} maxTarget - The upper-right corner of the view rectangle is written into this vector. */ getViewBounds(e, t, i) { qi.set(-1, -1, 0.5).applyMatrix4(this.projectionMatrixInverse), t.set(qi.x, qi.y).multiplyScalar(-e / qi.z), qi.set(1, 1, 0.5).applyMatrix4(this.projectionMatrixInverse), i.set(qi.x, qi.y).multiplyScalar(-e / qi.z); } /** * Computes the width and height of the camera's viewable rectangle at a given distance along the viewing direction. * * @param {number} distance - The viewing distance. * @param {Vector2} target - The target vector that is used to store result where x is width and y is height. * @returns {Vector2} The view size. */ getViewSize(e, t) { return this.getViewBounds(e, Al, Pl), t.subVectors(Pl, Al); } /** * Sets an offset in a larger frustum. This is useful for multi-window or * multi-monitor/multi-machine setups. * * For example, if you have 3x2 monitors and each monitor is 1920x1080 and * the monitors are in grid like this *``` * +---+---+---+ * | A | B | C | * +---+---+---+ * | D | E | F | * +---+---+---+ *``` * then for each monitor you would call it like this: *```js * const w = 1920; * const h = 1080; * const fullWidth = w * 3; * const fullHeight = h * 2; * * // --A-- * camera.setViewOffset( fullWidth, fullHeight, w * 0, h * 0, w, h ); * // --B-- * camera.setViewOffset( fullWidth, fullHeight, w * 1, h * 0, w, h ); * // --C-- * camera.setViewOffset( fullWidth, fullHeight, w * 2, h * 0, w, h ); * // --D-- * camera.setViewOffset( fullWidth, fullHeight, w * 0, h * 1, w, h ); * // --E-- * camera.setViewOffset( fullWidth, fullHeight, w * 1, h * 1, w, h ); * // --F-- * camera.setViewOffset( fullWidth, fullHeight, w * 2, h * 1, w, h ); * ``` * * Note there is no reason monitors have to be the same size or in a grid. * * @param {number} fullWidth - The full width of multiview setup. * @param {number} fullHeight - The full height of multiview setup. * @param {number} x - The horizontal offset of the subcamera. * @param {number} y - The vertical offset of the subcamera. * @param {number} width - The width of subcamera. * @param {number} height - The height of subcamera. */ setViewOffset(e, t, i, s, n, a) { this.aspect = e / t, this.view === null && (this.view = { enabled: !0, fullWidth: 1, fullHeight: 1, offsetX: 0, offsetY: 0, width: 1, height: 1 }), this.view.enabled = !0, this.view.fullWidth = e, this.view.fullHeight = t, this.view.offsetX = i, this.view.offsetY = s, this.view.width = n, this.view.height = a, this.updateProjectionMatrix(); } /** * Removes the view offset from the projection matrix. */ clearViewOffset() { this.view !== null && (this.view.enabled = !1), this.updateProjectionMatrix(); } /** * Updates the camera's projection matrix. Must be called after any change of * camera properties. */ updateProjectionMatrix() { const e = this.near; let t = e * Math.tan(xs * 0.5 * this.fov) / this.zoom, i = 2 * t, s = this.aspect * i, n = -0.5 * s; const a = this.view; if (this.view !== null && this.view.enabled) { const l = a.fullWidth, c = a.fullHeight; n += a.offsetX * s / l, t -= a.offsetY * i / c, s *= a.width / l, i *= a.height / c; } const o = this.filmOffset; o !== 0 && (n += e * o / this.getFilmWidth()), this.projectionMatrix.makePerspective(n, n + s, t, t - i, e, this.far, this.coordinateSystem, this.reversedDepth), this.projectionMatrixInverse.copy(this.projectionMatrix).invert(); } toJSON(e) { const t = super.toJSON(e); return t.object.fov = this.fov, t.object.zoom = this.zoom, t.object.near = this.near, t.object.far = this.far, t.object.focus = this.focus, t.object.aspect = this.aspect, this.view !== null && (t.object.view = Object.assign({}, this.view)), t.object.filmGauge = this.filmGauge, t.object.filmOffset = this.filmOffset, t; } } const Ar = -90, Pr = 1; class md extends dt { /** * Constructs a new cube camera. * * @param {number} near - The camera's near plane. * @param {number} far - The camera's far plane. * @param {WebGLCubeRenderTarget} renderTarget - The cube render target. */ constructor(e, t, i) { super(), this.type = "CubeCamera", this.renderTarget = i, this.coordinateSystem = null, this.activeMipmapLevel = 0; const s = new Mt(Ar, Pr, e, t); s.layers = this.layers, this.add(s); const n = new Mt(Ar, Pr, e, t); n.layers = this.layers, this.add(n); const a = new Mt(Ar, Pr, e, t); a.layers = this.layers, this.add(a); const o = new Mt(Ar, Pr, e, t); o.layers = this.layers, this.add(o); const l = new Mt(Ar, Pr, e, t); l.layers = this.layers, this.add(l); const c = new Mt(Ar, Pr, e, t); c.layers = this.layers, this.add(c); } /** * Must be called when the coordinate system of the cube camera is changed. */ updateCoordinateSystem() { const e = this.coordinateSystem, t = this.children.concat(), [i, s, n, a, o, l] = t; for (const c of t) this.remove(c); if (e === bi) i.up.set(0, 1, 0), i.lookAt(1, 0, 0), s.up.set(0, 1, 0), s.lookAt(-1, 0, 0), n.up.set(0, 0, -1), n.lookAt(0, 1, 0), a.up.set(0, 0, 1), a.lookAt(0, -1, 0), o.up.set(0, 1, 0), o.lookAt(0, 0, 1), l.up.set(0, 1, 0), l.lookAt(0, 0, -1); else if (e === Tn) i.up.set(0, -1, 0), i.lookAt(-1, 0, 0), s.up.set(0, -1, 0), s.lookAt(1, 0, 0), n.up.set(0, 0, 1), n.lookAt(0, 1, 0), a.up.set(0, 0, -1), a.lookAt(0, -1, 0), o.up.set(0, -1, 0), o.lookAt(0, 0, 1), l.up.set(0, -1, 0), l.lookAt(0, 0, -1); else throw new Error("THREE.CubeCamera.updateCoordinateSystem(): Invalid coordinate system: " + e); for (const c of t) this.add(c), c.updateMatrixWorld(); } /** * Calling this method will render the given scene with the given renderer * into the cube render target of the camera. * * @param {(Renderer|WebGLRenderer)} renderer - The renderer. * @param {Scene} scene - The scene to render. */ update(e, t) { this.parent === null && this.updateMatrixWorld(); const { renderTarget: i, activeMipmapLevel: s } = this; this.coordinateSystem !== e.coordinateSystem && (this.coordinateSystem = e.coordinateSystem, this.updateCoordinateSystem()); const [n, a, o, l, c, h] = this.children, u = e.getRenderTarget(), d = e.getActiveCubeFace(), f = e.getActiveMipmapLevel(), g = e.xr.enabled; e.xr.enabled = !1; const v = i.texture.generateMipmaps; i.texture.generateMipmaps = !1, e.setRenderTarget(i, 0, s), e.render(t, n), e.setRenderTarget(i, 1, s), e.render(t, a), e.setRenderTarget(i, 2, s), e.render(t, o), e.setRenderTarget(i, 3, s), e.render(t, l), e.setRenderTarget(i, 4, s), e.render(t, c), i.texture.generateMipmaps = v, e.setRenderTarget(i, 5, s), e.render(t, h), e.setRenderTarget(u, d, f), e.xr.enabled = g, i.texture.needsPMREMUpdate = !0; } } class Fo extends Ct { /** * 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(e = [], t = Gr, i, s, n, a, o, l, c, h) { super(e, t, i, s, n, a, o, l, c, h), this.isCubeTexture = !0, this.flipY = !1; } /** * Alias for {@link CubeTexture#image}. * * @type {Array} */ get images() { return this.image; } set images(e) { this.image = e; } } class gd extends _t { /** * Constructs a new cube render target. * * @param {number} [size=1] - The size of the render target. * @param {RenderTarget~Options} [options] - The configuration object. */ constructor(e = 1, t = {}) { super(e, e, t), this.isWebGLCubeRenderTarget = !0; const i = { width: e, height: e, depth: 1 }, s = [i, i, i, i, i, i]; this.texture = new Fo(s), this._setTextureOptions(t), this.texture.isRenderTargetTexture = !0; } /** * Converts the given equirectangular texture to a cube map. * * @param {WebGLRenderer} renderer - The renderer. * @param {Texture} texture - The equirectangular texture. * @return {WebGLCubeRenderTarget} A reference to this cube render target. */ fromEquirectangularTexture(e, t) { this.texture.type = t.type, this.texture.colorSpace = t.colorSpace, this.texture.generateMipmaps = t.generateMipmaps, this.texture.minFilter = t.minFilter, this.texture.magFilter = t.magFilter; const i = { uniforms: { tEquirect: { value: null } }, vertexShader: ( /* glsl */ ` varying vec3 vWorldDirection; vec3 transformDirection( in vec3 dir, in mat4 matrix ) { return normalize( ( matrix * vec4( dir, 0.0 ) ).xyz ); } void main() { vWorldDirection = transformDirection( position, modelMatrix ); #include #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 fr(5, 5, 5), n = new ct({ name: "CubemapFromEquirect", uniforms: Yr(i.uniforms), vertexShader: i.vertexShader, fragmentShader: i.fragmentShader, side: Ft, blending: vt }); n.uniforms.tEquirect.value = t; const a = new nt(s, n), o = t.minFilter; return t.minFilter === Si && (t.minFilter = xt), new md(1, 10, this).update(e, a), t.minFilter = o, a.geometry.dispose(), a.material.dispose(), this; } /** * Clears this cube render target. * * @param {WebGLRenderer} renderer - The renderer. * @param {boolean} [color=true] - Whether the color buffer should be cleared or not. * @param {boolean} [depth=true] - Whether the depth buffer should be cleared or not. * @param {boolean} [stencil=true] - Whether the stencil buffer should be cleared or not. */ clear(e, t = !0, i = !0, s = !0) { const n = e.getRenderTarget(); for (let a = 0; a < 6; a++) e.setRenderTarget(this, a), e.clear(t, i, s); e.setRenderTarget(n); } } let zi = class extends dt { constructor() { super(), this.isGroup = !0, this.type = "Group"; } }; const vd = { type: "move" }; class na { /** * 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 zi(), 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 zi(), this._targetRay.matrixAutoUpdate = !1, this._targetRay.visible = !1, this._targetRay.hasLinearVelocity = !1, this._targetRay.linearVelocity = new w(), this._targetRay.hasAngularVelocity = !1, this._targetRay.angularVelocity = new w()), 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 zi(), this._grip.matrixAutoUpdate = !1, this._grip.visible = !1, this._grip.hasLinearVelocity = !1, this._grip.linearVelocity = new w(), this._grip.hasAngularVelocity = !1, this._grip.angularVelocity = new w()), this._grip; } /** * Dispatches the given event to the groups representing * the different coordinate spaces of the XR controller. * * @param {Object} event - The event to dispatch. * @return {WebXRController} A reference to this instance. */ dispatchEvent(e) { return this._targetRay !== null && this._targetRay.dispatchEvent(e), this._grip !== null && this._grip.dispatchEvent(e), this._hand !== null && this._hand.dispatchEvent(e), this; } /** * Connects the controller with the given XR input source. * * @param {XRInputSource} inputSource - The input source. * @return {WebXRController} A reference to this instance. */ connect(e) { if (e && e.hand) { const t = this._hand; if (t) for (const i of e.hand.values()) this._getHandJoint(t, i); } return this.dispatchEvent({ type: "connected", data: e }), this; } /** * Disconnects the controller from the given XR input source. * * @param {XRInputSource} inputSource - The input source. * @return {WebXRController} A reference to this instance. */ disconnect(e) { return this.dispatchEvent({ type: "disconnected", data: e }), this._targetRay !== null && (this._targetRay.visible = !1), this._grip !== null && (this._grip.visible = !1), this._hand !== null && (this._hand.visible = !1), this; } /** * Updates the controller with the given input source, XR frame and reference space. * This updates the transformations of the groups that represent the different * coordinate systems of the controller. * * @param {XRInputSource} inputSource - The input source. * @param {XRFrame} frame - The XR frame. * @param {XRReferenceSpace} referenceSpace - The reference space. * @return {WebXRController} A reference to this instance. */ update(e, t, i) { let s = null, n = null, a = null; const o = this._targetRay, l = this._grip, c = this._hand; if (e && t.session.visibilityState !== "visible-blurred") { if (c && e.hand) { a = !0; for (const v of e.hand.values()) { const m = t.getJointPose(v, i), p = this._getHandJoint(c, v); m !== null && (p.matrix.fromArray(m.transform.matrix), p.matrix.decompose(p.position, p.rotation, p.scale), p.matrixWorldNeedsUpdate = !0, p.jointRadius = m.radius), p.visible = m !== null; } const h = c.joints["index-finger-tip"], u = c.joints["thumb-tip"], d = h.position.distanceTo(u.position), f = 0.02, g = 5e-3; c.inputState.pinching && d > f + g ? (c.inputState.pinching = !1, this.dispatchEvent({ type: "pinchend", handedness: e.handedness, target: this })) : !c.inputState.pinching && d <= f - g && (c.inputState.pinching = !0, this.dispatchEvent({ type: "pinchstart", handedness: e.handedness, target: this })); } else l !== null && e.gripSpace && (n = t.getPose(e.gripSpace, i), n !== null && (l.matrix.fromArray(n.transform.matrix), l.matrix.decompose(l.position, l.rotation, l.scale), l.matrixWorldNeedsUpdate = !0, n.linearVelocity ? (l.hasLinearVelocity = !0, l.linearVelocity.copy(n.linearVelocity)) : l.hasLinearVelocity = !1, n.angularVelocity ? (l.hasAngularVelocity = !0, l.angularVelocity.copy(n.angularVelocity)) : l.hasAngularVelocity = !1)); o !== null && (s = t.getPose(e.targetRaySpace, i), s === null && n !== null && (s = n), 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(vd))); } return o !== null && (o.visible = s !== null), l !== null && (l.visible = n !== null), c !== null && (c.visible = a !== null), this; } /** * Returns a group representing the hand joint for the given input joint. * * @private * @param {Group} hand - The group representing the hand space. * @param {XRJointSpace} inputjoint - The hand joint data. * @return {Group} A group representing the hand joint for the given input joint. */ _getHandJoint(e, t) { if (e.joints[t.jointName] === void 0) { const i = new zi(); i.matrixAutoUpdate = !1, i.visible = !1, e.joints[t.jointName] = i, e.add(i); } return e.joints[t.jointName]; } } class zo extends dt { /** * 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 gi(), this.environmentIntensity = 1, this.environmentRotation = new gi(), this.overrideMaterial = null, typeof __THREE_DEVTOOLS__ < "u" && __THREE_DEVTOOLS__.dispatchEvent(new CustomEvent("observe", { detail: this })); } copy(e, t) { return super.copy(e, t), e.background !== null && (this.background = e.background.clone()), e.environment !== null && (this.environment = e.environment.clone()), e.fog !== null && (this.fog = e.fog.clone()), this.backgroundBlurriness = e.backgroundBlurriness, this.backgroundIntensity = e.backgroundIntensity, this.backgroundRotation.copy(e.backgroundRotation), this.environmentIntensity = e.environmentIntensity, this.environmentRotation.copy(e.environmentRotation), e.overrideMaterial !== null && (this.overrideMaterial = e.overrideMaterial.clone()), this.matrixAutoUpdate = e.matrixAutoUpdate, this; } toJSON(e) { const t = super.toJSON(e); return this.fog !== null && (t.object.fog = this.fog.toJSON()), this.backgroundBlurriness > 0 && (t.object.backgroundBlurriness = this.backgroundBlurriness), this.backgroundIntensity !== 1 && (t.object.backgroundIntensity = this.backgroundIntensity), t.object.backgroundRotation = this.backgroundRotation.toArray(), this.environmentIntensity !== 1 && (t.object.environmentIntensity = this.environmentIntensity), t.object.environmentRotation = this.environmentRotation.toArray(), t; } } class _d { /** * Constructs a new interleaved buffer. * * @param {TypedArray} array - A typed array with a shared buffer storing attribute data. * @param {number} stride - The number of typed-array elements per vertex. */ constructor(e, t) { this.isInterleavedBuffer = !0, this.array = e, this.stride = t, this.count = e !== void 0 ? e.length / t : 0, this.usage = po, this.updateRanges = [], this.version = 0, this.uuid = di(); } /** * A callback function that is executed after the renderer has transferred the attribute array * data to the GPU. */ onUploadCallback() { } /** * Flag to indicate that this attribute has changed and should be re-sent to * the GPU. Set this to `true` when you modify the value of the array. * * @type {number} * @default false * @param {boolean} value */ set needsUpdate(e) { e === !0 && this.version++; } /** * Sets the usage of this interleaved buffer. * * @param {(StaticDrawUsage|DynamicDrawUsage|StreamDrawUsage|StaticReadUsage|DynamicReadUsage|StreamReadUsage|StaticCopyUsage|DynamicCopyUsage|StreamCopyUsage)} value - The usage to set. * @return {InterleavedBuffer} A reference to this interleaved buffer. */ setUsage(e) { return this.usage = e, this; } /** * Adds a range of data in the data array to be updated on the GPU. * * @param {number} start - Position at which to start update. * @param {number} count - The number of components to update. */ addUpdateRange(e, t) { this.updateRanges.push({ start: e, count: t }); } /** * Clears the update ranges. */ clearUpdateRanges() { this.updateRanges.length = 0; } /** * Copies the values of the given interleaved buffer to this instance. * * @param {InterleavedBuffer} source - The interleaved buffer to copy. * @return {InterleavedBuffer} A reference to this instance. */ copy(e) { return this.array = new e.array.constructor(e.array), this.count = e.count, this.stride = e.stride, this.usage = e.usage, this; } /** * Copies a vector from the given interleaved buffer to this one. The start * and destination position in the attribute buffers are represented by the * given indices. * * @param {number} index1 - The destination index into this interleaved buffer. * @param {InterleavedBuffer} interleavedBuffer - The interleaved buffer to copy from. * @param {number} index2 - The source index into the given interleaved buffer. * @return {InterleavedBuffer} A reference to this instance. */ copyAt(e, t, i) { e *= this.stride, i *= t.stride; for (let s = 0, n = this.stride; s < n; s++) this.array[e + s] = t.array[i + s]; return this; } /** * Sets the given array data in the interleaved buffer. * * @param {(TypedArray|Array)} value - The array data to set. * @param {number} [offset=0] - The offset in this interleaved buffer's array. * @return {InterleavedBuffer} A reference to this instance. */ set(e, t = 0) { return this.array.set(e, t), this; } /** * Returns a new interleaved buffer with copied values from this instance. * * @param {Object} [data] - An object with shared array buffers that allows to retain shared structures. * @return {InterleavedBuffer} A clone of this instance. */ clone(e) { e.arrayBuffers === void 0 && (e.arrayBuffers = {}), this.array.buffer._uuid === void 0 && (this.array.buffer._uuid = di()), e.arrayBuffers[this.array.buffer._uuid] === void 0 && (e.arrayBuffers[this.array.buffer._uuid] = this.array.slice(0).buffer); const t = new this.array.constructor(e.arrayBuffers[this.array.buffer._uuid]), i = new this.constructor(t, this.stride); return i.setUsage(this.usage), i; } /** * Sets the given callback function that is executed after the Renderer has transferred * the array data to the GPU. Can be used to perform clean-up operations after * the upload when data are not needed anymore on the CPU side. * * @param {Function} callback - The `onUpload()` callback. * @return {InterleavedBuffer} A reference to this instance. */ onUpload(e) { return this.onUploadCallback = e, this; } /** * Serializes the interleaved buffer into JSON. * * @param {Object} [data] - An optional value holding meta information about the serialization. * @return {Object} A JSON object representing the serialized interleaved buffer. */ toJSON(e) { return e.arrayBuffers === void 0 && (e.arrayBuffers = {}), this.array.buffer._uuid === void 0 && (this.array.buffer._uuid = di()), e.arrayBuffers[this.array.buffer._uuid] === void 0 && (e.arrayBuffers[this.array.buffer._uuid] = Array.from(new Uint32Array(this.array.buffer))), { uuid: this.uuid, buffer: this.array.buffer._uuid, type: this.array.constructor.name, stride: this.stride }; } } const Nt = /* @__PURE__ */ new w(); class ko { /** * Constructs a new interleaved buffer attribute. * * @param {InterleavedBuffer} interleavedBuffer - The buffer holding the interleaved data. * @param {number} itemSize - The item size. * @param {number} offset - The attribute offset into the buffer. * @param {boolean} [normalized=false] - Whether the data are normalized or not. */ constructor(e, t, i, s = !1) { this.isInterleavedBufferAttribute = !0, this.name = "", this.data = e, this.itemSize = t, this.offset = i, this.normalized = s; } /** * The item count of this buffer attribute. * * @type {number} * @readonly */ get count() { return this.data.count; } /** * The array holding the interleaved buffer attribute data. * * @type {TypedArray} */ get array() { return this.data.array; } /** * Flag to indicate that this attribute has changed and should be re-sent to * the GPU. Set this to `true` when you modify the value of the array. * * @type {number} * @default false * @param {boolean} value */ set needsUpdate(e) { this.data.needsUpdate = e; } /** * Applies the given 4x4 matrix to the given attribute. Only works with * item size `3`. * * @param {Matrix4} m - The matrix to apply. * @return {InterleavedBufferAttribute} A reference to this instance. */ applyMatrix4(e) { for (let t = 0, i = this.data.count; t < i; t++) Nt.fromBufferAttribute(this, t), Nt.applyMatrix4(e), this.setXYZ(t, Nt.x, Nt.y, Nt.z); return this; } /** * Applies the given 3x3 normal matrix to the given attribute. Only works with * item size `3`. * * @param {Matrix3} m - The normal matrix to apply. * @return {InterleavedBufferAttribute} A reference to this instance. */ applyNormalMatrix(e) { for (let t = 0, i = this.count; t < i; t++) Nt.fromBufferAttribute(this, t), Nt.applyNormalMatrix(e), this.setXYZ(t, Nt.x, Nt.y, Nt.z); return this; } /** * Applies the given 4x4 matrix to the given attribute. Only works with * item size `3` and with direction vectors. * * @param {Matrix4} m - The matrix to apply. * @return {InterleavedBufferAttribute} A reference to this instance. */ transformDirection(e) { for (let t = 0, i = this.count; t < i; t++) Nt.fromBufferAttribute(this, t), Nt.transformDirection(e), this.setXYZ(t, Nt.x, Nt.y, Nt.z); return this; } /** * Returns the given component of the vector at the given index. * * @param {number} index - The index into the buffer attribute. * @param {number} component - The component index. * @return {number} The returned value. */ getComponent(e, t) { let i = this.array[e * this.data.stride + this.offset + t]; return this.normalized && (i = ci(i, this.array)), i; } /** * Sets the given value to the given component of the vector at the given index. * * @param {number} index - The index into the buffer attribute. * @param {number} component - The component index. * @param {number} value - The value to set. * @return {InterleavedBufferAttribute} A reference to this instance. */ setComponent(e, t, i) { return this.normalized && (i = tt(i, this.array)), this.data.array[e * this.data.stride + this.offset + t] = i, this; } /** * Sets the x component of the vector at the given index. * * @param {number} index - The index into the buffer attribute. * @param {number} x - The value to set. * @return {InterleavedBufferAttribute} A reference to this instance. */ setX(e, t) { return this.normalized && (t = tt(t, this.array)), this.data.array[e * this.data.stride + this.offset] = t, this; } /** * Sets the y component of the vector at the given index. * * @param {number} index - The index into the buffer attribute. * @param {number} y - The value to set. * @return {InterleavedBufferAttribute} A reference to this instance. */ setY(e, t) { return this.normalized && (t = tt(t, this.array)), this.data.array[e * this.data.stride + this.offset + 1] = t, this; } /** * Sets the z component of the vector at the given index. * * @param {number} index - The index into the buffer attribute. * @param {number} z - The value to set. * @return {InterleavedBufferAttribute} A reference to this instance. */ setZ(e, t) { return this.normalized && (t = tt(t, this.array)), this.data.array[e * this.data.stride + this.offset + 2] = t, this; } /** * Sets the w component of the vector at the given index. * * @param {number} index - The index into the buffer attribute. * @param {number} w - The value to set. * @return {InterleavedBufferAttribute} A reference to this instance. */ setW(e, t) { return this.normalized && (t = tt(t, this.array)), this.data.array[e * this.data.stride + this.offset + 3] = t, this; } /** * Returns the x component of the vector at the given index. * * @param {number} index - The index into the buffer attribute. * @return {number} The x component. */ getX(e) { let t = this.data.array[e * this.data.stride + this.offset]; return this.normalized && (t = ci(t, this.array)), t; } /** * Returns the y component of the vector at the given index. * * @param {number} index - The index into the buffer attribute. * @return {number} The y component. */ getY(e) { let t = this.data.array[e * this.data.stride + this.offset + 1]; return this.normalized && (t = ci(t, this.array)), t; } /** * Returns the z component of the vector at the given index. * * @param {number} index - The index into the buffer attribute. * @return {number} The z component. */ getZ(e) { let t = this.data.array[e * this.data.stride + this.offset + 2]; return this.normalized && (t = ci(t, this.array)), t; } /** * Returns the w component of the vector at the given index. * * @param {number} index - The index into the buffer attribute. * @return {number} The w component. */ getW(e) { let t = this.data.array[e * this.data.stride + this.offset + 3]; return this.normalized && (t = ci(t, this.array)), t; } /** * Sets the x and y component of the vector at the given index. * * @param {number} index - The index into the buffer attribute. * @param {number} x - The value for the x component to set. * @param {number} y - The value for the y component to set. * @return {InterleavedBufferAttribute} A reference to this instance. */ setXY(e, t, i) { return e = e * this.data.stride + this.offset, this.normalized && (t = tt(t, this.array), i = tt(i, this.array)), this.data.array[e + 0] = t, this.data.array[e + 1] = i, this; } /** * Sets the x, y and z component of the vector at the given index. * * @param {number} index - The index into the buffer attribute. * @param {number} x - The value for the x component to set. * @param {number} y - The value for the y component to set. * @param {number} z - The value for the z component to set. * @return {InterleavedBufferAttribute} A reference to this instance. */ setXYZ(e, t, i, s) { return e = e * this.data.stride + this.offset, this.normalized && (t = tt(t, this.array), i = tt(i, this.array), s = tt(s, this.array)), this.data.array[e + 0] = t, this.data.array[e + 1] = i, this.data.array[e + 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 {InterleavedBufferAttribute} A reference to this instance. */ setXYZW(e, t, i, s, n) { return e = e * this.data.stride + this.offset, this.normalized && (t = tt(t, this.array), i = tt(i, this.array), s = tt(s, this.array), n = tt(n, this.array)), this.data.array[e + 0] = t, this.data.array[e + 1] = i, this.data.array[e + 2] = s, this.data.array[e + 3] = n, this; } /** * Returns a new buffer attribute with copied values from this instance. * * If no parameter is provided, cloning an interleaved buffer attribute will de-interleave buffer data. * * @param {Object} [data] - An object with interleaved buffers that allows to retain the interleaved property. * @return {BufferAttribute|InterleavedBufferAttribute} A clone of this instance. */ clone(e) { if (e === void 0) { En("InterleavedBufferAttribute.clone(): Cloning an interleaved buffer attribute will de-interleave buffer data."); const t = []; for (let i = 0; i < this.count; i++) { const s = i * this.data.stride + this.offset; for (let n = 0; n < this.itemSize; n++) t.push(this.data.array[s + n]); } return new zt(new this.array.constructor(t), this.itemSize, this.normalized); } else return e.interleavedBuffers === void 0 && (e.interleavedBuffers = {}), e.interleavedBuffers[this.data.uuid] === void 0 && (e.interleavedBuffers[this.data.uuid] = this.data.clone(e)), new ko(e.interleavedBuffers[this.data.uuid], this.itemSize, this.offset, this.normalized); } /** * Serializes the buffer attribute into JSON. * * If no parameter is provided, cloning an interleaved buffer attribute will de-interleave buffer data. * * @param {Object} [data] - An optional value holding meta information about the serialization. * @return {Object} A JSON object representing the serialized buffer attribute. */ toJSON(e) { if (e === void 0) { En("InterleavedBufferAttribute.toJSON(): Serializing an interleaved buffer attribute will de-interleave buffer data."); const t = []; for (let i = 0; i < this.count; i++) { const s = i * this.data.stride + this.offset; for (let n = 0; n < this.itemSize; n++) t.push(this.data.array[s + n]); } return { itemSize: this.itemSize, type: this.array.constructor.name, array: t, normalized: this.normalized }; } else return e.interleavedBuffers === void 0 && (e.interleavedBuffers = {}), e.interleavedBuffers[this.data.uuid] === void 0 && (e.interleavedBuffers[this.data.uuid] = this.data.toJSON(e)), { isInterleavedBufferAttribute: !0, itemSize: this.itemSize, data: this.data.uuid, offset: this.offset, normalized: this.normalized }; } } const Dl = /* @__PURE__ */ new w(), Ll = /* @__PURE__ */ new Je(), Il = /* @__PURE__ */ new Je(), xd = /* @__PURE__ */ new w(), Ul = /* @__PURE__ */ new Ue(), Js = /* @__PURE__ */ new w(), aa = /* @__PURE__ */ new Ci(), Nl = /* @__PURE__ */ new Ue(), oa = /* @__PURE__ */ new Qr(); class yd extends nt { /** * Constructs a new skinned mesh. * * @param {BufferGeometry} [geometry] - The mesh geometry. * @param {Material|Array} [material] - The mesh material. */ constructor(e, t) { super(e, t), this.isSkinnedMesh = !0, this.type = "SkinnedMesh", this.bindMode = ll, this.bindMatrix = new Ue(), this.bindMatrixInverse = new Ue(), this.boundingBox = null, this.boundingSphere = null; } /** * Computes the bounding box of the skinned mesh, and updates {@link SkinnedMesh#boundingBox}. * The bounding box is not automatically computed by the engine; this method must be called by your app. * If the skinned mesh is animated, the bounding box should be recomputed per frame in order to reflect * the current animation state. */ computeBoundingBox() { const e = this.geometry; this.boundingBox === null && (this.boundingBox = new Rt()), this.boundingBox.makeEmpty(); const t = e.getAttribute("position"); for (let i = 0; i < t.count; i++) this.getVertexPosition(i, Js), this.boundingBox.expandByPoint(Js); } /** * Computes the bounding sphere of the skinned mesh, and updates {@link SkinnedMesh#boundingSphere}. * The bounding sphere is automatically computed by the engine once when it is needed, e.g., for ray casting * and view frustum culling. If the skinned mesh is animated, the bounding sphere should be recomputed * per frame in order to reflect the current animation state. */ computeBoundingSphere() { const e = this.geometry; this.boundingSphere === null && (this.boundingSphere = new Ci()), this.boundingSphere.makeEmpty(); const t = e.getAttribute("position"); for (let i = 0; i < t.count; i++) this.getVertexPosition(i, Js), this.boundingSphere.expandByPoint(Js); } copy(e, t) { return super.copy(e, t), this.bindMode = e.bindMode, this.bindMatrix.copy(e.bindMatrix), this.bindMatrixInverse.copy(e.bindMatrixInverse), this.skeleton = e.skeleton, e.boundingBox !== null && (this.boundingBox = e.boundingBox.clone()), e.boundingSphere !== null && (this.boundingSphere = e.boundingSphere.clone()), this; } raycast(e, t) { const i = this.material, s = this.matrixWorld; i !== void 0 && (this.boundingSphere === null && this.computeBoundingSphere(), aa.copy(this.boundingSphere), aa.applyMatrix4(s), e.ray.intersectsSphere(aa) !== !1 && (Nl.copy(s).invert(), oa.copy(e.ray).applyMatrix4(Nl), !(this.boundingBox !== null && oa.intersectsBox(this.boundingBox) === !1) && this._computeIntersections(e, t, oa))); } getVertexPosition(e, t) { return super.getVertexPosition(e, t), this.applyBoneTransform(e, t), t; } /** * Binds the given skeleton to the skinned mesh. * * @param {Skeleton} skeleton - The skeleton to bind. * @param {Matrix4} [bindMatrix] - The bind matrix. If no bind matrix is provided, * the skinned mesh's world matrix will be used instead. */ bind(e, t) { this.skeleton = e, t === void 0 && (this.updateMatrixWorld(!0), this.skeleton.calculateInverses(), t = this.matrixWorld), this.bindMatrix.copy(t), this.bindMatrixInverse.copy(t).invert(); } /** * This method sets the skinned mesh in the rest pose). */ pose() { this.skeleton.pose(); } /** * Normalizes the skin weights which are defined as a buffer attribute * in the skinned mesh's geometry. */ normalizeSkinWeights() { const e = new Je(), t = this.geometry.attributes.skinWeight; for (let i = 0, s = t.count; i < s; i++) { e.fromBufferAttribute(t, i); const n = 1 / e.manhattanLength(); n !== 1 / 0 ? e.multiplyScalar(n) : e.set(1, 0, 0, 0), t.setXYZW(i, e.x, e.y, e.z, e.w); } } updateMatrixWorld(e) { super.updateMatrixWorld(e), this.bindMode === ll ? this.bindMatrixInverse.copy(this.matrixWorld).invert() : this.bindMode === mu ? this.bindMatrixInverse.copy(this.bindMatrix).invert() : Se("SkinnedMesh: Unrecognized bindMode: " + this.bindMode); } /** * Applies the bone transform associated with the given index to the given * vertex position. Returns the updated vector. * * @param {number} index - The vertex index. * @param {Vector3} target - The target object that is used to store the method's result. * the skinned mesh's world matrix will be used instead. * @return {Vector3} The updated vertex position. */ applyBoneTransform(e, t) { const i = this.skeleton, s = this.geometry; Ll.fromBufferAttribute(s.attributes.skinIndex, e), Il.fromBufferAttribute(s.attributes.skinWeight, e), Dl.copy(t).applyMatrix4(this.bindMatrix), t.set(0, 0, 0); for (let n = 0; n < 4; n++) { const a = Il.getComponent(n); if (a !== 0) { const o = Ll.getComponent(n); Ul.multiplyMatrices(i.bones[o].matrixWorld, i.boneInverses[o]), t.addScaledVector(xd.copy(Dl).applyMatrix4(Ul), a); } } return t.applyMatrix4(this.bindMatrixInverse); } } class hh extends dt { /** * Constructs a new bone. */ constructor() { super(), this.isBone = !0, this.type = "Bone"; } } class es extends Ct { /** * Constructs a new data texture. * * @param {?TypedArray} [data=null] - The buffer data. * @param {number} [width=1] - The width of the texture. * @param {number} [height=1] - The height of the texture. * @param {number} [format=RGBAFormat] - The texture format. * @param {number} [type=UnsignedByteType] - The texture type. * @param {number} [mapping=Texture.DEFAULT_MAPPING] - The texture mapping. * @param {number} [wrapS=ClampToEdgeWrapping] - The wrapS value. * @param {number} [wrapT=ClampToEdgeWrapping] - The wrapT value. * @param {number} [magFilter=NearestFilter] - The mag filter value. * @param {number} [minFilter=NearestFilter] - The min filter value. * @param {number} [anisotropy=Texture.DEFAULT_ANISOTROPY] - The anisotropy value. * @param {string} [colorSpace=NoColorSpace] - The color space. */ constructor(e = null, t = 1, i = 1, s, n, a, o, l, c = Dt, h = Dt, u, d) { super(null, a, o, l, c, h, s, n, u, d), this.isDataTexture = !0, this.image = { data: e, width: t, height: i }, this.generateMipmaps = !1, this.flipY = !1, this.unpackAlignment = 1; } } const Ol = /* @__PURE__ */ new Ue(), Md = /* @__PURE__ */ new Ue(); class Ho { /** * Constructs a new skeleton. * * @param {Array} [bones] - An array of bones. * @param {Array} [boneInverses] - An array of bone inverse matrices. * If not provided, these matrices will be computed automatically via {@link Skeleton#calculateInverses}. */ constructor(e = [], t = []) { this.uuid = di(), this.bones = e.slice(0), this.boneInverses = t, this.boneMatrices = null, this.boneTexture = null, this.init(); } /** * Initializes the skeleton. This method gets automatically called by the constructor * but depending on how the skeleton is created it might be necessary to call this method * manually. */ init() { const e = this.bones, t = this.boneInverses; if (this.boneMatrices = new Float32Array(e.length * 16), t.length === 0) this.calculateInverses(); else if (e.length !== t.length) { Se("Skeleton: Number of inverse bone matrices does not match amount of bones."), this.boneInverses = []; for (let i = 0, s = this.bones.length; i < s; i++) this.boneInverses.push(new Ue()); } } /** * Computes the bone inverse matrices. This method resets {@link Skeleton#boneInverses} * and fills it with new matrices. */ calculateInverses() { this.boneInverses.length = 0; for (let e = 0, t = this.bones.length; e < t; e++) { const i = new Ue(); this.bones[e] && i.copy(this.bones[e].matrixWorld).invert(), this.boneInverses.push(i); } } /** * Resets the skeleton to the base pose. */ pose() { for (let e = 0, t = this.bones.length; e < t; e++) { const i = this.bones[e]; i && i.matrixWorld.copy(this.boneInverses[e]).invert(); } for (let e = 0, t = this.bones.length; e < t; e++) { const i = this.bones[e]; i && (i.parent && i.parent.isBone ? (i.matrix.copy(i.parent.matrixWorld).invert(), i.matrix.multiply(i.matrixWorld)) : i.matrix.copy(i.matrixWorld), i.matrix.decompose(i.position, i.quaternion, i.scale)); } } /** * Resets the skeleton to the base pose. */ update() { const e = this.bones, t = this.boneInverses, i = this.boneMatrices, s = this.boneTexture; for (let n = 0, a = e.length; n < a; n++) { const o = e[n] ? e[n].matrixWorld : Md; Ol.multiplyMatrices(o, t[n]), Ol.toArray(i, n * 16); } s !== null && (s.needsUpdate = !0); } /** * Returns a new skeleton with copied values from this instance. * * @return {Skeleton} A clone of this instance. */ clone() { return new Ho(this.bones, this.boneInverses); } /** * Computes a data texture for passing bone data to the vertex shader. * * @return {Skeleton} A reference of this instance. */ computeBoneTexture() { let e = Math.sqrt(this.bones.length * 4); e = Math.ceil(e / 4) * 4, e = Math.max(e, 4); const t = new Float32Array(e * e * 4); t.set(this.boneMatrices); const i = new es(t, e, e, qt, Gt); return i.needsUpdate = !0, this.boneMatrices = t, this.boneTexture = i, this; } /** * Searches through the skeleton's bone array and returns the first with a * matching name. * * @param {string} name - The name of the bone. * @return {Bone|undefined} The found bone. `undefined` if no bone has been found. */ getBoneByName(e) { for (let t = 0, i = this.bones.length; t < i; t++) { const s = this.bones[t]; if (s.name === e) return s; } } /** * Frees the GPU-related resources allocated by this instance. Call this * method whenever this instance is no longer used in your app. */ dispose() { this.boneTexture !== null && (this.boneTexture.dispose(), this.boneTexture = null); } /** * Setups the skeleton by the given JSON and bones. * * @param {Object} json - The skeleton as serialized JSON. * @param {Object} bones - An array of bones. * @return {Skeleton} A reference of this instance. */ fromJSON(e, t) { this.uuid = e.uuid; for (let i = 0, s = e.bones.length; i < s; i++) { const n = e.bones[i]; let a = t[n]; a === void 0 && (Se("Skeleton: No bone found with UUID:", n), a = new hh()), this.bones.push(a), this.boneInverses.push(new Ue().fromArray(e.boneInverses[i])); } return this.init(), this; } /** * Serializes the skeleton into JSON. * * @return {Object} A JSON object representing the serialized skeleton. * @see {@link ObjectLoader#parse} */ toJSON() { const e = { metadata: { version: 4.7, type: "Skeleton", generator: "Skeleton.toJSON" }, bones: [], boneInverses: [] }; e.uuid = this.uuid; const t = this.bones, i = this.boneInverses; for (let s = 0, n = t.length; s < n; s++) { const a = t[s]; e.bones.push(a.uuid); const o = i[s]; e.boneInverses.push(o.toArray()); } return e; } } class fo extends zt { /** * Constructs a new instanced buffer attribute. * * @param {TypedArray} array - The array holding the attribute data. * @param {number} itemSize - The item size. * @param {boolean} [normalized=false] - Whether the data are normalized or not. * @param {number} [meshPerAttribute=1] - How often a value of this buffer attribute should be repeated. */ constructor(e, t, i, s = 1) { super(e, t, i), this.isInstancedBufferAttribute = !0, this.meshPerAttribute = s; } copy(e) { return super.copy(e), this.meshPerAttribute = e.meshPerAttribute, this; } toJSON() { const e = super.toJSON(); return e.meshPerAttribute = this.meshPerAttribute, e.isInstancedBufferAttribute = !0, e; } } const Dr = /* @__PURE__ */ new Ue(), Bl = /* @__PURE__ */ new Ue(), $s = [], Fl = /* @__PURE__ */ new Rt(), Sd = /* @__PURE__ */ new Ue(), cs = /* @__PURE__ */ new nt(), hs = /* @__PURE__ */ new Ci(); class bd extends nt { /** * Constructs a new instanced mesh. * * @param {BufferGeometry} [geometry] - The mesh geometry. * @param {Material|Array} [material] - The mesh material. * @param {number} count - The number of instances. */ constructor(e, t, i) { super(e, t), this.isInstancedMesh = !0, this.instanceMatrix = new fo(new Float32Array(i * 16), 16), this.instanceColor = null, this.morphTexture = null, this.count = i, this.boundingBox = null, this.boundingSphere = null; for (let s = 0; s < i; s++) this.setMatrixAt(s, Sd); } /** * Computes the bounding box of the instanced mesh, and updates {@link InstancedMesh#boundingBox}. * The bounding box is not automatically computed by the engine; this method must be called by your app. * You may need to recompute the bounding box if an instance is transformed via {@link InstancedMesh#setMatrixAt}. */ computeBoundingBox() { const e = this.geometry, t = this.count; this.boundingBox === null && (this.boundingBox = new Rt()), e.boundingBox === null && e.computeBoundingBox(), this.boundingBox.makeEmpty(); for (let i = 0; i < t; i++) this.getMatrixAt(i, Dr), Fl.copy(e.boundingBox).applyMatrix4(Dr), this.boundingBox.union(Fl); } /** * Computes the bounding sphere of the instanced mesh, and updates {@link InstancedMesh#boundingSphere} * The engine automatically computes the bounding sphere when it is needed, e.g., for ray casting or view frustum culling. * You may need to recompute the bounding sphere if an instance is transformed via {@link InstancedMesh#setMatrixAt}. */ computeBoundingSphere() { const e = this.geometry, t = this.count; this.boundingSphere === null && (this.boundingSphere = new Ci()), e.boundingSphere === null && e.computeBoundingSphere(), this.boundingSphere.makeEmpty(); for (let i = 0; i < t; i++) this.getMatrixAt(i, Dr), hs.copy(e.boundingSphere).applyMatrix4(Dr), this.boundingSphere.union(hs); } copy(e, t) { return super.copy(e, t), this.instanceMatrix.copy(e.instanceMatrix), e.morphTexture !== null && (this.morphTexture = e.morphTexture.clone()), e.instanceColor !== null && (this.instanceColor = e.instanceColor.clone()), this.count = e.count, e.boundingBox !== null && (this.boundingBox = e.boundingBox.clone()), e.boundingSphere !== null && (this.boundingSphere = e.boundingSphere.clone()), this; } /** * Gets the color of the defined instance. * * @param {number} index - The instance index. * @param {Color} color - The target object that is used to store the method's result. */ getColorAt(e, t) { t.fromArray(this.instanceColor.array, e * 3); } /** * Gets the local transformation matrix of the defined instance. * * @param {number} index - The instance index. * @param {Matrix4} matrix - The target object that is used to store the method's result. */ getMatrixAt(e, t) { t.fromArray(this.instanceMatrix.array, e * 16); } /** * Gets the morph target weights of the defined instance. * * @param {number} index - The instance index. * @param {Mesh} object - The target object that is used to store the method's result. */ getMorphAt(e, t) { const i = t.morphTargetInfluences, s = this.morphTexture.source.data.data, n = i.length + 1, a = e * n + 1; for (let o = 0; o < i.length; o++) i[o] = s[a + o]; } raycast(e, t) { const i = this.matrixWorld, s = this.count; if (cs.geometry = this.geometry, cs.material = this.material, cs.material !== void 0 && (this.boundingSphere === null && this.computeBoundingSphere(), hs.copy(this.boundingSphere), hs.applyMatrix4(i), e.ray.intersectsSphere(hs) !== !1)) for (let n = 0; n < s; n++) { this.getMatrixAt(n, Dr), Bl.multiplyMatrices(i, Dr), cs.matrixWorld = Bl, cs.raycast(e, $s); for (let a = 0, o = $s.length; a < o; a++) { const l = $s[a]; l.instanceId = n, l.object = this, t.push(l); } $s.length = 0; } } /** * Sets the given color to the defined instance. Make sure you set the `needsUpdate` flag of * {@link InstancedMesh#instanceColor} to `true` after updating all the colors. * * @param {number} index - The instance index. * @param {Color} color - The instance color. */ setColorAt(e, t) { this.instanceColor === null && (this.instanceColor = new fo(new Float32Array(this.instanceMatrix.count * 3).fill(1), 3)), t.toArray(this.instanceColor.array, e * 3); } /** * Sets the given local transformation matrix to the defined instance. Make sure you set the `needsUpdate` flag of * {@link InstancedMesh#instanceMatrix} to `true` after updating all the colors. * * @param {number} index - The instance index. * @param {Matrix4} matrix - The local transformation. */ setMatrixAt(e, t) { t.toArray(this.instanceMatrix.array, e * 16); } /** * Sets the morph target weights to the defined instance. Make sure you set the `needsUpdate` flag of * {@link InstancedMesh#morphTexture} to `true` after updating all the influences. * * @param {number} index - The instance index. * @param {Mesh} object - A mesh which `morphTargetInfluences` property containing the morph target weights * of a single instance. */ setMorphAt(e, t) { const i = t.morphTargetInfluences, s = i.length + 1; this.morphTexture === null && (this.morphTexture = new es(new Float32Array(s * this.count), s, this.count, Ao, Gt)); const n = this.morphTexture.source.data.data; let a = 0; for (let c = 0; c < i.length; c++) a += i[c]; const o = this.geometry.morphTargetsRelative ? 1 : 1 - a, l = s * e; n[l] = o, n.set(i, l + 1); } updateMorphTargets() { } /** * Frees the GPU-related resources allocated by this instance. Call this * method whenever this instance is no longer used in your app. */ dispose() { this.dispatchEvent({ type: "dispose" }), this.morphTexture !== null && (this.morphTexture.dispose(), this.morphTexture = null); } } const la = /* @__PURE__ */ new w(), Td = /* @__PURE__ */ new w(), Ed = /* @__PURE__ */ new Be(); class yi { /** * Constructs a new plane. * * @param {Vector3} [normal=(1,0,0)] - A unit length vector defining the normal of the plane. * @param {number} [constant=0] - The signed distance from the origin to the plane. */ constructor(e = new w(1, 0, 0), t = 0) { this.isPlane = !0, this.normal = e, this.constant = t; } /** * Sets the plane components by copying the given values. * * @param {Vector3} normal - The normal. * @param {number} constant - The constant. * @return {Plane} A reference to this plane. */ set(e, t) { return this.normal.copy(e), this.constant = t, this; } /** * Sets the plane components by defining `x`, `y`, `z` as the * plane normal and `w` as the constant. * * @param {number} x - The value for the normal's x component. * @param {number} y - The value for the normal's y component. * @param {number} z - The value for the normal's z component. * @param {number} w - The constant value. * @return {Plane} A reference to this plane. */ setComponents(e, t, i, s) { return this.normal.set(e, t, i), 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(e, t) { return this.normal.copy(e), this.constant = -t.dot(this.normal), this; } /** * Sets the plane from three coplanar points. The winding order is * assumed to be counter-clockwise, and determines the direction of * the plane normal. * * @param {Vector3} a - The first coplanar point. * @param {Vector3} b - The second coplanar point. * @param {Vector3} c - The third coplanar point. * @return {Plane} A reference to this plane. */ setFromCoplanarPoints(e, t, i) { const s = la.subVectors(i, t).cross(Td.subVectors(e, t)).normalize(); return this.setFromNormalAndCoplanarPoint(s, e), this; } /** * Copies the values of the given plane to this instance. * * @param {Plane} plane - The plane to copy. * @return {Plane} A reference to this plane. */ copy(e) { return this.normal.copy(e.normal), this.constant = e.constant, this; } /** * Normalizes the plane normal and adjusts the constant accordingly. * * @return {Plane} A reference to this plane. */ normalize() { const e = 1 / this.normal.length(); return this.normal.multiplyScalar(e), this.constant *= e, this; } /** * Negates both the plane normal and the constant. * * @return {Plane} A reference to this plane. */ negate() { return this.constant *= -1, this.normal.negate(), this; } /** * Returns the signed distance from the given point to this plane. * * @param {Vector3} point - The point to compute the distance for. * @return {number} The signed distance. */ distanceToPoint(e) { return this.normal.dot(e) + this.constant; } /** * Returns the signed distance from the given sphere to this plane. * * @param {Sphere} sphere - The sphere to compute the distance for. * @return {number} The signed distance. */ distanceToSphere(e) { return this.distanceToPoint(e.center) - e.radius; } /** * Projects a the given point onto the plane. * * @param {Vector3} point - The point to project. * @param {Vector3} target - The target vector that is used to store the method's result. * @return {Vector3} The projected point on the plane. */ projectPoint(e, t) { return t.copy(e).addScaledVector(this.normal, -this.distanceToPoint(e)); } /** * Returns the intersection point of the passed line and the plane. Returns * `null` if the line does not intersect. Returns the line's starting point if * the line is coplanar with the plane. * * @param {Line3} line - The line to compute the intersection for. * @param {Vector3} target - The target vector that is used to store the method's result. * @return {?Vector3} The intersection point. */ intersectLine(e, t) { const i = e.delta(la), s = this.normal.dot(i); if (s === 0) return this.distanceToPoint(e.start) === 0 ? t.copy(e.start) : null; const n = -(e.start.dot(this.normal) + this.constant) / s; return n < 0 || n > 1 ? null : t.copy(e.start).addScaledVector(i, n); } /** * Returns `true` if the given line segment intersects with (passes through) the plane. * * @param {Line3} line - The line to test. * @return {boolean} Whether the given line segment intersects with the plane or not. */ intersectsLine(e) { const t = this.distanceToPoint(e.start), i = this.distanceToPoint(e.end); return t < 0 && i > 0 || i < 0 && t > 0; } /** * Returns `true` if the given bounding box intersects with the plane. * * @param {Box3} box - The bounding box to test. * @return {boolean} Whether the given bounding box intersects with the plane or not. */ intersectsBox(e) { return e.intersectsPlane(this); } /** * Returns `true` if the given bounding sphere intersects with the plane. * * @param {Sphere} sphere - The bounding sphere to test. * @return {boolean} Whether the given bounding sphere intersects with the plane or not. */ intersectsSphere(e) { return e.intersectsPlane(this); } /** * Returns a coplanar vector to the plane, by calculating the * projection of the normal at the origin onto the plane. * * @param {Vector3} target - The target vector that is used to store the method's result. * @return {Vector3} The coplanar point. */ coplanarPoint(e) { return e.copy(this.normal).multiplyScalar(-this.constant); } /** * Apply a 4x4 matrix to the plane. The matrix must be an affine, homogeneous transform. * * The optional normal matrix can be pre-computed like so: * ```js * const optionalNormalMatrix = new THREE.Matrix3().getNormalMatrix( matrix ); * ``` * * @param {Matrix4} matrix - The transformation matrix. * @param {Matrix4} [optionalNormalMatrix] - A pre-computed normal matrix. * @return {Plane} A reference to this plane. */ applyMatrix4(e, t) { const i = t || Ed.getNormalMatrix(e), s = this.coplanarPoint(la).applyMatrix4(e), n = this.normal.applyMatrix3(i).normalize(); return this.constant = -s.dot(n), this; } /** * Translates the plane by the distance defined by the given offset vector. * Note that this only affects the plane constant and will not affect the normal vector. * * @param {Vector3} offset - The offset vector. * @return {Plane} A reference to this plane. */ translate(e) { return this.constant -= e.dot(this.normal), this; } /** * Returns `true` if this plane is equal with the given one. * * @param {Plane} plane - The plane to test for equality. * @return {boolean} Whether this plane is equal with the given one. */ equals(e) { return e.normal.equals(this.normal) && e.constant === this.constant; } /** * Returns a new plane with copied values from this instance. * * @return {Plane} A clone of this instance. */ clone() { return new this.constructor().copy(this); } } const or = /* @__PURE__ */ new Ci(), wd = /* @__PURE__ */ new oe(0.5, 0.5), Qs = /* @__PURE__ */ new w(); class Vo { /** * Constructs a new frustum. * * @param {Plane} [p0] - The first plane that encloses the frustum. * @param {Plane} [p1] - The second plane that encloses the frustum. * @param {Plane} [p2] - The third plane that encloses the frustum. * @param {Plane} [p3] - The fourth plane that encloses the frustum. * @param {Plane} [p4] - The fifth plane that encloses the frustum. * @param {Plane} [p5] - The sixth plane that encloses the frustum. */ constructor(e = new yi(), t = new yi(), i = new yi(), s = new yi(), n = new yi(), a = new yi()) { this.planes = [e, t, i, s, n, a]; } /** * Sets the frustum planes by copying the given planes. * * @param {Plane} [p0] - The first plane that encloses the frustum. * @param {Plane} [p1] - The second plane that encloses the frustum. * @param {Plane} [p2] - The third plane that encloses the frustum. * @param {Plane} [p3] - The fourth plane that encloses the frustum. * @param {Plane} [p4] - The fifth plane that encloses the frustum. * @param {Plane} [p5] - The sixth plane that encloses the frustum. * @return {Frustum} A reference to this frustum. */ set(e, t, i, s, n, a) { const o = this.planes; return o[0].copy(e), o[1].copy(t), o[2].copy(i), o[3].copy(s), o[4].copy(n), o[5].copy(a), this; } /** * Copies the values of the given frustum to this instance. * * @param {Frustum} frustum - The frustum to copy. * @return {Frustum} A reference to this frustum. */ copy(e) { const t = this.planes; for (let i = 0; i < 6; i++) t[i].copy(e.planes[i]); return this; } /** * Sets the frustum planes from the given projection matrix. * * @param {Matrix4} m - The projection matrix. * @param {(WebGLCoordinateSystem|WebGPUCoordinateSystem)} coordinateSystem - The coordinate system. * @param {boolean} [reversedDepth=false] - Whether to use a reversed depth. * @return {Frustum} A reference to this frustum. */ setFromProjectionMatrix(e, t = bi, i = !1) { const s = this.planes, n = e.elements, a = n[0], o = n[1], l = n[2], c = n[3], h = n[4], u = n[5], d = n[6], f = n[7], g = n[8], v = n[9], m = n[10], p = n[11], y = n[12], _ = n[13], E = n[14], A = n[15]; if (s[0].setComponents(c - a, f - h, p - g, A - y).normalize(), s[1].setComponents(c + a, f + h, p + g, A + y).normalize(), s[2].setComponents(c + o, f + u, p + v, A + _).normalize(), s[3].setComponents(c - o, f - u, p - v, A - _).normalize(), i) s[4].setComponents(l, d, m, E).normalize(), s[5].setComponents(c - l, f - d, p - m, A - E).normalize(); else if (s[4].setComponents(c - l, f - d, p - m, A - E).normalize(), t === bi) s[5].setComponents(c + l, f + d, p + m, A + E).normalize(); else if (t === Tn) s[5].setComponents(l, d, m, E).normalize(); else throw new Error("THREE.Frustum.setFromProjectionMatrix(): Invalid coordinate system: " + t); return this; } /** * Returns `true` if the 3D object's bounding sphere is intersecting this frustum. * * Note that the 3D object must have a geometry so that the bounding sphere can be calculated. * * @param {Object3D} object - The 3D object to test. * @return {boolean} Whether the 3D object's bounding sphere is intersecting this frustum or not. */ intersectsObject(e) { if (e.boundingSphere !== void 0) e.boundingSphere === null && e.computeBoundingSphere(), or.copy(e.boundingSphere).applyMatrix4(e.matrixWorld); else { const t = e.geometry; t.boundingSphere === null && t.computeBoundingSphere(), or.copy(t.boundingSphere).applyMatrix4(e.matrixWorld); } return this.intersectsSphere(or); } /** * Returns `true` if the given sprite is intersecting this frustum. * * @param {Sprite} sprite - The sprite to test. * @return {boolean} Whether the sprite is intersecting this frustum or not. */ intersectsSprite(e) { or.center.set(0, 0, 0); const t = wd.distanceTo(e.center); return or.radius = 0.7071067811865476 + t, or.applyMatrix4(e.matrixWorld), this.intersectsSphere(or); } /** * Returns `true` if the given bounding sphere is intersecting this frustum. * * @param {Sphere} sphere - The bounding sphere to test. * @return {boolean} Whether the bounding sphere is intersecting this frustum or not. */ intersectsSphere(e) { const t = this.planes, i = e.center, s = -e.radius; for (let n = 0; n < 6; n++) if (t[n].distanceToPoint(i) < 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(e) { const t = this.planes; for (let i = 0; i < 6; i++) { const s = t[i]; if (Qs.x = s.normal.x > 0 ? e.max.x : e.min.x, Qs.y = s.normal.y > 0 ? e.max.y : e.min.y, Qs.z = s.normal.z > 0 ? e.max.z : e.min.z, s.distanceToPoint(Qs) < 0) return !1; } return !0; } /** * Returns `true` if the given point lies within the frustum. * * @param {Vector3} point - The point to test. * @return {boolean} Whether the point lies within this frustum or not. */ containsPoint(e) { const t = this.planes; for (let i = 0; i < 6; i++) if (t[i].distanceToPoint(e) < 0) return !1; return !0; } /** * Returns a new frustum with copied values from this instance. * * @return {Frustum} A clone of this instance. */ clone() { return new this.constructor().copy(this); } } class uh extends $t { /** * Constructs a new line basic material. * * @param {Object} [parameters] - An object with one or more properties * defining the material's appearance. Any property of the material * (including any property from inherited materials) can be passed * in here. Color values can be passed any type of value accepted * by {@link Color#set}. */ constructor(e) { super(), this.isLineBasicMaterial = !0, this.type = "LineBasicMaterial", this.color = new _e(16777215), this.map = null, this.linewidth = 1, this.linecap = "round", this.linejoin = "round", this.fog = !0, this.setValues(e); } copy(e) { return super.copy(e), this.color.copy(e.color), this.map = e.map, this.linewidth = e.linewidth, this.linecap = e.linecap, this.linejoin = e.linejoin, this.fog = e.fog, this; } } const wn = /* @__PURE__ */ new w(), Cn = /* @__PURE__ */ new w(), zl = /* @__PURE__ */ new Ue(), us = /* @__PURE__ */ new Qr(), en = /* @__PURE__ */ new Ci(), ca = /* @__PURE__ */ new w(), kl = /* @__PURE__ */ new w(); class Go extends dt { /** * Constructs a new line. * * @param {BufferGeometry} [geometry] - The line geometry. * @param {Material|Array} [material] - The line material. */ constructor(e = new Qt(), t = new uh()) { super(), this.isLine = !0, this.type = "Line", this.geometry = e, this.material = t, this.morphTargetDictionary = void 0, this.morphTargetInfluences = void 0, this.updateMorphTargets(); } copy(e, t) { return super.copy(e, t), this.material = Array.isArray(e.material) ? e.material.slice() : e.material, this.geometry = e.geometry, this; } /** * Computes an array of distance values which are necessary for rendering dashed lines. * For each vertex in the geometry, the method calculates the cumulative length from the * current point to the very beginning of the line. * * @return {Line} A reference to this line. */ computeLineDistances() { const e = this.geometry; if (e.index === null) { const t = e.attributes.position, i = [0]; for (let s = 1, n = t.count; s < n; s++) wn.fromBufferAttribute(t, s - 1), Cn.fromBufferAttribute(t, s), i[s] = i[s - 1], i[s] += wn.distanceTo(Cn); e.setAttribute("lineDistance", new pi(i, 1)); } else Se("Line.computeLineDistances(): Computation only possible with non-indexed BufferGeometry."); return this; } /** * Computes intersection points between a casted ray and this line. * * @param {Raycaster} raycaster - The raycaster. * @param {Array} intersects - The target array that holds the intersection points. */ raycast(e, t) { const i = this.geometry, s = this.matrixWorld, n = e.params.Line.threshold, a = i.drawRange; if (i.boundingSphere === null && i.computeBoundingSphere(), en.copy(i.boundingSphere), en.applyMatrix4(s), en.radius += n, e.ray.intersectsSphere(en) === !1) return; zl.copy(s).invert(), us.copy(e.ray).applyMatrix4(zl); const o = n / ((this.scale.x + this.scale.y + this.scale.z) / 3), l = o * o, c = this.isLineSegments ? 2 : 1, h = i.index, u = i.attributes.position; if (h !== null) { const d = Math.max(0, a.start), f = Math.min(h.count, a.start + a.count); for (let g = d, v = f - 1; g < v; g += c) { const m = h.getX(g), p = h.getX(g + 1), y = tn(this, e, us, l, m, p, g); y && t.push(y); } if (this.isLineLoop) { const g = h.getX(f - 1), v = h.getX(d), m = tn(this, e, us, l, g, v, f - 1); m && t.push(m); } } else { const d = Math.max(0, a.start), f = Math.min(u.count, a.start + a.count); for (let g = d, v = f - 1; g < v; g += c) { const m = tn(this, e, us, l, g, g + 1, g); m && t.push(m); } if (this.isLineLoop) { const g = tn(this, e, us, l, f - 1, d, f - 1); g && t.push(g); } } } /** * Sets the values of {@link Line#morphTargetDictionary} and {@link Line#morphTargetInfluences} * to make sure existing morph targets can influence this 3D object. */ updateMorphTargets() { const e = this.geometry.morphAttributes, t = Object.keys(e); if (t.length > 0) { const i = e[t[0]]; if (i !== void 0) { this.morphTargetInfluences = [], this.morphTargetDictionary = {}; for (let s = 0, n = i.length; s < n; s++) { const a = i[s].name || String(s); this.morphTargetInfluences.push(0), this.morphTargetDictionary[a] = s; } } } } } function tn(r, e, t, i, s, n, a) { const o = r.geometry.attributes.position; if (wn.fromBufferAttribute(o, s), Cn.fromBufferAttribute(o, n), t.distanceSqToSegment(wn, Cn, ca, kl) > i) return; ca.applyMatrix4(r.matrixWorld); const l = e.ray.origin.distanceTo(ca); if (!(l < e.near || l > e.far)) return { distance: l, // What do we want? intersection point on the ray or on the segment?? // point: raycaster.ray.at( distance ), point: kl.clone().applyMatrix4(r.matrixWorld), index: a, face: null, faceIndex: null, barycoord: null, object: r }; } const Hl = /* @__PURE__ */ new w(), Vl = /* @__PURE__ */ new w(); class Cd extends Go { /** * Constructs a new line segments. * * @param {BufferGeometry} [geometry] - The line geometry. * @param {Material|Array} [material] - The line material. */ constructor(e, t) { super(e, t), this.isLineSegments = !0, this.type = "LineSegments"; } computeLineDistances() { const e = this.geometry; if (e.index === null) { const t = e.attributes.position, i = []; for (let s = 0, n = t.count; s < n; s += 2) Hl.fromBufferAttribute(t, s), Vl.fromBufferAttribute(t, s + 1), i[s] = s === 0 ? 0 : i[s - 1], i[s + 1] = i[s] + Hl.distanceTo(Vl); e.setAttribute("lineDistance", new pi(i, 1)); } else Se("LineSegments.computeLineDistances(): Computation only possible with non-indexed BufferGeometry."); return this; } } class Rd extends Go { /** * Constructs a new line loop. * * @param {BufferGeometry} [geometry] - The line geometry. * @param {Material|Array} [material] - The line material. */ constructor(e, t) { super(e, t), this.isLineLoop = !0, this.type = "LineLoop"; } } class dh extends $t { /** * Constructs a new points material. * * @param {Object} [parameters] - An object with one or more properties * defining the material's appearance. Any property of the material * (including any property from inherited materials) can be passed * in here. Color values can be passed any type of value accepted * by {@link Color#set}. */ constructor(e) { super(), this.isPointsMaterial = !0, this.type = "PointsMaterial", this.color = new _e(16777215), this.map = null, this.alphaMap = null, this.size = 1, this.sizeAttenuation = !0, this.fog = !0, this.setValues(e); } copy(e) { return super.copy(e), this.color.copy(e.color), this.map = e.map, this.alphaMap = e.alphaMap, this.size = e.size, this.sizeAttenuation = e.sizeAttenuation, this.fog = e.fog, this; } } const Gl = /* @__PURE__ */ new Ue(), mo = /* @__PURE__ */ new Qr(), rn = /* @__PURE__ */ new Ci(), sn = /* @__PURE__ */ new w(); class Ad extends dt { /** * Constructs a new point cloud. * * @param {BufferGeometry} [geometry] - The points geometry. * @param {Material|Array} [material] - The points material. */ constructor(e = new Qt(), t = new dh()) { super(), this.isPoints = !0, this.type = "Points", this.geometry = e, this.material = t, this.morphTargetDictionary = void 0, this.morphTargetInfluences = void 0, this.updateMorphTargets(); } copy(e, t) { return super.copy(e, t), this.material = Array.isArray(e.material) ? e.material.slice() : e.material, this.geometry = e.geometry, this; } /** * Computes intersection points between a casted ray and this point cloud. * * @param {Raycaster} raycaster - The raycaster. * @param {Array} intersects - The target array that holds the intersection points. */ raycast(e, t) { const i = this.geometry, s = this.matrixWorld, n = e.params.Points.threshold, a = i.drawRange; if (i.boundingSphere === null && i.computeBoundingSphere(), rn.copy(i.boundingSphere), rn.applyMatrix4(s), rn.radius += n, e.ray.intersectsSphere(rn) === !1) return; Gl.copy(s).invert(), mo.copy(e.ray).applyMatrix4(Gl); const o = n / ((this.scale.x + this.scale.y + this.scale.z) / 3), l = o * o, c = i.index, h = i.attributes.position; if (c !== null) { const u = Math.max(0, a.start), d = Math.min(c.count, a.start + a.count); for (let f = u, g = d; f < g; f++) { const v = c.getX(f); sn.fromBufferAttribute(h, v), Wl(sn, v, l, s, e, t, this); } } else { const u = Math.max(0, a.start), d = Math.min(h.count, a.start + a.count); for (let f = u, g = d; f < g; f++) sn.fromBufferAttribute(h, f), Wl(sn, f, l, s, e, t, this); } } /** * Sets the values of {@link Points#morphTargetDictionary} and {@link Points#morphTargetInfluences} * to make sure existing morph targets can influence this 3D object. */ updateMorphTargets() { const e = this.geometry.morphAttributes, t = Object.keys(e); if (t.length > 0) { const i = e[t[0]]; if (i !== void 0) { this.morphTargetInfluences = [], this.morphTargetDictionary = {}; for (let s = 0, n = i.length; s < n; s++) { const a = i[s].name || String(s); this.morphTargetInfluences.push(0), this.morphTargetDictionary[a] = s; } } } } } function Wl(r, e, t, i, s, n, a) { const o = mo.distanceSqToPoint(r); if (o < t) { const l = new w(); mo.closestPointToPoint(r, l), l.applyMatrix4(i); const c = s.ray.origin.distanceTo(l); if (c < s.near || c > s.far) return; n.push({ distance: c, distanceToRay: Math.sqrt(o), point: l, index: e, face: null, faceIndex: null, barycoord: null, object: a }); } } class Wo extends Ct { /** * Constructs a new depth texture. * * @param {number} width - The width of the texture. * @param {number} height - The height of the texture. * @param {number} [type=UnsignedIntType] - The texture type. * @param {number} [mapping=Texture.DEFAULT_MAPPING] - The texture mapping. * @param {number} [wrapS=ClampToEdgeWrapping] - The wrapS value. * @param {number} [wrapT=ClampToEdgeWrapping] - The wrapT value. * @param {number} [magFilter=LinearFilter] - The mag filter value. * @param {number} [minFilter=LinearFilter] - The min filter value. * @param {number} [anisotropy=Texture.DEFAULT_ANISOTROPY] - The anisotropy value. * @param {number} [format=DepthFormat] - The texture format. * @param {number} [depth=1] - The depth of the texture. */ constructor(e, t, i = pr, s, n, a, o = Dt, l = Dt, c, h = bs, u = 1) { if (h !== bs && h !== Xr) throw new Error("DepthTexture format must be either THREE.DepthFormat or THREE.DepthStencilFormat"); const d = { width: e, height: t, depth: u }; super(d, s, n, a, o, l, h, i, c), this.isDepthTexture = !0, this.flipY = !1, this.generateMipmaps = !1, this.compareFunction = null; } copy(e) { return super.copy(e), this.source = new Oo(Object.assign({}, e.image)), this.compareFunction = e.compareFunction, this; } toJSON(e) { const t = super.toJSON(e); return this.compareFunction !== null && (t.compareFunction = this.compareFunction), t; } } class ph extends Ct { /** * Creates a new raw texture. * * @param {?(WebGLTexture|GPUTexture)} [sourceTexture=null] - The external texture. */ constructor(e = null) { super(), this.sourceTexture = e, this.isExternalTexture = !0; } copy(e) { return super.copy(e), this.sourceTexture = e.sourceTexture, this; } } class Rs extends Qt { /** * Constructs a new plane geometry. * * @param {number} [width=1] - The width along the X axis. * @param {number} [height=1] - The height along the Y axis * @param {number} [widthSegments=1] - The number of segments along the X axis. * @param {number} [heightSegments=1] - The number of segments along the Y axis. */ constructor(e = 1, t = 1, i = 1, s = 1) { super(), this.type = "PlaneGeometry", this.parameters = { width: e, height: t, widthSegments: i, heightSegments: s }; const n = e / 2, a = t / 2, o = Math.floor(i), l = Math.floor(s), c = o + 1, h = l + 1, u = e / o, d = t / l, f = [], g = [], v = [], m = []; for (let p = 0; p < h; p++) { const y = p * d - a; for (let _ = 0; _ < c; _++) { const E = _ * u - n; g.push(E, -y, 0), v.push(0, 0, 1), m.push(_ / o), m.push(1 - p / l); } } for (let p = 0; p < l; p++) for (let y = 0; y < o; y++) { const _ = y + c * p, E = y + c * (p + 1), A = y + 1 + c * (p + 1), T = y + 1 + c * p; f.push(_, E, T), f.push(E, A, T); } this.setIndex(f), this.setAttribute("position", new pi(g, 3)), this.setAttribute("normal", new pi(v, 3)), this.setAttribute("uv", new pi(m, 2)); } copy(e) { return super.copy(e), this.parameters = Object.assign({}, e.parameters), this; } /** * Factory method for creating an instance of this class from the given * JSON object. * * @param {Object} data - A JSON object representing the serialized geometry. * @return {PlaneGeometry} A new instance. */ static fromJSON(e) { return new Rs(e.width, e.height, e.widthSegments, e.heightSegments); } } class Pd extends ct { /** * Constructs a new raw shader material. * * @param {Object} [parameters] - An object with one or more properties * defining the material's appearance. Any property of the material * (including any property from inherited materials) can be passed * in here. Color values can be passed any type of value accepted * by {@link Color#set}. */ constructor(e) { super(e), this.isRawShaderMaterial = !0, this.type = "RawShaderMaterial"; } } class jo extends $t { /** * Constructs a new mesh standard material. * * @param {Object} [parameters] - An object with one or more properties * defining the material's appearance. Any property of the material * (including any property from inherited materials) can be passed * in here. Color values can be passed any type of value accepted * by {@link Color#set}. */ constructor(e) { super(), this.isMeshStandardMaterial = !0, this.type = "MeshStandardMaterial", this.defines = { STANDARD: "" }, this.color = new _e(16777215), this.roughness = 1, this.metalness = 0, this.map = null, this.lightMap = null, this.lightMapIntensity = 1, this.aoMap = null, this.aoMapIntensity = 1, this.emissive = new _e(0), this.emissiveIntensity = 1, this.emissiveMap = null, this.bumpMap = null, this.bumpScale = 1, this.normalMap = null, this.normalMapType = Dn, this.normalScale = new oe(1, 1), this.displacementMap = null, this.displacementScale = 1, this.displacementBias = 0, this.roughnessMap = null, this.metalnessMap = null, this.alphaMap = null, this.envMap = null, this.envMapRotation = new gi(), this.envMapIntensity = 1, this.wireframe = !1, this.wireframeLinewidth = 1, this.wireframeLinecap = "round", this.wireframeLinejoin = "round", this.flatShading = !1, this.fog = !0, this.setValues(e); } copy(e) { return super.copy(e), this.defines = { STANDARD: "" }, this.color.copy(e.color), this.roughness = e.roughness, this.metalness = e.metalness, this.map = e.map, this.lightMap = e.lightMap, this.lightMapIntensity = e.lightMapIntensity, this.aoMap = e.aoMap, this.aoMapIntensity = e.aoMapIntensity, this.emissive.copy(e.emissive), this.emissiveMap = e.emissiveMap, this.emissiveIntensity = e.emissiveIntensity, this.bumpMap = e.bumpMap, this.bumpScale = e.bumpScale, this.normalMap = e.normalMap, this.normalMapType = e.normalMapType, this.normalScale.copy(e.normalScale), this.displacementMap = e.displacementMap, this.displacementScale = e.displacementScale, this.displacementBias = e.displacementBias, this.roughnessMap = e.roughnessMap, this.metalnessMap = e.metalnessMap, this.alphaMap = e.alphaMap, this.envMap = e.envMap, this.envMapRotation.copy(e.envMapRotation), this.envMapIntensity = e.envMapIntensity, this.wireframe = e.wireframe, this.wireframeLinewidth = e.wireframeLinewidth, this.wireframeLinecap = e.wireframeLinecap, this.wireframeLinejoin = e.wireframeLinejoin, this.flatShading = e.flatShading, this.fog = e.fog, this; } } class Ri extends jo { /** * Constructs a new mesh physical material. * * @param {Object} [parameters] - An object with one or more properties * defining the material's appearance. Any property of the material * (including any property from inherited materials) can be passed * in here. Color values can be passed any type of value accepted * by {@link Color#set}. */ constructor(e) { super(), this.isMeshPhysicalMaterial = !0, this.defines = { STANDARD: "", PHYSICAL: "" }, this.type = "MeshPhysicalMaterial", this.anisotropyRotation = 0, this.anisotropyMap = null, this.clearcoatMap = null, this.clearcoatRoughness = 0, this.clearcoatRoughnessMap = null, this.clearcoatNormalScale = new oe(1, 1), this.clearcoatNormalMap = null, this.ior = 1.5, Object.defineProperty(this, "reflectivity", { get: function() { return ze(2.5 * (this.ior - 1) / (this.ior + 1), 0, 1); }, set: function(t) { this.ior = (1 + 0.4 * t) / (1 - 0.4 * t); } }), this.iridescenceMap = null, this.iridescenceIOR = 1.3, this.iridescenceThicknessRange = [100, 400], this.iridescenceThicknessMap = null, this.sheenColor = new _e(0), this.sheenColorMap = null, this.sheenRoughness = 1, this.sheenRoughnessMap = null, this.transmissionMap = null, this.thickness = 0, this.thicknessMap = null, this.attenuationDistance = 1 / 0, this.attenuationColor = new _e(1, 1, 1), this.specularIntensity = 1, this.specularIntensityMap = null, this.specularColor = new _e(1, 1, 1), this.specularColorMap = null, this._anisotropy = 0, this._clearcoat = 0, this._dispersion = 0, this._iridescence = 0, this._sheen = 0, this._transmission = 0, this.setValues(e); } /** * The anisotropy strength, from `0.0` to `1.0`. * * @type {number} * @default 0 */ get anisotropy() { return this._anisotropy; } set anisotropy(e) { this._anisotropy > 0 != e > 0 && this.version++, this._anisotropy = e; } /** * Represents the intensity of the clear coat layer, from `0.0` to `1.0`. Use * clear coat related properties to enable multilayer materials that have a * thin translucent layer over the base layer. * * @type {number} * @default 0 */ get clearcoat() { return this._clearcoat; } set clearcoat(e) { this._clearcoat > 0 != e > 0 && this.version++, this._clearcoat = e; } /** * The intensity of the iridescence layer, simulating RGB color shift based on the angle between * the surface and the viewer, from `0.0` to `1.0`. * * @type {number} * @default 0 */ get iridescence() { return this._iridescence; } set iridescence(e) { this._iridescence > 0 != e > 0 && this.version++, this._iridescence = e; } /** * Defines the strength of the angular separation of colors (chromatic aberration) transmitting * through a relatively clear volume. Any value zero or larger is valid, the typical range of * realistic values is `[0, 1]`. This property can be only be used with transmissive objects. * * @type {number} * @default 0 */ get dispersion() { return this._dispersion; } set dispersion(e) { this._dispersion > 0 != e > 0 && this.version++, this._dispersion = e; } /** * The intensity of the sheen layer, from `0.0` to `1.0`. * * @type {number} * @default 0 */ get sheen() { return this._sheen; } set sheen(e) { this._sheen > 0 != e > 0 && this.version++, this._sheen = e; } /** * Degree of transmission (or optical transparency), from `0.0` to `1.0`. * * Thin, transparent or semitransparent, plastic or glass materials remain * largely reflective even if they are fully transmissive. The transmission * property can be used to model these materials. * * When transmission is non-zero, `opacity` should be set to `1`. * * @type {number} * @default 0 */ get transmission() { return this._transmission; } set transmission(e) { this._transmission > 0 != e > 0 && this.version++, this._transmission = e; } copy(e) { return super.copy(e), this.defines = { STANDARD: "", PHYSICAL: "" }, this.anisotropy = e.anisotropy, this.anisotropyRotation = e.anisotropyRotation, this.anisotropyMap = e.anisotropyMap, this.clearcoat = e.clearcoat, this.clearcoatMap = e.clearcoatMap, this.clearcoatRoughness = e.clearcoatRoughness, this.clearcoatRoughnessMap = e.clearcoatRoughnessMap, this.clearcoatNormalMap = e.clearcoatNormalMap, this.clearcoatNormalScale.copy(e.clearcoatNormalScale), this.dispersion = e.dispersion, this.ior = e.ior, this.iridescence = e.iridescence, this.iridescenceMap = e.iridescenceMap, this.iridescenceIOR = e.iridescenceIOR, this.iridescenceThicknessRange = [...e.iridescenceThicknessRange], this.iridescenceThicknessMap = e.iridescenceThicknessMap, this.sheen = e.sheen, this.sheenColor.copy(e.sheenColor), this.sheenColorMap = e.sheenColorMap, this.sheenRoughness = e.sheenRoughness, this.sheenRoughnessMap = e.sheenRoughnessMap, this.transmission = e.transmission, this.transmissionMap = e.transmissionMap, this.thickness = e.thickness, this.thicknessMap = e.thicknessMap, this.attenuationDistance = e.attenuationDistance, this.attenuationColor.copy(e.attenuationColor), this.specularIntensity = e.specularIntensity, this.specularIntensityMap = e.specularIntensityMap, this.specularColor.copy(e.specularColor), this.specularColorMap = e.specularColorMap, this; } } class Dd extends $t { /** * Constructs a new mesh normal material. * * @param {Object} [parameters] - An object with one or more properties * defining the material's appearance. Any property of the material * (including any property from inherited materials) can be passed * in here. Color values can be passed any type of value accepted * by {@link Color#set}. */ constructor(e) { super(), this.isMeshNormalMaterial = !0, this.type = "MeshNormalMaterial", this.bumpMap = null, this.bumpScale = 1, this.normalMap = null, this.normalMapType = Dn, this.normalScale = new oe(1, 1), this.displacementMap = null, this.displacementScale = 1, this.displacementBias = 0, this.wireframe = !1, this.wireframeLinewidth = 1, this.flatShading = !1, this.setValues(e); } copy(e) { return super.copy(e), this.bumpMap = e.bumpMap, this.bumpScale = e.bumpScale, this.normalMap = e.normalMap, this.normalMapType = e.normalMapType, this.normalScale.copy(e.normalScale), this.displacementMap = e.displacementMap, this.displacementScale = e.displacementScale, this.displacementBias = e.displacementBias, this.wireframe = e.wireframe, this.wireframeLinewidth = e.wireframeLinewidth, this.flatShading = e.flatShading, this; } } class Ld extends $t { /** * Constructs a new mesh lambert material. * * @param {Object} [parameters] - An object with one or more properties * defining the material's appearance. Any property of the material * (including any property from inherited materials) can be passed * in here. Color values can be passed any type of value accepted * by {@link Color#set}. */ constructor(e) { super(), this.isMeshLambertMaterial = !0, this.type = "MeshLambertMaterial", this.color = new _e(16777215), this.map = null, this.lightMap = null, this.lightMapIntensity = 1, this.aoMap = null, this.aoMapIntensity = 1, this.emissive = new _e(0), this.emissiveIntensity = 1, this.emissiveMap = null, this.bumpMap = null, this.bumpScale = 1, this.normalMap = null, this.normalMapType = Dn, this.normalScale = new oe(1, 1), this.displacementMap = null, this.displacementScale = 1, this.displacementBias = 0, this.specularMap = null, this.alphaMap = null, this.envMap = null, this.envMapRotation = new gi(), this.combine = To, this.reflectivity = 1, this.refractionRatio = 0.98, this.wireframe = !1, this.wireframeLinewidth = 1, this.wireframeLinecap = "round", this.wireframeLinejoin = "round", this.flatShading = !1, this.fog = !0, this.setValues(e); } copy(e) { return super.copy(e), this.color.copy(e.color), this.map = e.map, this.lightMap = e.lightMap, this.lightMapIntensity = e.lightMapIntensity, this.aoMap = e.aoMap, this.aoMapIntensity = e.aoMapIntensity, this.emissive.copy(e.emissive), this.emissiveMap = e.emissiveMap, this.emissiveIntensity = e.emissiveIntensity, this.bumpMap = e.bumpMap, this.bumpScale = e.bumpScale, this.normalMap = e.normalMap, this.normalMapType = e.normalMapType, this.normalScale.copy(e.normalScale), this.displacementMap = e.displacementMap, this.displacementScale = e.displacementScale, this.displacementBias = e.displacementBias, this.specularMap = e.specularMap, this.alphaMap = e.alphaMap, this.envMap = e.envMap, this.envMapRotation.copy(e.envMapRotation), this.combine = e.combine, this.reflectivity = e.reflectivity, this.refractionRatio = e.refractionRatio, this.wireframe = e.wireframe, this.wireframeLinewidth = e.wireframeLinewidth, this.wireframeLinecap = e.wireframeLinecap, this.wireframeLinejoin = e.wireframeLinejoin, this.flatShading = e.flatShading, this.fog = e.fog, this; } } class fh extends $t { /** * Constructs a new mesh depth material. * * @param {Object} [parameters] - An object with one or more properties * defining the material's appearance. Any property of the material * (including any property from inherited materials) can be passed * in here. Color values can be passed any type of value accepted * by {@link Color#set}. */ constructor(e) { super(), this.isMeshDepthMaterial = !0, this.type = "MeshDepthMaterial", this.depthPacking = _u, this.map = null, this.alphaMap = null, this.displacementMap = null, this.displacementScale = 1, this.displacementBias = 0, this.wireframe = !1, this.wireframeLinewidth = 1, this.setValues(e); } copy(e) { return super.copy(e), this.depthPacking = e.depthPacking, this.map = e.map, this.alphaMap = e.alphaMap, this.displacementMap = e.displacementMap, this.displacementScale = e.displacementScale, this.displacementBias = e.displacementBias, this.wireframe = e.wireframe, this.wireframeLinewidth = e.wireframeLinewidth, this; } } class Id extends $t { /** * Constructs a new mesh distance material. * * @param {Object} [parameters] - An object with one or more properties * defining the material's appearance. Any property of the material * (including any property from inherited materials) can be passed * in here. Color values can be passed any type of value accepted * by {@link Color#set}. */ constructor(e) { super(), this.isMeshDistanceMaterial = !0, this.type = "MeshDistanceMaterial", this.map = null, this.alphaMap = null, this.displacementMap = null, this.displacementScale = 1, this.displacementBias = 0, this.setValues(e); } copy(e) { return super.copy(e), this.map = e.map, this.alphaMap = e.alphaMap, this.displacementMap = e.displacementMap, this.displacementScale = e.displacementScale, this.displacementBias = e.displacementBias, this; } } function nn(r, e) { return !r || r.constructor === e ? r : typeof e.BYTES_PER_ELEMENT == "number" ? new e(r) : Array.prototype.slice.call(r); } function Ud(r) { return ArrayBuffer.isView(r) && !(r instanceof DataView); } function Nd(r) { function e(s, n) { return r[s] - r[n]; } const t = r.length, i = new Array(t); for (let s = 0; s !== t; ++s) i[s] = s; return i.sort(e), i; } function jl(r, e, t) { const i = r.length, s = new r.constructor(i); for (let n = 0, a = 0; a !== i; ++n) { const o = t[n] * e; for (let l = 0; l !== e; ++l) s[a++] = r[o + l]; } return s; } function mh(r, e, t, i) { let s = 1, n = r[0]; for (; n !== void 0 && n[i] === void 0; ) n = r[s++]; if (n === void 0) return; let a = n[i]; if (a !== void 0) if (Array.isArray(a)) do a = n[i], a !== void 0 && (e.push(n.time), t.push(...a)), n = r[s++]; while (n !== void 0); else if (a.toArray !== void 0) do a = n[i], a !== void 0 && (e.push(n.time), a.toArray(t, t.length)), n = r[s++]; while (n !== void 0); else do a = n[i], a !== void 0 && (e.push(n.time), t.push(a)), n = r[s++]; while (n !== void 0); } class As { /** * Constructs a new interpolant. * * @param {TypedArray} parameterPositions - The parameter positions hold the interpolation factors. * @param {TypedArray} sampleValues - The sample values. * @param {number} sampleSize - The sample size * @param {TypedArray} [resultBuffer] - The result buffer. */ constructor(e, t, i, s) { this.parameterPositions = e, this._cachedIndex = 0, this.resultBuffer = s !== void 0 ? s : new t.constructor(i), this.sampleValues = t, this.valueSize = i, this.settings = null, this.DefaultSettings_ = {}; } /** * Evaluate the interpolant at position `t`. * * @param {number} t - The interpolation factor. * @return {TypedArray} The result buffer. */ evaluate(e) { const t = this.parameterPositions; let i = this._cachedIndex, s = t[i], n = t[i - 1]; i: { e: { let a; t: { r: if (!(e < s)) { for (let o = i + 2; ; ) { if (s === void 0) { if (e < n) break r; return i = t.length, this._cachedIndex = i, this.copySampleValue_(i - 1); } if (i === o) break; if (n = s, s = t[++i], e < s) break e; } a = t.length; break t; } if (!(e >= n)) { const o = t[1]; e < o && (i = 2, n = o); for (let l = i - 2; ; ) { if (n === void 0) return this._cachedIndex = 0, this.copySampleValue_(0); if (i === l) break; if (s = n, n = t[--i - 1], e >= n) break e; } a = i, i = 0; break t; } break i; } for (; i < a; ) { const o = i + a >>> 1; e < t[o] ? a = o : i = o + 1; } if (s = t[i], n = t[i - 1], n === void 0) return this._cachedIndex = 0, this.copySampleValue_(0); if (s === void 0) return i = t.length, this._cachedIndex = i, this.copySampleValue_(i - 1); } this._cachedIndex = i, this.intervalChanged_(i, n, s); } return this.interpolate_(i, n, e, s); } /** * Returns the interpolation settings. * * @return {Object} The interpolation settings. */ getSettings_() { return this.settings || this.DefaultSettings_; } /** * Copies a sample value to the result buffer. * * @param {number} index - An index into the sample value buffer. * @return {TypedArray} The result buffer. */ copySampleValue_(e) { const t = this.resultBuffer, i = this.sampleValues, s = this.valueSize, n = e * s; for (let a = 0; a !== s; ++a) t[a] = i[n + a]; return t; } /** * Copies a sample value to the result buffer. * * @abstract * @param {number} i1 - An index into the sample value buffer. * @param {number} t0 - The previous interpolation factor. * @param {number} t - The current interpolation factor. * @param {number} t1 - The next interpolation factor. * @return {TypedArray} The result buffer. */ interpolate_() { throw new Error("call to abstract method"); } /** * Optional method that is executed when the interval has changed. * * @param {number} i1 - An index into the sample value buffer. * @param {number} t0 - The previous interpolation factor. * @param {number} t - The current interpolation factor. */ intervalChanged_() { } } class Od extends As { /** * Constructs a new cubic interpolant. * * @param {TypedArray} parameterPositions - The parameter positions hold the interpolation factors. * @param {TypedArray} sampleValues - The sample values. * @param {number} sampleSize - The sample size * @param {TypedArray} [resultBuffer] - The result buffer. */ constructor(e, t, i, s) { super(e, t, i, s), this._weightPrev = -0, this._offsetPrev = -0, this._weightNext = -0, this._offsetNext = -0, this.DefaultSettings_ = { endingStart: cl, endingEnd: cl }; } intervalChanged_(e, t, i) { const s = this.parameterPositions; let n = e - 2, a = e + 1, o = s[n], l = s[a]; if (o === void 0) switch (this.getSettings_().endingStart) { case hl: n = e, o = 2 * t - i; break; case ul: n = s.length - 2, o = t + s[n] - s[n + 1]; break; default: n = e, o = i; } if (l === void 0) switch (this.getSettings_().endingEnd) { case hl: a = e, l = 2 * i - t; break; case ul: a = 1, l = i + s[1] - s[0]; break; default: a = e - 1, l = t; } const c = (i - t) * 0.5, h = this.valueSize; this._weightPrev = c / (t - o), this._weightNext = c / (l - i), this._offsetPrev = n * h, this._offsetNext = a * h; } interpolate_(e, t, i, s) { const n = this.resultBuffer, a = this.sampleValues, o = this.valueSize, l = e * o, c = l - o, h = this._offsetPrev, u = this._offsetNext, d = this._weightPrev, f = this._weightNext, g = (i - t) / (s - t), v = g * g, m = v * g, p = -d * m + 2 * d * v - d * g, y = (1 + d) * m + (-1.5 - 2 * d) * v + (-0.5 + d) * g + 1, _ = (-1 - f) * m + (1.5 + f) * v + 0.5 * g, E = f * m - f * v; for (let A = 0; A !== o; ++A) n[A] = p * a[h + A] + y * a[c + A] + _ * a[l + A] + E * a[u + A]; return n; } } class Bd extends As { /** * Constructs a new linear interpolant. * * @param {TypedArray} parameterPositions - The parameter positions hold the interpolation factors. * @param {TypedArray} sampleValues - The sample values. * @param {number} sampleSize - The sample size * @param {TypedArray} [resultBuffer] - The result buffer. */ constructor(e, t, i, s) { super(e, t, i, s); } interpolate_(e, t, i, s) { const n = this.resultBuffer, a = this.sampleValues, o = this.valueSize, l = e * o, c = l - o, h = (i - t) / (s - t), u = 1 - h; for (let d = 0; d !== o; ++d) n[d] = a[c + d] * u + a[l + d] * h; return n; } } class Fd extends As { /** * Constructs a new discrete interpolant. * * @param {TypedArray} parameterPositions - The parameter positions hold the interpolation factors. * @param {TypedArray} sampleValues - The sample values. * @param {number} sampleSize - The sample size * @param {TypedArray} [resultBuffer] - The result buffer. */ constructor(e, t, i, s) { super(e, t, i, s); } interpolate_(e) { return this.copySampleValue_(e - 1); } } class vi { /** * Constructs a new keyframe track. * * @param {string} name - The keyframe track's name. * @param {Array} times - A list of keyframe times. * @param {Array} values - A list of keyframe values. * @param {(InterpolateLinear|InterpolateDiscrete|InterpolateSmooth)} [interpolation] - The interpolation type. */ constructor(e, t, i, s) { if (e === void 0) throw new Error("THREE.KeyframeTrack: track name is undefined"); if (t === void 0 || t.length === 0) throw new Error("THREE.KeyframeTrack: no keyframes in track named " + e); this.name = e, this.times = nn(t, this.TimeBufferType), this.values = nn(i, this.ValueBufferType), this.setInterpolation(s || this.DefaultInterpolation); } /** * Converts the keyframe track to JSON. * * @static * @param {KeyframeTrack} track - The keyframe track to serialize. * @return {Object} The serialized keyframe track as JSON. */ static toJSON(e) { const t = e.constructor; let i; if (t.toJSON !== this.toJSON) i = t.toJSON(e); else { i = { name: e.name, times: nn(e.times, Array), values: nn(e.values, Array) }; const s = e.getInterpolation(); s !== e.DefaultInterpolation && (i.interpolation = s); } return i.type = e.ValueTypeName, i; } /** * Factory method for creating a new discrete interpolant. * * @static * @param {TypedArray} [result] - The result buffer. * @return {DiscreteInterpolant} The new interpolant. */ InterpolantFactoryMethodDiscrete(e) { return new Fd(this.times, this.values, this.getValueSize(), e); } /** * Factory method for creating a new linear interpolant. * * @static * @param {TypedArray} [result] - The result buffer. * @return {LinearInterpolant} The new interpolant. */ InterpolantFactoryMethodLinear(e) { return new Bd(this.times, this.values, this.getValueSize(), e); } /** * Factory method for creating a new smooth interpolant. * * @static * @param {TypedArray} [result] - The result buffer. * @return {CubicInterpolant} The new interpolant. */ InterpolantFactoryMethodSmooth(e) { return new Od(this.times, this.values, this.getValueSize(), e); } /** * Defines the interpolation factor method for this keyframe track. * * @param {(InterpolateLinear|InterpolateDiscrete|InterpolateSmooth)} interpolation - The interpolation type. * @return {KeyframeTrack} A reference to this keyframe track. */ setInterpolation(e) { let t; switch (e) { case Ts: t = this.InterpolantFactoryMethodDiscrete; break; case Es: t = this.InterpolantFactoryMethodLinear; break; case On: t = this.InterpolantFactoryMethodSmooth; break; } if (t === void 0) { const i = "unsupported interpolation for " + this.ValueTypeName + " keyframe track named " + this.name; if (this.createInterpolant === void 0) if (e !== this.DefaultInterpolation) this.setInterpolation(this.DefaultInterpolation); else throw new Error(i); return Se("KeyframeTrack:", i), this; } return this.createInterpolant = t, this; } /** * Returns the current interpolation type. * * @return {(InterpolateLinear|InterpolateDiscrete|InterpolateSmooth)} The interpolation type. */ getInterpolation() { switch (this.createInterpolant) { case this.InterpolantFactoryMethodDiscrete: return Ts; case this.InterpolantFactoryMethodLinear: return Es; case this.InterpolantFactoryMethodSmooth: return On; } } /** * Returns the value size. * * @return {number} The value size. */ getValueSize() { return this.values.length / this.times.length; } /** * Moves all keyframes either forward or backward in time. * * @param {number} timeOffset - The offset to move the time values. * @return {KeyframeTrack} A reference to this keyframe track. */ shift(e) { if (e !== 0) { const t = this.times; for (let i = 0, s = t.length; i !== s; ++i) t[i] += e; } return this; } /** * Scale all keyframe times by a factor (useful for frame - seconds conversions). * * @param {number} timeScale - The time scale. * @return {KeyframeTrack} A reference to this keyframe track. */ scale(e) { if (e !== 1) { const t = this.times; for (let i = 0, s = t.length; i !== s; ++i) t[i] *= e; } return this; } /** * Removes keyframes before and after animation without changing any values within the defined time range. * * Note: The method does not shift around keys to the start of the track time, because for interpolated * keys this will change their values * * @param {number} startTime - The start time. * @param {number} endTime - The end time. * @return {KeyframeTrack} A reference to this keyframe track. */ trim(e, t) { const i = this.times, s = i.length; let n = 0, a = s - 1; for (; n !== s && i[n] < e; ) ++n; for (; a !== -1 && i[a] > t; ) --a; if (++a, n !== 0 || a !== s) { n >= a && (a = Math.max(a, 1), n = a - 1); const o = this.getValueSize(); this.times = i.slice(n, a), this.values = this.values.slice(n * o, a * o); } return this; } /** * Performs minimal validation on the keyframe track. Returns `true` if the values * are valid. * * @return {boolean} Whether the keyframes are valid or not. */ validate() { let e = !0; const t = this.getValueSize(); t - Math.floor(t) !== 0 && (He("KeyframeTrack: Invalid value size in track.", this), e = !1); const i = this.times, s = this.values, n = i.length; n === 0 && (He("KeyframeTrack: Track is empty.", this), e = !1); let a = null; for (let o = 0; o !== n; o++) { const l = i[o]; if (typeof l == "number" && isNaN(l)) { He("KeyframeTrack: Time is not a valid number.", this, o, l), e = !1; break; } if (a !== null && a > l) { He("KeyframeTrack: Out of order keys.", this, o, l, a), e = !1; break; } a = l; } if (s !== void 0 && Ud(s)) for (let o = 0, l = s.length; o !== l; ++o) { const c = s[o]; if (isNaN(c)) { He("KeyframeTrack: Value is not a valid number.", this, o, c), e = !1; break; } } return e; } /** * Optimizes this keyframe track by removing equivalent sequential keys (which are * common in morph target sequences). * * @return {AnimationClip} A reference to this animation clip. */ optimize() { const e = this.times.slice(), t = this.values.slice(), i = this.getValueSize(), s = this.getInterpolation() === On, n = e.length - 1; let a = 1; for (let o = 1; o < n; ++o) { let l = !1; const c = e[o], h = e[o + 1]; if (c !== h && (o !== 1 || c !== e[0])) if (s) l = !0; else { const u = o * i, d = u - i, f = u + i; for (let g = 0; g !== i; ++g) { const v = t[u + g]; if (v !== t[d + g] || v !== t[f + g]) { l = !0; break; } } } if (l) { if (o !== a) { e[a] = e[o]; const u = o * i, d = a * i; for (let f = 0; f !== i; ++f) t[d + f] = t[u + f]; } ++a; } } if (n > 0) { e[a] = e[n]; for (let o = n * i, l = a * i, c = 0; c !== i; ++c) t[l + c] = t[o + c]; ++a; } return a !== e.length ? (this.times = e.slice(0, a), this.values = t.slice(0, a * i)) : (this.times = e, this.values = t), this; } /** * Returns a new keyframe track with copied values from this instance. * * @return {KeyframeTrack} A clone of this instance. */ clone() { const e = this.times.slice(), t = this.values.slice(), i = this.constructor, s = new i(this.name, e, t); return s.createInterpolant = this.createInterpolant, s; } } vi.prototype.ValueTypeName = ""; vi.prototype.TimeBufferType = Float32Array; vi.prototype.ValueBufferType = Float32Array; vi.prototype.DefaultInterpolation = Es; class ts extends vi { /** * Constructs a new boolean keyframe track. * * This keyframe track type has no `interpolation` parameter because the * interpolation is always discrete. * * @param {string} name - The keyframe track's name. * @param {Array} times - A list of keyframe times. * @param {Array} values - A list of keyframe values. */ constructor(e, t, i) { super(e, t, i); } } ts.prototype.ValueTypeName = "bool"; ts.prototype.ValueBufferType = Array; ts.prototype.DefaultInterpolation = Ts; ts.prototype.InterpolantFactoryMethodLinear = void 0; ts.prototype.InterpolantFactoryMethodSmooth = void 0; class gh extends vi { /** * Constructs a new color keyframe track. * * @param {string} name - The keyframe track's name. * @param {Array} times - A list of keyframe times. * @param {Array} values - A list of keyframe values. * @param {(InterpolateLinear|InterpolateDiscrete|InterpolateSmooth)} [interpolation] - The interpolation type. */ constructor(e, t, i, s) { super(e, t, i, s); } } gh.prototype.ValueTypeName = "color"; class Kr extends vi { /** * Constructs a new number keyframe track. * * @param {string} name - The keyframe track's name. * @param {Array} times - A list of keyframe times. * @param {Array} values - A list of keyframe values. * @param {(InterpolateLinear|InterpolateDiscrete|InterpolateSmooth)} [interpolation] - The interpolation type. */ constructor(e, t, i, s) { super(e, t, i, s); } } Kr.prototype.ValueTypeName = "number"; class zd extends As { /** * Constructs a new SLERP interpolant. * * @param {TypedArray} parameterPositions - The parameter positions hold the interpolation factors. * @param {TypedArray} sampleValues - The sample values. * @param {number} sampleSize - The sample size * @param {TypedArray} [resultBuffer] - The result buffer. */ constructor(e, t, i, s) { super(e, t, i, s); } interpolate_(e, t, i, s) { const n = this.resultBuffer, a = this.sampleValues, o = this.valueSize, l = (i - t) / (s - t); let c = e * o; for (let h = c + o; c !== h; c += 4) mi.slerpFlat(n, 0, a, c - o, a, c, l); return n; } } class Zr extends vi { /** * Constructs a new Quaternion keyframe track. * * @param {string} name - The keyframe track's name. * @param {Array} times - A list of keyframe times. * @param {Array} values - A list of keyframe values. * @param {(InterpolateLinear|InterpolateDiscrete|InterpolateSmooth)} [interpolation] - The interpolation type. */ constructor(e, t, i, s) { super(e, t, i, s); } /** * Overwritten so the method returns Quaternion based interpolant. * * @static * @param {TypedArray} [result] - The result buffer. * @return {QuaternionLinearInterpolant} The new interpolant. */ InterpolantFactoryMethodLinear(e) { return new zd(this.times, this.values, this.getValueSize(), e); } } Zr.prototype.ValueTypeName = "quaternion"; Zr.prototype.InterpolantFactoryMethodSmooth = void 0; class is extends vi { /** * Constructs a new string keyframe track. * * This keyframe track type has no `interpolation` parameter because the * interpolation is always discrete. * * @param {string} name - The keyframe track's name. * @param {Array} times - A list of keyframe times. * @param {Array} values - A list of keyframe values. */ constructor(e, t, i) { super(e, t, i); } } is.prototype.ValueTypeName = "string"; is.prototype.ValueBufferType = Array; is.prototype.DefaultInterpolation = Ts; is.prototype.InterpolantFactoryMethodLinear = void 0; is.prototype.InterpolantFactoryMethodSmooth = void 0; class Jr extends vi { /** * Constructs a new vector keyframe track. * * @param {string} name - The keyframe track's name. * @param {Array} times - A list of keyframe times. * @param {Array} values - A list of keyframe values. * @param {(InterpolateLinear|InterpolateDiscrete|InterpolateSmooth)} [interpolation] - The interpolation type. */ constructor(e, t, i, s) { super(e, t, i, s); } } Jr.prototype.ValueTypeName = "vector"; class kd { /** * Constructs a new animation clip. * * Note: Instead of instantiating an AnimationClip directly with the constructor, you can * use the static interface of this class for creating clips. In most cases though, animation clips * will automatically be created by loaders when importing animated 3D assets. * * @param {string} [name=''] - The clip's name. * @param {number} [duration=-1] - The clip's duration in seconds. If a negative value is passed, * the duration will be calculated from the passed keyframes. * @param {Array} tracks - An array of keyframe tracks. * @param {(NormalAnimationBlendMode|AdditiveAnimationBlendMode)} [blendMode=NormalAnimationBlendMode] - Defines how the animation * is blended/combined when two or more animations are simultaneously played. */ constructor(e = "", t = -1, i = [], s = gu) { this.name = e, this.tracks = i, this.duration = t, this.blendMode = s, this.uuid = di(), this.userData = {}, this.duration < 0 && this.resetDuration(); } /** * Factory method for creating an animation clip from the given JSON. * * @static * @param {Object} json - The serialized animation clip. * @return {AnimationClip} The new animation clip. */ static parse(e) { const t = [], i = e.tracks, s = 1 / (e.fps || 1); for (let a = 0, o = i.length; a !== o; ++a) t.push(Vd(i[a]).scale(s)); const n = new this(e.name, e.duration, t, e.blendMode); return n.uuid = e.uuid, n.userData = JSON.parse(e.userData || "{}"), n; } /** * Serializes the given animation clip into JSON. * * @static * @param {AnimationClip} clip - The animation clip to serialize. * @return {Object} The JSON object. */ static toJSON(e) { const t = [], i = e.tracks, s = { name: e.name, duration: e.duration, tracks: t, uuid: e.uuid, blendMode: e.blendMode, userData: JSON.stringify(e.userData) }; for (let n = 0, a = i.length; n !== a; ++n) t.push(vi.toJSON(i[n])); return s; } /** * Returns a new animation clip from the passed morph targets array of a * geometry, taking a name and the number of frames per second. * * Note: The fps parameter is required, but the animation speed can be * overridden via {@link AnimationAction#setDuration}. * * @static * @param {string} name - The name of the animation clip. * @param {Array} morphTargetSequence - A sequence of morph targets. * @param {number} fps - The Frames-Per-Second value. * @param {boolean} noLoop - Whether the clip should be no loop or not. * @return {AnimationClip} The new animation clip. */ static CreateFromMorphTargetSequence(e, t, i, s) { const n = t.length, a = []; for (let o = 0; o < n; o++) { let l = [], c = []; l.push( (o + n - 1) % n, o, (o + 1) % n ), c.push(0, 1, 0); const h = Nd(l); l = jl(l, 1, h), c = jl(c, 1, h), !s && l[0] === 0 && (l.push(n), c.push(c[0])), a.push( new Kr( ".morphTargetInfluences[" + t[o].name + "]", l, c ).scale(1 / i) ); } return new this(e, -1, a); } /** * Searches for an animation clip by name, taking as its first parameter * either an array of clips, or a mesh or geometry that contains an * array named "animations" property. * * @static * @param {(Array|Object3D)} objectOrClipArray - The array or object to search through. * @param {string} name - The name to search for. * @return {?AnimationClip} The found animation clip. Returns `null` if no clip has been found. */ static findByName(e, t) { let i = e; if (!Array.isArray(e)) { const s = e; i = s.geometry && s.geometry.animations || s.animations; } for (let s = 0; s < i.length; s++) if (i[s].name === t) return i[s]; return null; } /** * Returns an array of new AnimationClips created from the morph target * sequences of a geometry, trying to sort morph target names into * animation-group-based patterns like "Walk_001, Walk_002, Run_001, Run_002...". * * See {@link MD2Loader#parse} as an example for how the method should be used. * * @static * @param {Array} morphTargets - A sequence of morph targets. * @param {number} fps - The Frames-Per-Second value. * @param {boolean} noLoop - Whether the clip should be no loop or not. * @return {Array} An array of new animation clips. */ static CreateClipsFromMorphTargetSequences(e, t, i) { const s = {}, n = /^([\w-]*?)([\d]+)$/; for (let o = 0, l = e.length; o < l; o++) { const c = e[o], h = c.name.match(n); if (h && h.length > 1) { const u = h[1]; let d = s[u]; d || (s[u] = d = []), d.push(c); } } const a = []; for (const o in s) a.push(this.CreateFromMorphTargetSequence(o, s[o], t, i)); return a; } /** * Parses the `animation.hierarchy` format and returns a new animation clip. * * @static * @deprecated since r175. * @param {Object} animation - A serialized animation clip as JSON. * @param {Array} bones - An array of bones. * @return {?AnimationClip} The new animation clip. */ static parseAnimation(e, t) { if (Se("AnimationClip: parseAnimation() is deprecated and will be removed with r185"), !e) return He("AnimationClip: No animation in JSONLoader data."), null; const i = function(h, u, d, f, g) { if (d.length !== 0) { const v = [], m = []; mh(d, v, m, f), v.length !== 0 && g.push(new h(u, v, m)); } }, s = [], n = e.name || "default", a = e.fps || 30, o = e.blendMode; let l = e.length || -1; const c = e.hierarchy || []; for (let h = 0; h < c.length; h++) { const u = c[h].keys; if (!(!u || u.length === 0)) if (u[0].morphTargets) { const d = {}; let f; for (f = 0; f < u.length; f++) if (u[f].morphTargets) for (let g = 0; g < u[f].morphTargets.length; g++) d[u[f].morphTargets[g]] = -1; for (const g in d) { const v = [], m = []; for (let p = 0; p !== u[f].morphTargets.length; ++p) { const y = u[f]; v.push(y.time), m.push(y.morphTarget === g ? 1 : 0); } s.push(new Kr(".morphTargetInfluence[" + g + "]", v, m)); } l = d.length * a; } else { const d = ".bones[" + t[h].name + "]"; i( Jr, d + ".position", u, "pos", s ), i( Zr, d + ".quaternion", u, "rot", s ), i( Jr, d + ".scale", u, "scl", s ); } } return s.length === 0 ? null : new this(n, l, s, o); } /** * Sets the duration of this clip to the duration of its longest keyframe track. * * @return {AnimationClip} A reference to this animation clip. */ resetDuration() { const e = this.tracks; let t = 0; for (let i = 0, s = e.length; i !== s; ++i) { const n = this.tracks[i]; t = Math.max(t, n.times[n.times.length - 1]); } return this.duration = t, this; } /** * Trims all tracks to the clip's duration. * * @return {AnimationClip} A reference to this animation clip. */ trim() { for (let e = 0; e < this.tracks.length; e++) this.tracks[e].trim(0, this.duration); return this; } /** * Performs minimal validation on each track in the clip. Returns `true` if all * tracks are valid. * * @return {boolean} Whether the clip's keyframes are valid or not. */ validate() { let e = !0; for (let t = 0; t < this.tracks.length; t++) e = e && this.tracks[t].validate(); return e; } /** * Optimizes each track by removing equivalent sequential keys (which are * common in morph target sequences). * * @return {AnimationClip} A reference to this animation clip. */ optimize() { for (let e = 0; e < this.tracks.length; e++) this.tracks[e].optimize(); return this; } /** * Returns a new animation clip with copied values from this instance. * * @return {AnimationClip} A clone of this instance. */ clone() { const e = []; for (let i = 0; i < this.tracks.length; i++) e.push(this.tracks[i].clone()); const t = new this.constructor(this.name, this.duration, e, this.blendMode); return t.userData = JSON.parse(JSON.stringify(this.userData)), t; } /** * Serializes this animation clip into JSON. * * @return {Object} The JSON object. */ toJSON() { return this.constructor.toJSON(this); } } function Hd(r) { switch (r.toLowerCase()) { case "scalar": case "double": case "float": case "number": case "integer": return Kr; case "vector": case "vector2": case "vector3": case "vector4": return Jr; case "color": return gh; case "quaternion": return Zr; case "bool": case "boolean": return ts; case "string": return is; } throw new Error("THREE.KeyframeTrack: Unsupported typeName: " + r); } function Vd(r) { if (r.type === void 0) throw new Error("THREE.KeyframeTrack: track type undefined, can not parse"); const e = Hd(r.type); if (r.times === void 0) { const t = [], i = []; mh(r.keys, t, i, "value"), r.times = t, r.values = i; } return e.parse !== void 0 ? e.parse(r) : new e(r.name, r.times, r.values, r.interpolation); } const ki = { /** * Whether caching is enabled or not. * * @static * @type {boolean} * @default false */ enabled: !1, /** * A dictionary that holds cached files. * * @static * @type {Object} */ files: {}, /** * Adds a cache entry with a key to reference the file. If this key already * holds a file, it is overwritten. * * @static * @param {string} key - The key to reference the cached file. * @param {Object} file - The file to be cached. */ add: function(r, e) { this.enabled !== !1 && (this.files[r] = e); }, /** * Gets the cached value for the given key. * * @static * @param {string} key - The key to reference the cached file. * @return {Object|undefined} The cached file. If the key does not exist `undefined` is returned. */ get: function(r) { if (this.enabled !== !1) return this.files[r]; }, /** * Removes the cached file associated with the given key. * * @static * @param {string} key - The key to reference the cached file. */ remove: function(r) { delete this.files[r]; }, /** * Remove all values from the cache. * * @static */ clear: function() { this.files = {}; } }; class Gd { /** * Constructs a new loading manager. * * @param {Function} [onLoad] - Executes when all items have been loaded. * @param {Function} [onProgress] - Executes when single items have been loaded. * @param {Function} [onError] - Executes when an error occurs. */ constructor(e, t, i) { const s = this; let n = !1, a = 0, o = 0, l; const c = []; this.onStart = void 0, this.onLoad = e, this.onProgress = t, this.onError = i, this._abortController = null, this.itemStart = function(h) { o++, n === !1 && s.onStart !== void 0 && s.onStart(h, a, o), n = !0; }, this.itemEnd = function(h) { a++, s.onProgress !== void 0 && s.onProgress(h, a, o), a === o && (n = !1, s.onLoad !== void 0 && s.onLoad()); }, this.itemError = function(h) { s.onError !== void 0 && s.onError(h); }, this.resolveURL = function(h) { return l ? l(h) : h; }, this.setURLModifier = function(h) { return l = h, this; }, this.addHandler = function(h, u) { return c.push(h, u), this; }, this.removeHandler = function(h) { const u = c.indexOf(h); return u !== -1 && c.splice(u, 2), this; }, this.getHandler = function(h) { for (let u = 0, d = c.length; u < d; u += 2) { const f = c[u], g = c[u + 1]; if (f.global && (f.lastIndex = 0), f.test(h)) return g; } return null; }, this.abort = function() { return this.abortController.abort(), this._abortController = null, this; }; } // TODO: Revert this back to a single member variable once this issue has been fixed // https://github.com/cloudflare/workerd/issues/3657 /** * Used for aborting ongoing requests in loaders using this manager. * * @type {AbortController} */ get abortController() { return this._abortController || (this._abortController = new AbortController()), this._abortController; } } const Wd = /* @__PURE__ */ new Gd(); class er { /** * Constructs a new loader. * * @param {LoadingManager} [manager] - The loading manager. */ constructor(e) { this.manager = e !== void 0 ? e : Wd, this.crossOrigin = "anonymous", this.withCredentials = !1, this.path = "", this.resourcePath = "", this.requestHeader = {}; } /** * This method needs to be implemented by all concrete loaders. It holds the * logic for loading assets from the backend. * * @abstract * @param {string} url - The path/URL of the file to be loaded. * @param {Function} onLoad - Executed when the loading process has been finished. * @param {onProgressCallback} [onProgress] - Executed while the loading is in progress. * @param {onErrorCallback} [onError] - Executed when errors occur. */ load() { } /** * A async version of {@link Loader#load}. * * @param {string} url - The path/URL of the file to be loaded. * @param {onProgressCallback} [onProgress] - Executed while the loading is in progress. * @return {Promise} A Promise that resolves when the asset has been loaded. */ loadAsync(e, t) { const i = this; return new Promise(function(s, n) { i.load(e, s, t, n); }); } /** * This method needs to be implemented by all concrete loaders. It holds the * logic for parsing the asset into three.js entities. * * @abstract * @param {any} data - The data to parse. */ parse() { } /** * Sets the `crossOrigin` String to implement CORS for loading the URL * from a different domain that allows CORS. * * @param {string} crossOrigin - The `crossOrigin` value. * @return {Loader} A reference to this instance. */ setCrossOrigin(e) { return this.crossOrigin = e, this; } /** * Whether the XMLHttpRequest uses credentials such as cookies, authorization * headers or TLS client certificates, see [XMLHttpRequest.withCredentials](https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest/withCredentials). * * Note: This setting has no effect if you are loading files locally or from the same domain. * * @param {boolean} value - The `withCredentials` value. * @return {Loader} A reference to this instance. */ setWithCredentials(e) { return this.withCredentials = e, this; } /** * Sets the base path for the asset. * * @param {string} path - The base path. * @return {Loader} A reference to this instance. */ setPath(e) { return this.path = e, this; } /** * Sets the base path for dependent resources like textures. * * @param {string} resourcePath - The resource path. * @return {Loader} A reference to this instance. */ setResourcePath(e) { return this.resourcePath = e, this; } /** * Sets the given request header. * * @param {Object} requestHeader - A [request header](https://developer.mozilla.org/en-US/docs/Glossary/Request_header) * for configuring the HTTP request. * @return {Loader} A reference to this instance. */ setRequestHeader(e) { return this.requestHeader = e, this; } /** * This method can be implemented in loaders for aborting ongoing requests. * * @abstract * @return {Loader} A reference to this instance. */ abort() { return this; } } er.DEFAULT_MATERIAL_NAME = "__DEFAULT"; const Ni = {}; class jd extends Error { constructor(e, t) { super(e), this.response = t; } } class Xo extends er { /** * Constructs a new file loader. * * @param {LoadingManager} [manager] - The loading manager. */ constructor(e) { super(e), this.mimeType = "", this.responseType = "", this._abortController = new AbortController(); } /** * Starts loading from the given URL and pass the loaded response to the `onLoad()` callback. * * @param {string} url - The path/URL of the file to be loaded. This can also be a data URI. * @param {function(any)} onLoad - Executed when the loading process has been finished. * @param {onProgressCallback} [onProgress] - Executed while the loading is in progress. * @param {onErrorCallback} [onError] - Executed when errors occur. * @return {any|undefined} The cached resource if available. */ load(e, t, i, s) { e === void 0 && (e = ""), this.path !== void 0 && (e = this.path + e), e = this.manager.resolveURL(e); const n = ki.get(`file:${e}`); if (n !== void 0) return this.manager.itemStart(e), setTimeout(() => { t && t(n), this.manager.itemEnd(e); }, 0), n; if (Ni[e] !== void 0) { Ni[e].push({ onLoad: t, onProgress: i, onError: s }); return; } Ni[e] = [], Ni[e].push({ onLoad: t, onProgress: i, onError: s }); const a = new Request(e, { headers: new Headers(this.requestHeader), credentials: this.withCredentials ? "include" : "same-origin", signal: typeof AbortSignal.any == "function" ? AbortSignal.any([this._abortController.signal, this.manager.abortController.signal]) : this._abortController.signal }), o = this.mimeType, l = this.responseType; fetch(a).then((c) => { if (c.status === 200 || c.status === 0) { if (c.status === 0 && Se("FileLoader: HTTP Status 0 received."), typeof ReadableStream > "u" || c.body === void 0 || c.body.getReader === void 0) return c; const h = Ni[e], u = c.body.getReader(), d = c.headers.get("X-File-Size") || c.headers.get("Content-Length"), f = d ? parseInt(d) : 0, g = f !== 0; let v = 0; const m = new ReadableStream({ start(p) { y(); function y() { u.read().then(({ done: _, value: E }) => { if (_) p.close(); else { v += E.byteLength; const A = new ProgressEvent("progress", { lengthComputable: g, loaded: v, total: f }); for (let T = 0, R = h.length; T < R; T++) { const I = h[T]; I.onProgress && I.onProgress(A); } p.enqueue(E), y(); } }, (_) => { p.error(_); }); } } }); return new Response(m); } else throw new jd(`fetch for "${c.url}" responded with ${c.status}: ${c.statusText}`, c); }).then((c) => { switch (l) { case "arraybuffer": return c.arrayBuffer(); case "blob": return c.blob(); case "document": return c.text().then((h) => new DOMParser().parseFromString(h, o)); case "json": return c.json(); default: if (o === "") return c.text(); { const h = /charset="?([^;"\s]*)"?/i.exec(o), u = h && h[1] ? h[1].toLowerCase() : void 0, d = new TextDecoder(u); return c.arrayBuffer().then((f) => d.decode(f)); } } }).then((c) => { ki.add(`file:${e}`, c); const h = Ni[e]; delete Ni[e]; for (let u = 0, d = h.length; u < d; u++) { const f = h[u]; f.onLoad && f.onLoad(c); } }).catch((c) => { const h = Ni[e]; if (h === void 0) throw this.manager.itemError(e), c; delete Ni[e]; for (let u = 0, d = h.length; u < d; u++) { const f = h[u]; f.onError && f.onError(c); } this.manager.itemError(e); }).finally(() => { this.manager.itemEnd(e); }), this.manager.itemStart(e); } /** * Sets the expected response type. * * @param {('arraybuffer'|'blob'|'document'|'json'|'')} value - The response type. * @return {FileLoader} A reference to this file loader. */ setResponseType(e) { return this.responseType = e, this; } /** * Sets the expected mime type of the loaded file. * * @param {string} value - The mime type. * @return {FileLoader} A reference to this file loader. */ setMimeType(e) { return this.mimeType = e, this; } /** * Aborts ongoing fetch requests. * * @return {FileLoader} A reference to this instance. */ abort() { return this._abortController.abort(), this._abortController = new AbortController(), this; } } const Lr = /* @__PURE__ */ new WeakMap(); class vh extends er { /** * Constructs a new image loader. * * @param {LoadingManager} [manager] - The loading manager. */ constructor(e) { super(e); } /** * Starts loading from the given URL and passes the loaded image * to the `onLoad()` callback. The method also returns a new `Image` object which can * directly be used for texture creation. If you do it this way, the texture * may pop up in your scene once the respective loading process is finished. * * @param {string} url - The path/URL of the file to be loaded. This can also be a data URI. * @param {function(Image)} onLoad - Executed when the loading process has been finished. * @param {onProgressCallback} onProgress - Unsupported in this loader. * @param {onErrorCallback} onError - Executed when errors occur. * @return {Image} The image. */ load(e, t, i, s) { this.path !== void 0 && (e = this.path + e), e = this.manager.resolveURL(e); const n = this, a = ki.get(`image:${e}`); if (a !== void 0) { if (a.complete === !0) n.manager.itemStart(e), setTimeout(function() { t && t(a), n.manager.itemEnd(e); }, 0); else { let u = Lr.get(a); u === void 0 && (u = [], Lr.set(a, u)), u.push({ onLoad: t, onError: s }); } return a; } const o = ws("img"); function l() { h(), t && t(this); const u = Lr.get(this) || []; for (let d = 0; d < u.length; d++) { const f = u[d]; f.onLoad && f.onLoad(this); } Lr.delete(this), n.manager.itemEnd(e); } function c(u) { h(), s && s(u), ki.remove(`image:${e}`); const d = Lr.get(this) || []; for (let f = 0; f < d.length; f++) { const g = d[f]; g.onError && g.onError(u); } Lr.delete(this), n.manager.itemError(e), n.manager.itemEnd(e); } function h() { o.removeEventListener("load", l, !1), o.removeEventListener("error", c, !1); } return o.addEventListener("load", l, !1), o.addEventListener("error", c, !1), e.slice(0, 5) !== "data:" && this.crossOrigin !== void 0 && (o.crossOrigin = this.crossOrigin), ki.add(`image:${e}`, o), n.manager.itemStart(e), o.src = e, o; } } class _h extends er { /** * Constructs a new cube texture loader. * * @param {LoadingManager} [manager] - The loading manager. */ constructor(e) { super(e); } /** * Starts loading from the given URL and pass the fully loaded cube texture * to the `onLoad()` callback. The method also returns a new cube texture object which can * directly be used for material creation. If you do it this way, the cube texture * may pop up in your scene once the respective loading process is finished. * * @param {Array} urls - Array of 6 URLs to images, one for each side of the * cube texture. The urls should be specified in the following order: pos-x, * neg-x, pos-y, neg-y, pos-z, neg-z. An array of data URIs are allowed as well. * @param {function(CubeTexture)} onLoad - Executed when the loading process has been finished. * @param {onProgressCallback} onProgress - Unsupported in this loader. * @param {onErrorCallback} onError - Executed when errors occur. * @return {CubeTexture} The cube texture. */ load(e, t, i, s) { const n = new Fo(); n.colorSpace = wt; const a = new vh(this.manager); a.setCrossOrigin(this.crossOrigin), a.setPath(this.path); let o = 0; function l(c) { a.load(e[c], function(h) { n.images[c] = h, o++, o === 6 && (n.needsUpdate = !0, t && t(n)); }, void 0, s); } for (let c = 0; c < e.length; ++c) l(c); return n; } } class Xd extends er { /** * Constructs a new data texture loader. * * @param {LoadingManager} [manager] - The loading manager. */ constructor(e) { super(e); } /** * Starts loading from the given URL and passes the loaded data texture * to the `onLoad()` callback. The method also returns a new texture object which can * directly be used for material creation. If you do it this way, the texture * may pop up in your scene once the respective loading process is finished. * * @param {string} url - The path/URL of the file to be loaded. This can also be a data URI. * @param {function(DataTexture)} onLoad - Executed when the loading process has been finished. * @param {onProgressCallback} onProgress - Executed while the loading is in progress. * @param {onErrorCallback} onError - Executed when errors occur. * @return {DataTexture} The data texture. */ load(e, t, i, s) { const n = this, a = new es(), o = new Xo(this.manager); return o.setResponseType("arraybuffer"), o.setRequestHeader(this.requestHeader), o.setPath(this.path), o.setWithCredentials(n.withCredentials), o.load(e, function(l) { let c; try { c = n.parse(l); } catch (h) { if (s !== void 0) s(h); else { h(h); return; } } c.image !== void 0 ? a.image = c.image : c.data !== void 0 && (a.image.width = c.width, a.image.height = c.height, a.image.data = c.data), a.wrapS = c.wrapS !== void 0 ? c.wrapS : Jt, a.wrapT = c.wrapT !== void 0 ? c.wrapT : Jt, a.magFilter = c.magFilter !== void 0 ? c.magFilter : xt, a.minFilter = c.minFilter !== void 0 ? c.minFilter : xt, a.anisotropy = c.anisotropy !== void 0 ? c.anisotropy : 1, c.colorSpace !== void 0 && (a.colorSpace = c.colorSpace), c.flipY !== void 0 && (a.flipY = c.flipY), c.format !== void 0 && (a.format = c.format), c.type !== void 0 && (a.type = c.type), c.mipmaps !== void 0 && (a.mipmaps = c.mipmaps, a.minFilter = Si), c.mipmapCount === 1 && (a.minFilter = xt), c.generateMipmaps !== void 0 && (a.generateMipmaps = c.generateMipmaps), a.needsUpdate = !0, t && t(a, c); }, i, s), a; } } class xh extends er { /** * Constructs a new texture loader. * * @param {LoadingManager} [manager] - The loading manager. */ constructor(e) { super(e); } /** * Starts loading from the given URL and pass the fully loaded texture * to the `onLoad()` callback. The method also returns a new texture object which can * directly be used for material creation. If you do it this way, the texture * may pop up in your scene once the respective loading process is finished. * * @param {string} url - The path/URL of the file to be loaded. This can also be a data URI. * @param {function(Texture)} onLoad - Executed when the loading process has been finished. * @param {onProgressCallback} onProgress - Unsupported in this loader. * @param {onErrorCallback} onError - Executed when errors occur. * @return {Texture} The texture. */ load(e, t, i, s) { const n = new Ct(), a = new vh(this.manager); return a.setCrossOrigin(this.crossOrigin), a.setPath(this.path), a.load(e, function(o) { n.image = o, n.needsUpdate = !0, t !== void 0 && t(n); }, i, s), n; } } class Ps extends dt { /** * Constructs a new light. * * @param {(number|Color|string)} [color=0xffffff] - The light's color. * @param {number} [intensity=1] - The light's strength/intensity. */ constructor(e, t = 1) { super(), this.isLight = !0, this.type = "Light", this.color = new _e(e), this.intensity = t; } /** * Frees the GPU-related resources allocated by this instance. Call this * method whenever this instance is no longer used in your app. */ dispose() { } copy(e, t) { return super.copy(e, t), this.color.copy(e.color), this.intensity = e.intensity, this; } toJSON(e) { const t = super.toJSON(e); return t.object.color = this.color.getHex(), t.object.intensity = this.intensity, this.groundColor !== void 0 && (t.object.groundColor = this.groundColor.getHex()), this.distance !== void 0 && (t.object.distance = this.distance), this.angle !== void 0 && (t.object.angle = this.angle), this.decay !== void 0 && (t.object.decay = this.decay), this.penumbra !== void 0 && (t.object.penumbra = this.penumbra), this.shadow !== void 0 && (t.object.shadow = this.shadow.toJSON()), this.target !== void 0 && (t.object.target = this.target.uuid), t; } } const ha = /* @__PURE__ */ new Ue(), Xl = /* @__PURE__ */ new w(), ql = /* @__PURE__ */ new w(); class qo { /** * Constructs a new light shadow. * * @param {Camera} camera - The light's view of the world. */ constructor(e) { this.camera = e, this.intensity = 1, this.bias = 0, this.normalBias = 0, this.radius = 1, this.blurSamples = 8, this.mapSize = new oe(512, 512), this.mapType = fi, this.map = null, this.mapPass = null, this.matrix = new Ue(), this.autoUpdate = !0, this.needsUpdate = !1, this._frustum = new Vo(), this._frameExtents = new oe(1, 1), this._viewportCount = 1, this._viewports = [ new Je(0, 0, 1, 1) ]; } /** * Used internally by the renderer to get the number of viewports that need * to be rendered for this shadow. * * @return {number} The viewport count. */ getViewportCount() { return this._viewportCount; } /** * Gets the shadow cameras frustum. Used internally by the renderer to cull objects. * * @return {Frustum} The shadow camera frustum. */ getFrustum() { return this._frustum; } /** * Update the matrices for the camera and shadow, used internally by the renderer. * * @param {Light} light - The light for which the shadow is being rendered. */ updateMatrices(e) { const t = this.camera, i = this.matrix; Xl.setFromMatrixPosition(e.matrixWorld), t.position.copy(Xl), ql.setFromMatrixPosition(e.target.matrixWorld), t.lookAt(ql), t.updateMatrixWorld(), ha.multiplyMatrices(t.projectionMatrix, t.matrixWorldInverse), this._frustum.setFromProjectionMatrix(ha, t.coordinateSystem, t.reversedDepth), t.reversedDepth ? i.set( 0.5, 0, 0, 0.5, 0, 0.5, 0, 0.5, 0, 0, 1, 0, 0, 0, 0, 1 ) : i.set( 0.5, 0, 0, 0.5, 0, 0.5, 0, 0.5, 0, 0, 0.5, 0.5, 0, 0, 0, 1 ), i.multiply(ha); } /** * Returns a viewport definition for the given viewport index. * * @param {number} viewportIndex - The viewport index. * @return {Vector4} The viewport. */ getViewport(e) { return this._viewports[e]; } /** * Returns the frame extends. * * @return {Vector2} The frame extends. */ getFrameExtents() { return this._frameExtents; } /** * Frees the GPU-related resources allocated by this instance. Call this * method whenever this instance is no longer used in your app. */ dispose() { this.map && this.map.dispose(), this.mapPass && this.mapPass.dispose(); } /** * Copies the values of the given light shadow instance to this instance. * * @param {LightShadow} source - The light shadow to copy. * @return {LightShadow} A reference to this light shadow instance. */ copy(e) { return this.camera = e.camera.clone(), this.intensity = e.intensity, this.bias = e.bias, this.radius = e.radius, this.autoUpdate = e.autoUpdate, this.needsUpdate = e.needsUpdate, this.normalBias = e.normalBias, this.blurSamples = e.blurSamples, this.mapSize.copy(e.mapSize), this; } /** * Returns a new light shadow instance with copied values from this instance. * * @return {LightShadow} A clone of this instance. */ clone() { return new this.constructor().copy(this); } /** * Serializes the light shadow into JSON. * * @return {Object} A JSON object representing the serialized light shadow. * @see {@link ObjectLoader#parse} */ toJSON() { const e = {}; return this.intensity !== 1 && (e.intensity = this.intensity), this.bias !== 0 && (e.bias = this.bias), this.normalBias !== 0 && (e.normalBias = this.normalBias), this.radius !== 1 && (e.radius = this.radius), (this.mapSize.x !== 512 || this.mapSize.y !== 512) && (e.mapSize = this.mapSize.toArray()), e.camera = this.camera.toJSON(!1).object, delete e.camera.matrix, e; } } class qd extends qo { /** * Constructs a new spot light shadow. */ constructor() { super(new Mt(50, 1, 0.5, 500)), this.isSpotLightShadow = !0, this.focus = 1, this.aspect = 1; } updateMatrices(e) { const t = this.camera, i = qr * 2 * e.angle * this.focus, s = this.mapSize.width / this.mapSize.height * this.aspect, n = e.distance || t.far; (i !== t.fov || s !== t.aspect || n !== t.far) && (t.fov = i, t.aspect = s, t.far = n, t.updateProjectionMatrix()), super.updateMatrices(e); } copy(e) { return super.copy(e), this.focus = e.focus, this; } } class Yd extends Ps { /** * Constructs a new spot light. * * @param {(number|Color|string)} [color=0xffffff] - The light's color. * @param {number} [intensity=1] - The light's strength/intensity measured in candela (cd). * @param {number} [distance=0] - Maximum range of the light. `0` means no limit. * @param {number} [angle=Math.PI/3] - Maximum angle of light dispersion from its direction whose upper bound is `Math.PI/2`. * @param {number} [penumbra=0] - Percent of the spotlight cone that is attenuated due to penumbra. Value range is `[0,1]`. * @param {number} [decay=2] - The amount the light dims along the distance of the light. */ constructor(e, t, i = 0, s = Math.PI / 3, n = 0, a = 2) { super(e, t), this.isSpotLight = !0, this.type = "SpotLight", this.position.copy(dt.DEFAULT_UP), this.updateMatrix(), this.target = new dt(), this.distance = i, this.angle = s, this.penumbra = n, this.decay = a, this.map = null, this.shadow = new qd(); } /** * The light's power. Power is the luminous power of the light measured in lumens (lm). * Changing the power will also change the light's intensity. * * @type {number} */ get power() { return this.intensity * Math.PI; } set power(e) { this.intensity = e / Math.PI; } dispose() { this.shadow.dispose(); } copy(e, t) { return super.copy(e, t), this.distance = e.distance, this.angle = e.angle, this.penumbra = e.penumbra, this.decay = e.decay, this.target = e.target.clone(), this.shadow = e.shadow.clone(), this; } } const Yl = /* @__PURE__ */ new Ue(), ds = /* @__PURE__ */ new w(), ua = /* @__PURE__ */ new w(); class Kd extends qo { /** * Constructs a new point light shadow. */ constructor() { super(new Mt(90, 1, 0.5, 500)), this.isPointLightShadow = !0, this._frameExtents = new oe(4, 2), this._viewportCount = 6, this._viewports = [ // These viewports map a cube-map onto a 2D texture with the // following orientation: // // xzXZ // y Y // // X - Positive x direction // x - Negative x direction // Y - Positive y direction // y - Negative y direction // Z - Positive z direction // z - Negative z direction // positive X new Je(2, 1, 1, 1), // negative X new Je(0, 1, 1, 1), // positive Z new Je(3, 1, 1, 1), // negative Z new Je(1, 1, 1, 1), // positive Y new Je(3, 0, 1, 1), // negative Y new Je(1, 0, 1, 1) ], this._cubeDirections = [ new w(1, 0, 0), new w(-1, 0, 0), new w(0, 0, 1), new w(0, 0, -1), new w(0, 1, 0), new w(0, -1, 0) ], this._cubeUps = [ new w(0, 1, 0), new w(0, 1, 0), new w(0, 1, 0), new w(0, 1, 0), new w(0, 0, 1), new w(0, 0, -1) ]; } /** * Update the matrices for the camera and shadow, used internally by the renderer. * * @param {Light} light - The light for which the shadow is being rendered. * @param {number} [viewportIndex=0] - The viewport index. */ updateMatrices(e, t = 0) { const i = this.camera, s = this.matrix, n = e.distance || i.far; n !== i.far && (i.far = n, i.updateProjectionMatrix()), ds.setFromMatrixPosition(e.matrixWorld), i.position.copy(ds), ua.copy(i.position), ua.add(this._cubeDirections[t]), i.up.copy(this._cubeUps[t]), i.lookAt(ua), i.updateMatrixWorld(), s.makeTranslation(-ds.x, -ds.y, -ds.z), Yl.multiplyMatrices(i.projectionMatrix, i.matrixWorldInverse), this._frustum.setFromProjectionMatrix(Yl, i.coordinateSystem, i.reversedDepth); } } class Zd extends Ps { /** * Constructs a new point light. * * @param {(number|Color|string)} [color=0xffffff] - The light's color. * @param {number} [intensity=1] - The light's strength/intensity measured in candela (cd). * @param {number} [distance=0] - Maximum range of the light. `0` means no limit. * @param {number} [decay=2] - The amount the light dims along the distance of the light. */ constructor(e, t, i = 0, s = 2) { super(e, t), this.isPointLight = !0, this.type = "PointLight", this.distance = i, this.decay = s, this.shadow = new Kd(); } /** * The light's power. Power is the luminous power of the light measured in lumens (lm). * Changing the power will also change the light's intensity. * * @type {number} */ get power() { return this.intensity * 4 * Math.PI; } set power(e) { this.intensity = e / (4 * Math.PI); } dispose() { this.shadow.dispose(); } copy(e, t) { return super.copy(e, t), this.distance = e.distance, this.decay = e.decay, this.shadow = e.shadow.clone(), this; } } class mr extends ch { /** * Constructs a new orthographic camera. * * @param {number} [left=-1] - The left plane of the camera's frustum. * @param {number} [right=1] - The right plane of the camera's frustum. * @param {number} [top=1] - The top plane of the camera's frustum. * @param {number} [bottom=-1] - The bottom plane of the camera's frustum. * @param {number} [near=0.1] - The camera's near plane. * @param {number} [far=2000] - The camera's far plane. */ constructor(e = -1, t = 1, i = 1, s = -1, n = 0.1, a = 2e3) { super(), this.isOrthographicCamera = !0, this.type = "OrthographicCamera", this.zoom = 1, this.view = null, this.left = e, this.right = t, this.top = i, this.bottom = s, this.near = n, this.far = a, this.updateProjectionMatrix(); } copy(e, t) { return super.copy(e, t), this.left = e.left, this.right = e.right, this.top = e.top, this.bottom = e.bottom, this.near = e.near, this.far = e.far, this.zoom = e.zoom, this.view = e.view === null ? null : Object.assign({}, e.view), this; } /** * Sets an offset in a larger frustum. This is useful for multi-window or * multi-monitor/multi-machine setups. * * @param {number} fullWidth - The full width of multiview setup. * @param {number} fullHeight - The full height of multiview setup. * @param {number} x - The horizontal offset of the subcamera. * @param {number} y - The vertical offset of the subcamera. * @param {number} width - The width of subcamera. * @param {number} height - The height of subcamera. * @see {@link PerspectiveCamera#setViewOffset} */ setViewOffset(e, t, i, s, n, a) { this.view === null && (this.view = { enabled: !0, fullWidth: 1, fullHeight: 1, offsetX: 0, offsetY: 0, width: 1, height: 1 }), this.view.enabled = !0, this.view.fullWidth = e, this.view.fullHeight = t, this.view.offsetX = i, this.view.offsetY = s, this.view.width = n, this.view.height = a, this.updateProjectionMatrix(); } /** * Removes the view offset from the projection matrix. */ clearViewOffset() { this.view !== null && (this.view.enabled = !1), this.updateProjectionMatrix(); } /** * Updates the camera's projection matrix. Must be called after any change of * camera properties. */ updateProjectionMatrix() { const e = (this.right - this.left) / (2 * this.zoom), t = (this.top - this.bottom) / (2 * this.zoom), i = (this.right + this.left) / 2, s = (this.top + this.bottom) / 2; let n = i - e, a = i + e, o = s + t, l = s - t; if (this.view !== null && this.view.enabled) { const c = (this.right - this.left) / this.view.fullWidth / this.zoom, h = (this.top - this.bottom) / this.view.fullHeight / this.zoom; n += c * this.view.offsetX, a = n + c * this.view.width, o -= h * this.view.offsetY, l = o - h * this.view.height; } this.projectionMatrix.makeOrthographic(n, a, o, l, this.near, this.far, this.coordinateSystem, this.reversedDepth), this.projectionMatrixInverse.copy(this.projectionMatrix).invert(); } toJSON(e) { const t = super.toJSON(e); return t.object.zoom = this.zoom, t.object.left = this.left, t.object.right = this.right, t.object.top = this.top, t.object.bottom = this.bottom, t.object.near = this.near, t.object.far = this.far, this.view !== null && (t.object.view = Object.assign({}, this.view)), t; } } class Jd extends qo { /** * Constructs a new directional light shadow. */ constructor() { super(new mr(-5, 5, 5, -5, 0.5, 500)), this.isDirectionalLightShadow = !0; } } class yh extends Ps { /** * Constructs a new directional light. * * @param {(number|Color|string)} [color=0xffffff] - The light's color. * @param {number} [intensity=1] - The light's strength/intensity. */ constructor(e, t) { super(e, t), this.isDirectionalLight = !0, this.type = "DirectionalLight", this.position.copy(dt.DEFAULT_UP), this.updateMatrix(), this.target = new dt(), this.shadow = new Jd(); } dispose() { this.shadow.dispose(); } copy(e) { return super.copy(e), this.target = e.target.clone(), this.shadow = e.shadow.clone(), this; } } class Mh extends Ps { /** * Constructs a new ambient light. * * @param {(number|Color|string)} [color=0xffffff] - The light's color. * @param {number} [intensity=1] - The light's strength/intensity. */ constructor(e, t) { super(e, t), this.isAmbientLight = !0, this.type = "AmbientLight"; } } class Ms { /** * Extracts the base URL from the given URL. * * @param {string} url -The URL to extract the base URL from. * @return {string} The extracted base URL. */ static extractUrlBase(e) { const t = e.lastIndexOf("/"); return t === -1 ? "./" : e.slice(0, t + 1); } /** * Resolves relative URLs against the given path. Absolute paths, data urls, * and blob URLs will be returned as is. Invalid URLs will return an empty * string. * * @param {string} url -The URL to resolve. * @param {string} path - The base path for relative URLs to be resolved against. * @return {string} The resolved URL. */ static resolveURL(e, t) { return typeof e != "string" || e === "" ? "" : (/^https?:\/\//i.test(t) && /^\//.test(e) && (t = t.replace(/(^https?:\/\/[^\/]+).*/i, "$1")), /^(https?:)?\/\//i.test(e) || /^data:.*,.*$/i.test(e) || /^blob:.*$/i.test(e) ? e : t + e); } } const da = /* @__PURE__ */ new WeakMap(); class $d extends er { /** * Constructs a new image bitmap loader. * * @param {LoadingManager} [manager] - The loading manager. */ constructor(e) { super(e), this.isImageBitmapLoader = !0, typeof createImageBitmap > "u" && Se("ImageBitmapLoader: createImageBitmap() not supported."), typeof fetch > "u" && Se("ImageBitmapLoader: fetch() not supported."), this.options = { premultiplyAlpha: "none" }, this._abortController = new AbortController(); } /** * Sets the given loader options. The structure of the object must match the `options` parameter of * [createImageBitmap](https://developer.mozilla.org/en-US/docs/Web/API/Window/createImageBitmap). * * @param {Object} options - The loader options to set. * @return {ImageBitmapLoader} A reference to this image bitmap loader. */ setOptions(e) { return this.options = e, this; } /** * Starts loading from the given URL and pass the loaded image bitmap to the `onLoad()` callback. * * @param {string} url - The path/URL of the file to be loaded. This can also be a data URI. * @param {function(ImageBitmap)} onLoad - Executed when the loading process has been finished. * @param {onProgressCallback} onProgress - Unsupported in this loader. * @param {onErrorCallback} onError - Executed when errors occur. * @return {ImageBitmap|undefined} The image bitmap. */ load(e, t, i, s) { e === void 0 && (e = ""), this.path !== void 0 && (e = this.path + e), e = this.manager.resolveURL(e); const n = this, a = ki.get(`image-bitmap:${e}`); if (a !== void 0) { if (n.manager.itemStart(e), a.then) { a.then((c) => { if (da.has(a) === !0) s && s(da.get(a)), n.manager.itemError(e), n.manager.itemEnd(e); else return t && t(c), n.manager.itemEnd(e), c; }); return; } return setTimeout(function() { t && t(a), n.manager.itemEnd(e); }, 0), a; } const o = {}; o.credentials = this.crossOrigin === "anonymous" ? "same-origin" : "include", o.headers = this.requestHeader, o.signal = typeof AbortSignal.any == "function" ? AbortSignal.any([this._abortController.signal, this.manager.abortController.signal]) : this._abortController.signal; const l = fetch(e, o).then(function(c) { return c.blob(); }).then(function(c) { return createImageBitmap(c, Object.assign(n.options, { colorSpaceConversion: "none" })); }).then(function(c) { return ki.add(`image-bitmap:${e}`, c), t && t(c), n.manager.itemEnd(e), c; }).catch(function(c) { s && s(c), da.set(l, c), ki.remove(`image-bitmap:${e}`), n.manager.itemError(e), n.manager.itemEnd(e); }); ki.add(`image-bitmap:${e}`, l), n.manager.itemStart(e); } /** * Aborts ongoing fetch requests. * * @return {ImageBitmapLoader} A reference to this instance. */ abort() { return this._abortController.abort(), this._abortController = new AbortController(), this; } } class Qd extends Mt { /** * Constructs a new array camera. * * @param {Array} [array=[]] - An array of perspective sub cameras. */ constructor(e = []) { super(), this.isArrayCamera = !0, this.isMultiViewCamera = !1, this.cameras = e; } } class ep { /** * Constructs a new clock. * * @param {boolean} [autoStart=true] - Whether to automatically start the clock when * `getDelta()` is called for the first time. */ constructor(e = !0) { this.autoStart = e, this.startTime = 0, this.oldTime = 0, this.elapsedTime = 0, this.running = !1; } /** * Starts the clock. When `autoStart` is set to `true`, the method is automatically * called by the class. */ start() { this.startTime = performance.now(), this.oldTime = this.startTime, this.elapsedTime = 0, this.running = !0; } /** * Stops the clock. */ stop() { this.getElapsedTime(), this.running = !1, this.autoStart = !1; } /** * Returns the elapsed time in seconds. * * @return {number} The elapsed time. */ getElapsedTime() { return this.getDelta(), this.elapsedTime; } /** * Returns the delta time in seconds. * * @return {number} The delta time. */ getDelta() { let e = 0; if (this.autoStart && !this.running) return this.start(), 0; if (this.running) { const t = performance.now(); e = (t - this.oldTime) / 1e3, this.oldTime = t, this.elapsedTime += e; } return e; } } const Yo = "\\[\\]\\.:\\/", tp = new RegExp("[" + Yo + "]", "g"), Ko = "[^" + Yo + "]", ip = "[^" + Yo.replace("\\.", "") + "]", rp = /* @__PURE__ */ /((?:WC+[\/:])*)/.source.replace("WC", Ko), sp = /* @__PURE__ */ /(WCOD+)?/.source.replace("WCOD", ip), np = /* @__PURE__ */ /(?:\.(WC+)(?:\[(.+)\])?)?/.source.replace("WC", Ko), ap = /* @__PURE__ */ /\.(WC+)(?:\[(.+)\])?/.source.replace("WC", Ko), op = new RegExp( "^" + rp + sp + np + ap + "$" ), lp = ["material", "materials", "bones", "map"]; class cp { constructor(e, t, i) { const s = i || it.parseTrackName(t); this._targetGroup = e, this._bindings = e.subscribe_(t, s); } getValue(e, t) { this.bind(); const i = this._targetGroup.nCachedObjects_, s = this._bindings[i]; s !== void 0 && s.getValue(e, t); } setValue(e, t) { const i = this._bindings; for (let s = this._targetGroup.nCachedObjects_, n = i.length; s !== n; ++s) i[s].setValue(e, t); } bind() { const e = this._bindings; for (let t = this._targetGroup.nCachedObjects_, i = e.length; t !== i; ++t) e[t].bind(); } unbind() { const e = this._bindings; for (let t = this._targetGroup.nCachedObjects_, i = e.length; t !== i; ++t) e[t].unbind(); } } class it { /** * Constructs a new property binding. * * @param {Object} rootNode - The root node. * @param {string} path - The path. * @param {?Object} [parsedPath] - The parsed path. */ constructor(e, t, i) { this.path = t, this.parsedPath = i || it.parseTrackName(t), this.node = it.findNode(e, this.parsedPath.nodeName), this.rootNode = e, this.getValue = this._getValue_unbound, this.setValue = this._setValue_unbound; } /** * Factory method for creating a property binding from the given parameters. * * @static * @param {Object} root - The root node. * @param {string} path - The path. * @param {?Object} [parsedPath] - The parsed path. * @return {PropertyBinding|Composite} The created property binding or composite. */ static create(e, t, i) { return e && e.isAnimationObjectGroup ? new it.Composite(e, t, i) : new it(e, t, i); } /** * Replaces spaces with underscores and removes unsupported characters from * node names, to ensure compatibility with parseTrackName(). * * @param {string} name - Node name to be sanitized. * @return {string} The sanitized node name. */ static sanitizeNodeName(e) { return e.replace(/\s/g, "_").replace(tp, ""); } /** * Parses the given track name (an object path to an animated property) and * returns an object with information about the path. Matches strings in the following forms: * * - nodeName.property * - nodeName.property[accessor] * - nodeName.material.property[accessor] * - uuid.property[accessor] * - uuid.objectName[objectIndex].propertyName[propertyIndex] * - parentName/nodeName.property * - parentName/parentName/nodeName.property[index] * - .bone[Armature.DEF_cog].position * - scene:helium_balloon_model:helium_balloon_model.position * * @static * @param {string} trackName - The track name to parse. * @return {Object} The parsed track name as an object. */ static parseTrackName(e) { const t = op.exec(e); if (t === null) throw new Error("PropertyBinding: Cannot parse trackName: " + e); const i = { // directoryName: matches[ 1 ], // (tschw) currently unused nodeName: t[2], objectName: t[3], objectIndex: t[4], propertyName: t[5], // required propertyIndex: t[6] }, s = i.nodeName && i.nodeName.lastIndexOf("."); if (s !== void 0 && s !== -1) { const n = i.nodeName.substring(s + 1); lp.indexOf(n) !== -1 && (i.nodeName = i.nodeName.substring(0, s), i.objectName = n); } if (i.propertyName === null || i.propertyName.length === 0) throw new Error("PropertyBinding: can not parse propertyName from trackName: " + e); return i; } /** * Searches for a node in the hierarchy of the given root object by the given * node name. * * @static * @param {Object} root - The root object. * @param {string|number} nodeName - The name of the node. * @return {?Object} The found node. Returns `null` if no object was found. */ static findNode(e, t) { if (t === void 0 || t === "" || t === "." || t === -1 || t === e.name || t === e.uuid) return e; if (e.skeleton) { const i = e.skeleton.getBoneByName(t); if (i !== void 0) return i; } if (e.children) { const i = function(n) { for (let a = 0; a < n.length; a++) { const o = n[a]; if (o.name === t || o.uuid === t) return o; const l = i(o.children); if (l) return l; } return null; }, s = i(e.children); if (s) return s; } return null; } // these are used to "bind" a nonexistent property _getValue_unavailable() { } _setValue_unavailable() { } // Getters _getValue_direct(e, t) { e[t] = this.targetObject[this.propertyName]; } _getValue_array(e, t) { const i = this.resolvedProperty; for (let s = 0, n = i.length; s !== n; ++s) e[t++] = i[s]; } _getValue_arrayElement(e, t) { e[t] = this.resolvedProperty[this.propertyIndex]; } _getValue_toArray(e, t) { this.resolvedProperty.toArray(e, t); } // Direct _setValue_direct(e, t) { this.targetObject[this.propertyName] = e[t]; } _setValue_direct_setNeedsUpdate(e, t) { this.targetObject[this.propertyName] = e[t], this.targetObject.needsUpdate = !0; } _setValue_direct_setMatrixWorldNeedsUpdate(e, t) { this.targetObject[this.propertyName] = e[t], this.targetObject.matrixWorldNeedsUpdate = !0; } // EntireArray _setValue_array(e, t) { const i = this.resolvedProperty; for (let s = 0, n = i.length; s !== n; ++s) i[s] = e[t++]; } _setValue_array_setNeedsUpdate(e, t) { const i = this.resolvedProperty; for (let s = 0, n = i.length; s !== n; ++s) i[s] = e[t++]; this.targetObject.needsUpdate = !0; } _setValue_array_setMatrixWorldNeedsUpdate(e, t) { const i = this.resolvedProperty; for (let s = 0, n = i.length; s !== n; ++s) i[s] = e[t++]; this.targetObject.matrixWorldNeedsUpdate = !0; } // ArrayElement _setValue_arrayElement(e, t) { this.resolvedProperty[this.propertyIndex] = e[t]; } _setValue_arrayElement_setNeedsUpdate(e, t) { this.resolvedProperty[this.propertyIndex] = e[t], this.targetObject.needsUpdate = !0; } _setValue_arrayElement_setMatrixWorldNeedsUpdate(e, t) { this.resolvedProperty[this.propertyIndex] = e[t], this.targetObject.matrixWorldNeedsUpdate = !0; } // HasToFromArray _setValue_fromArray(e, t) { this.resolvedProperty.fromArray(e, t); } _setValue_fromArray_setNeedsUpdate(e, t) { this.resolvedProperty.fromArray(e, t), this.targetObject.needsUpdate = !0; } _setValue_fromArray_setMatrixWorldNeedsUpdate(e, t) { this.resolvedProperty.fromArray(e, t), this.targetObject.matrixWorldNeedsUpdate = !0; } _getValue_unbound(e, t) { this.bind(), this.getValue(e, t); } _setValue_unbound(e, t) { this.bind(), this.setValue(e, t); } /** * Creates a getter / setter pair for the property tracked by this binding. */ bind() { let e = this.node; const t = this.parsedPath, i = t.objectName, s = t.propertyName; let n = t.propertyIndex; if (e || (e = it.findNode(this.rootNode, t.nodeName), this.node = e), this.getValue = this._getValue_unavailable, this.setValue = this._setValue_unavailable, !e) { Se("PropertyBinding: No target node found for track: " + this.path + "."); return; } if (i) { let c = t.objectIndex; switch (i) { case "materials": if (!e.material) { He("PropertyBinding: Can not bind to material as node does not have a material.", this); return; } if (!e.material.materials) { He("PropertyBinding: Can not bind to material.materials as node.material does not have a materials array.", this); return; } e = e.material.materials; break; case "bones": if (!e.skeleton) { He("PropertyBinding: Can not bind to bones as node does not have a skeleton.", this); return; } e = e.skeleton.bones; for (let h = 0; h < e.length; h++) if (e[h].name === c) { c = h; break; } break; case "map": if ("map" in e) { e = e.map; break; } if (!e.material) { He("PropertyBinding: Can not bind to material as node does not have a material.", this); return; } if (!e.material.map) { He("PropertyBinding: Can not bind to material.map as node.material does not have a map.", this); return; } e = e.material.map; break; default: if (e[i] === void 0) { He("PropertyBinding: Can not bind to objectName of node undefined.", this); return; } e = e[i]; } if (c !== void 0) { if (e[c] === void 0) { He("PropertyBinding: Trying to bind to objectIndex of objectName, but is undefined.", this, e); return; } e = e[c]; } } const a = e[s]; if (a === void 0) { const c = t.nodeName; He("PropertyBinding: Trying to update property for track: " + c + "." + s + " but it wasn't found.", e); return; } let o = this.Versioning.None; this.targetObject = e, e.isMaterial === !0 ? o = this.Versioning.NeedsUpdate : e.isObject3D === !0 && (o = this.Versioning.MatrixWorldNeedsUpdate); let l = this.BindingType.Direct; if (n !== void 0) { if (s === "morphTargetInfluences") { if (!e.geometry) { He("PropertyBinding: Can not bind to morphTargetInfluences because node does not have a geometry.", this); return; } if (!e.geometry.morphAttributes) { He("PropertyBinding: Can not bind to morphTargetInfluences because node does not have a geometry.morphAttributes.", this); return; } e.morphTargetDictionary[n] !== void 0 && (n = e.morphTargetDictionary[n]); } l = this.BindingType.ArrayElement, this.resolvedProperty = a, this.propertyIndex = n; } else a.fromArray !== void 0 && a.toArray !== void 0 ? (l = this.BindingType.HasFromToArray, this.resolvedProperty = a) : Array.isArray(a) ? (l = this.BindingType.EntireArray, this.resolvedProperty = a) : this.propertyName = s; this.getValue = this.GetterByBindingType[l], this.setValue = this.SetterByBindingTypeAndVersioning[l][o]; } /** * Unbinds the property. */ unbind() { this.node = null, this.getValue = this._getValue_unbound, this.setValue = this._setValue_unbound; } } it.Composite = cp; it.prototype.BindingType = { Direct: 0, EntireArray: 1, ArrayElement: 2, HasFromToArray: 3 }; it.prototype.Versioning = { None: 0, NeedsUpdate: 1, MatrixWorldNeedsUpdate: 2 }; it.prototype.GetterByBindingType = [ it.prototype._getValue_direct, it.prototype._getValue_array, it.prototype._getValue_arrayElement, it.prototype._getValue_toArray ]; it.prototype.SetterByBindingTypeAndVersioning = [ [ // Direct it.prototype._setValue_direct, it.prototype._setValue_direct_setNeedsUpdate, it.prototype._setValue_direct_setMatrixWorldNeedsUpdate ], [ // EntireArray it.prototype._setValue_array, it.prototype._setValue_array_setNeedsUpdate, it.prototype._setValue_array_setMatrixWorldNeedsUpdate ], [ // ArrayElement it.prototype._setValue_arrayElement, it.prototype._setValue_arrayElement_setNeedsUpdate, it.prototype._setValue_arrayElement_setMatrixWorldNeedsUpdate ], [ // HasToFromArray it.prototype._setValue_fromArray, it.prototype._setValue_fromArray_setNeedsUpdate, it.prototype._setValue_fromArray_setMatrixWorldNeedsUpdate ] ]; const Kl = /* @__PURE__ */ new Ue(); class Zl { /** * Constructs a new raycaster. * * @param {Vector3} origin - The origin vector where the ray casts from. * @param {Vector3} direction - The (normalized) direction vector that gives direction to the ray. * @param {number} [near=0] - All results returned are further away than near. Near can't be negative. * @param {number} [far=Infinity] - All results returned are closer than far. Far can't be lower than near. */ constructor(e, t, i = 0, s = 1 / 0) { this.ray = new Qr(e, t), this.near = i, this.far = s, this.camera = null, this.layers = new Bo(), this.params = { Mesh: {}, Line: { threshold: 1 }, LOD: {}, Points: { threshold: 1 }, Sprite: {} }; } /** * Updates the ray with a new origin and direction by copying the values from the arguments. * * @param {Vector3} origin - The origin vector where the ray casts from. * @param {Vector3} direction - The (normalized) direction vector that gives direction to the ray. */ set(e, t) { this.ray.set(e, t); } /** * Uses the given coordinates and camera to compute a new origin and direction for the internal ray. * * @param {Vector2} coords - 2D coordinates of the mouse, in normalized device coordinates (NDC). * X and Y components should be between `-1` and `1`. * @param {Camera} camera - The camera from which the ray should originate. */ setFromCamera(e, t) { t.isPerspectiveCamera ? (this.ray.origin.setFromMatrixPosition(t.matrixWorld), this.ray.direction.set(e.x, e.y, 0.5).unproject(t).sub(this.ray.origin).normalize(), this.camera = t) : t.isOrthographicCamera ? (this.ray.origin.set(e.x, e.y, (t.near + t.far) / (t.near - t.far)).unproject(t), this.ray.direction.set(0, 0, -1).transformDirection(t.matrixWorld), this.camera = t) : He("Raycaster: Unsupported camera type: " + t.type); } /** * Uses the given WebXR controller to compute a new origin and direction for the internal ray. * * @param {WebXRController} controller - The controller to copy the position and direction from. * @return {Raycaster} A reference to this raycaster. */ setFromXRController(e) { return Kl.identity().extractRotation(e.matrixWorld), this.ray.origin.setFromMatrixPosition(e.matrixWorld), this.ray.direction.set(0, 0, -1).applyMatrix4(Kl), 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(e, t = !0, i = []) { return go(e, this, i, t), i.sort(Jl), i; } /** * Checks all intersection between the ray and the objects with or without * the descendants. Intersections are returned sorted by distance, closest first. * * @param {Array} 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(e, t = !0, i = []) { for (let s = 0, n = e.length; s < n; s++) go(e[s], this, i, t); return i.sort(Jl), i; } } function Jl(r, e) { return r.distance - e.distance; } function go(r, e, t, i) { let s = !0; if (r.layers.test(e.layers) && r.raycast(e, t) === !1 && (s = !1), s === !0 && i === !0) { const n = r.children; for (let a = 0, o = n.length; a < o; a++) go(n[a], e, t, !0); } } class $l { /** * Constructs a new spherical. * * @param {number} [radius=1] - The radius, or the Euclidean distance (straight-line distance) from the point to the origin. * @param {number} [phi=0] - The polar angle in radians from the y (up) axis. * @param {number} [theta=0] - The equator/azimuthal angle in radians around the y (up) axis. */ constructor(e = 1, t = 0, i = 0) { this.radius = e, this.phi = t, this.theta = i; } /** * Sets the spherical components by copying the given values. * * @param {number} radius - The radius. * @param {number} phi - The polar angle. * @param {number} theta - The azimuthal angle. * @return {Spherical} A reference to this spherical. */ set(e, t, i) { return this.radius = e, this.phi = t, this.theta = i, this; } /** * Copies the values of the given spherical to this instance. * * @param {Spherical} other - The spherical to copy. * @return {Spherical} A reference to this spherical. */ copy(e) { return this.radius = e.radius, this.phi = e.phi, this.theta = e.theta, this; } /** * Restricts the polar angle [page:.phi phi] to be between `0.000001` and pi - * `0.000001`. * * @return {Spherical} A reference to this spherical. */ makeSafe() { return this.phi = ze(this.phi, 1e-6, Math.PI - 1e-6), this; } /** * Sets the spherical components from the given vector which is assumed to hold * Cartesian coordinates. * * @param {Vector3} v - The vector to set. * @return {Spherical} A reference to this spherical. */ setFromVector3(e) { return this.setFromCartesianCoords(e.x, e.y, e.z); } /** * Sets the spherical components from the given Cartesian coordinates. * * @param {number} x - The x value. * @param {number} y - The y value. * @param {number} z - The z value. * @return {Spherical} A reference to this spherical. */ setFromCartesianCoords(e, t, i) { return this.radius = Math.sqrt(e * e + t * t + i * i), this.radius === 0 ? (this.theta = 0, this.phi = 0) : (this.theta = Math.atan2(e, i), this.phi = Math.acos(ze(t / this.radius, -1, 1))), this; } /** * Returns a new spherical with copied values from this instance. * * @return {Spherical} A clone of this instance. */ clone() { return new this.constructor().copy(this); } } class hp extends gr { /** * Constructs a new controls instance. * * @param {Object3D} object - The object that is managed by the controls. * @param {?HTMLElement} domElement - The HTML element used for event listeners. */ constructor(e, t = null) { super(), this.object = e, this.domElement = t, this.enabled = !0, this.state = -1, this.keys = {}, this.mouseButtons = { LEFT: null, MIDDLE: null, RIGHT: null }, this.touches = { ONE: null, TWO: null }; } /** * Connects the controls to the DOM. This method has so called "side effects" since * it adds the module's event listeners to the DOM. * * @param {HTMLElement} element - The DOM element to connect to. */ connect(e) { if (e === void 0) { Se("Controls: connect() now requires an element."); return; } this.domElement !== null && this.disconnect(), this.domElement = e; } /** * Disconnects the controls from the DOM. */ disconnect() { } /** * Call this method if you no longer want use to the controls. It frees all internal * resources and removes all event listeners. */ dispose() { } /** * Controls should implement this method if they have to update their internal state * per simulation step. * * @param {number} [delta] - The time delta in seconds. */ update() { } } function Ql(r, e, t, i) { const s = up(i); switch (t) { // https://registry.khronos.org/OpenGL-Refpages/es3.0/html/glTexImage2D.xhtml case $c: return r * e; case Ao: return r * e / s.components * s.byteLength; case Po: return r * e / s.components * s.byteLength; case Do: return r * e * 2 / s.components * s.byteLength; case Lo: return r * e * 2 / s.components * s.byteLength; case Qc: return r * e * 3 / s.components * s.byteLength; case qt: return r * e * 4 / s.components * s.byteLength; case Io: return r * e * 4 / s.components * s.byteLength; // https://registry.khronos.org/webgl/extensions/WEBGL_compressed_texture_s3tc_srgb/ case fn: case mn: return Math.floor((r + 3) / 4) * Math.floor((e + 3) / 4) * 8; case gn: case vn: return Math.floor((r + 3) / 4) * Math.floor((e + 3) / 4) * 16; // https://registry.khronos.org/webgl/extensions/WEBGL_compressed_texture_pvrtc/ case Ba: case za: return Math.max(r, 16) * Math.max(e, 8) / 4; case Oa: case Fa: return Math.max(r, 8) * Math.max(e, 8) / 2; // https://registry.khronos.org/webgl/extensions/WEBGL_compressed_texture_etc/ case ka: case Ha: return Math.floor((r + 3) / 4) * Math.floor((e + 3) / 4) * 8; case Va: return Math.floor((r + 3) / 4) * Math.floor((e + 3) / 4) * 16; // https://registry.khronos.org/webgl/extensions/WEBGL_compressed_texture_astc/ case Ga: return Math.floor((r + 3) / 4) * Math.floor((e + 3) / 4) * 16; case Wa: return Math.floor((r + 4) / 5) * Math.floor((e + 3) / 4) * 16; case ja: return Math.floor((r + 4) / 5) * Math.floor((e + 4) / 5) * 16; case Xa: return Math.floor((r + 5) / 6) * Math.floor((e + 4) / 5) * 16; case qa: return Math.floor((r + 5) / 6) * Math.floor((e + 5) / 6) * 16; case Ya: return Math.floor((r + 7) / 8) * Math.floor((e + 4) / 5) * 16; case Ka: return Math.floor((r + 7) / 8) * Math.floor((e + 5) / 6) * 16; case Za: return Math.floor((r + 7) / 8) * Math.floor((e + 7) / 8) * 16; case Ja: return Math.floor((r + 9) / 10) * Math.floor((e + 4) / 5) * 16; case $a: return Math.floor((r + 9) / 10) * Math.floor((e + 5) / 6) * 16; case Qa: return Math.floor((r + 9) / 10) * Math.floor((e + 7) / 8) * 16; case eo: return Math.floor((r + 9) / 10) * Math.floor((e + 9) / 10) * 16; case to: return Math.floor((r + 11) / 12) * Math.floor((e + 9) / 10) * 16; case io: return Math.floor((r + 11) / 12) * Math.floor((e + 11) / 12) * 16; // https://registry.khronos.org/webgl/extensions/EXT_texture_compression_bptc/ case ro: case so: case no: return Math.ceil(r / 4) * Math.ceil(e / 4) * 16; // https://registry.khronos.org/webgl/extensions/EXT_texture_compression_rgtc/ case ao: case oo: return Math.ceil(r / 4) * Math.ceil(e / 4) * 8; case lo: case co: return Math.ceil(r / 4) * Math.ceil(e / 4) * 16; } throw new Error( `Unable to determine texture byte length for ${t} format.` ); } function up(r) { switch (r) { case fi: case Yc: return { byteLength: 1, components: 1 }; case Ss: case Kc: case ft: return { byteLength: 2, components: 1 }; case Co: case Ro: return { byteLength: 2, components: 4 }; case pr: case wo: case Gt: return { byteLength: 4, components: 1 }; case Zc: case Jc: return { byteLength: 4, components: 3 }; } throw new Error(`Unknown texture type ${r}.`); } typeof __THREE_DEVTOOLS__ < "u" && __THREE_DEVTOOLS__.dispatchEvent(new CustomEvent("register", { detail: { revision: "181" } })); typeof window < "u" && (window.__THREE__ ? Se("WARNING: Multiple instances of Three.js being imported.") : window.__THREE__ = "181"); function Sh() { let r = null, e = !1, t = null, i = null; function s(n, a) { t(n, a), i = r.requestAnimationFrame(s); } return { start: function() { e !== !0 && t !== null && (i = r.requestAnimationFrame(s), e = !0); }, stop: function() { r.cancelAnimationFrame(i), e = !1; }, setAnimationLoop: function(n) { t = n; }, setContext: function(n) { r = n; } }; } function dp(r) { const e = /* @__PURE__ */ new WeakMap(); function t(o, l) { const c = o.array, h = o.usage, u = c.byteLength, d = r.createBuffer(); r.bindBuffer(l, d), r.bufferData(l, c, h), o.onUploadCallback(); let f; if (c instanceof Float32Array) f = r.FLOAT; else if (typeof Float16Array < "u" && c instanceof Float16Array) f = r.HALF_FLOAT; else if (c instanceof Uint16Array) o.isFloat16BufferAttribute ? f = r.HALF_FLOAT : f = r.UNSIGNED_SHORT; else if (c instanceof Int16Array) f = r.SHORT; else if (c instanceof Uint32Array) f = r.UNSIGNED_INT; else if (c instanceof Int32Array) f = r.INT; else if (c instanceof Int8Array) f = r.BYTE; else if (c instanceof Uint8Array) f = r.UNSIGNED_BYTE; else if (c instanceof Uint8ClampedArray) f = r.UNSIGNED_BYTE; else throw new Error("THREE.WebGLAttributes: Unsupported buffer data format: " + c); return { buffer: d, type: f, bytesPerElement: c.BYTES_PER_ELEMENT, version: o.version, size: u }; } function i(o, l, c) { const h = l.array, u = l.updateRanges; if (r.bindBuffer(c, o), u.length === 0) r.bufferSubData(c, 0, h); else { u.sort((f, g) => f.start - g.start); let d = 0; for (let f = 1; f < u.length; f++) { const g = u[d], v = u[f]; v.start <= g.start + g.count + 1 ? g.count = Math.max( g.count, v.start + v.count - g.start ) : (++d, u[d] = v); } u.length = d + 1; for (let f = 0, g = u.length; f < g; f++) { const v = u[f]; r.bufferSubData( c, v.start * h.BYTES_PER_ELEMENT, h, v.start, v.count ); } l.clearUpdateRanges(); } l.onUploadCallback(); } function s(o) { return o.isInterleavedBufferAttribute && (o = o.data), e.get(o); } function n(o) { o.isInterleavedBufferAttribute && (o = o.data); const l = e.get(o); l && (r.deleteBuffer(l.buffer), e.delete(o)); } function a(o, l) { if (o.isInterleavedBufferAttribute && (o = o.data), o.isGLBufferAttribute) { const h = e.get(o); (!h || h.version < o.version) && e.set(o, { buffer: o.buffer, type: o.type, bytesPerElement: o.elementSize, version: o.version }); return; } const c = e.get(o); if (c === void 0) e.set(o, t(o, l)); else if (c.version < o.version) { if (c.size !== o.array.byteLength) throw new Error("THREE.WebGLAttributes: The size of the buffer attribute's array buffer does not match the original size. Resizing buffer attributes is not supported."); i(c.buffer, o, l), c.version = o.version; } } return { get: s, remove: n, update: a }; } var pp = `#ifdef USE_ALPHAHASH if ( diffuseColor.a < getAlphaHashThreshold( vPosition ) ) discard; #endif`, fp = `#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`, mp = `#ifdef USE_ALPHAMAP diffuseColor.a *= texture2D( alphaMap, vAlphaMapUv ).g; #endif`, gp = `#ifdef USE_ALPHAMAP uniform sampler2D alphaMap; #endif`, vp = `#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`, _p = `#ifdef USE_ALPHATEST uniform float alphaTest; #endif`, xp = `#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`, yp = `#ifdef USE_AOMAP uniform sampler2D aoMap; uniform float aoMapIntensity; #endif`, Mp = `#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`, Sp = `#ifdef USE_BATCHING mat4 batchingMatrix = getBatchingMatrix( getIndirectIndex( gl_DrawID ) ); #endif`, bp = `vec3 transformed = vec3( position ); #ifdef USE_ALPHAHASH vPosition = vec3( position ); #endif`, Tp = `vec3 objectNormal = vec3( normal ); #ifdef USE_TANGENT vec3 objectTangent = vec3( tangent.xyz ); #endif`, Ep = `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`, wp = `#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`, Cp = `#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`, Rp = `#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`, Ap = `#if NUM_CLIPPING_PLANES > 0 varying vec3 vClipPosition; uniform vec4 clippingPlanes[ NUM_CLIPPING_PLANES ]; #endif`, Pp = `#if NUM_CLIPPING_PLANES > 0 varying vec3 vClipPosition; #endif`, Dp = `#if NUM_CLIPPING_PLANES > 0 vClipPosition = - mvPosition.xyz; #endif`, Lp = `#if defined( USE_COLOR_ALPHA ) diffuseColor *= vColor; #elif defined( USE_COLOR ) diffuseColor.rgb *= vColor; #endif`, Ip = `#if defined( USE_COLOR_ALPHA ) varying vec4 vColor; #elif defined( USE_COLOR ) varying vec3 vColor; #endif`, Up = `#if defined( USE_COLOR_ALPHA ) varying vec4 vColor; #elif defined( USE_COLOR ) || defined( USE_INSTANCING_COLOR ) || defined( USE_BATCHING_COLOR ) varying vec3 vColor; #endif`, Np = `#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`, Op = `#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 ); } 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`, Bp = `#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`, Fp = `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`, zp = `#ifdef USE_DISPLACEMENTMAP uniform sampler2D displacementMap; uniform float displacementScale; uniform float displacementBias; #endif`, kp = `#ifdef USE_DISPLACEMENTMAP transformed += normalize( objectNormal ) * ( texture2D( displacementMap, vDisplacementMapUv ).x * displacementScale + displacementBias ); #endif`, Hp = `#ifdef USE_EMISSIVEMAP vec4 emissiveColor = texture2D( emissiveMap, vEmissiveMapUv ); #ifdef DECODE_VIDEO_TEXTURE_EMISSIVE emissiveColor = sRGBTransferEOTF( emissiveColor ); #endif totalEmissiveRadiance *= emissiveColor.rgb; #endif`, Vp = `#ifdef USE_EMISSIVEMAP uniform sampler2D emissiveMap; #endif`, Gp = "gl_FragColor = linearToOutputTexel( gl_FragColor );", Wp = `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 ); }`, jp = `#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`, Xp = `#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`, qp = `#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`, Yp = `#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`, Kp = `#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`, Zp = `#ifdef USE_FOG vFogDepth = - mvPosition.z; #endif`, Jp = `#ifdef USE_FOG varying float vFogDepth; #endif`, $p = `#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`, Qp = `#ifdef USE_FOG uniform vec3 fogColor; varying float vFogDepth; #ifdef FOG_EXP2 uniform float fogDensity; #else uniform float fogNear; uniform float fogFar; #endif #endif`, ef = `#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 }`, tf = `#ifdef USE_LIGHTMAP uniform sampler2D lightMap; uniform float lightMapIntensity; #endif`, rf = `LambertMaterial material; material.diffuseColor = diffuseColor.rgb; material.specularStrength = specularStrength;`, sf = `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`, nf = `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`, af = `#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, pow4( 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`, of = `ToonMaterial material; material.diffuseColor = diffuseColor.rgb;`, lf = `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`, cf = `BlinnPhongMaterial material; material.diffuseColor = diffuseColor.rgb; material.specularColor = specular; material.specularShininess = shininess; material.specularStrength = specularStrength;`, hf = `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`, uf = `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`, df = `uniform sampler2D dfgLUT; 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 * transpose( 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 ) ); vec2 uv = vec2( roughness, dotNV ); return texture2D( dfgLUT, uv ).rg; } 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; } vec3 BRDF_GGX_Multiscatter( const in vec3 lightDir, const in vec3 viewDir, const in vec3 normal, const in PhysicalMaterial material ) { vec3 singleScatter = BRDF_GGX( lightDir, viewDir, normal, material ); float dotNL = saturate( dot( normal, lightDir ) ); float dotNV = saturate( dot( normal, viewDir ) ); vec2 dfgV = DFGApprox( vec3(0.0, 0.0, 1.0), vec3(sqrt(1.0 - dotNV * dotNV), 0.0, dotNV), material.roughness ); vec2 dfgL = DFGApprox( vec3(0.0, 0.0, 1.0), vec3(sqrt(1.0 - dotNL * dotNL), 0.0, dotNL), material.roughness ); vec3 FssEss_V = material.specularColor * dfgV.x + material.specularF90 * dfgV.y; vec3 FssEss_L = material.specularColor * dfgL.x + material.specularF90 * dfgL.y; float Ess_V = dfgV.x + dfgV.y; float Ess_L = dfgL.x + dfgL.y; float Ems_V = 1.0 - Ess_V; float Ems_L = 1.0 - Ess_L; vec3 Favg = material.specularColor + ( 1.0 - material.specularColor ) * 0.047619; vec3 Fms = FssEss_V * FssEss_L * Favg / ( 1.0 - Ems_V * Ems_L * Favg * Favg + EPSILON ); float compensationFactor = Ems_V * Ems_L; vec3 multiScatter = Fms * compensationFactor; return singleScatter + multiScatter; } #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_Multiscatter( 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 ); }`, pf = ` 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`, ff = `#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`, mf = `#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`, gf = `#if defined( USE_LOGARITHMIC_DEPTH_BUFFER ) gl_FragDepth = vIsPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5; #endif`, vf = `#if defined( USE_LOGARITHMIC_DEPTH_BUFFER ) uniform float logDepthBufFC; varying float vFragDepth; varying float vIsPerspective; #endif`, _f = `#ifdef USE_LOGARITHMIC_DEPTH_BUFFER varying float vFragDepth; varying float vIsPerspective; #endif`, xf = `#ifdef USE_LOGARITHMIC_DEPTH_BUFFER vFragDepth = 1.0 + gl_Position.w; vIsPerspective = float( isPerspectiveMatrix( projectionMatrix ) ); #endif`, yf = `#ifdef USE_MAP vec4 sampledDiffuseColor = texture2D( map, vMapUv ); #ifdef DECODE_VIDEO_TEXTURE sampledDiffuseColor = sRGBTransferEOTF( sampledDiffuseColor ); #endif diffuseColor *= sampledDiffuseColor; #endif`, Mf = `#ifdef USE_MAP uniform sampler2D map; #endif`, Sf = `#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`, bf = `#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`, Tf = `float metalnessFactor = metalness; #ifdef USE_METALNESSMAP vec4 texelMetalness = texture2D( metalnessMap, vMetalnessMapUv ); metalnessFactor *= texelMetalness.b; #endif`, Ef = `#ifdef USE_METALNESSMAP uniform sampler2D metalnessMap; #endif`, wf = `#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`, Cf = `#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`, Rf = `#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`, Af = `#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`, Pf = `#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`, Df = `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;`, Lf = `#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`, If = `#ifndef FLAT_SHADED varying vec3 vNormal; #ifdef USE_TANGENT varying vec3 vTangent; varying vec3 vBitangent; #endif #endif`, Uf = `#ifndef FLAT_SHADED varying vec3 vNormal; #ifdef USE_TANGENT varying vec3 vTangent; varying vec3 vBitangent; #endif #endif`, Nf = `#ifndef FLAT_SHADED vNormal = normalize( transformedNormal ); #ifdef USE_TANGENT vTangent = normalize( transformedTangent ); vBitangent = normalize( cross( vNormal, vTangent ) * tangent.w ); #endif #endif`, Of = `#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`, Bf = `#ifdef USE_CLEARCOAT vec3 clearcoatNormal = nonPerturbedNormal; #endif`, Ff = `#ifdef USE_CLEARCOAT_NORMALMAP vec3 clearcoatMapN = texture2D( clearcoatNormalMap, vClearcoatNormalMapUv ).xyz * 2.0 - 1.0; clearcoatMapN.xy *= clearcoatNormalScale; clearcoatNormal = normalize( tbn2 * clearcoatMapN ); #endif`, zf = `#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`, kf = `#ifdef USE_IRIDESCENCEMAP uniform sampler2D iridescenceMap; #endif #ifdef USE_IRIDESCENCE_THICKNESSMAP uniform sampler2D iridescenceThicknessMap; #endif`, Hf = `#ifdef OPAQUE diffuseColor.a = 1.0; #endif #ifdef USE_TRANSMISSION diffuseColor.a *= material.transmissionAlpha; #endif gl_FragColor = vec4( outgoingLight, diffuseColor.a );`, Vf = `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 ); }`, Gf = `#ifdef PREMULTIPLIED_ALPHA gl_FragColor.rgb *= gl_FragColor.a; #endif`, Wf = `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;`, jf = `#ifdef DITHERING gl_FragColor.rgb = dithering( gl_FragColor.rgb ); #endif`, Xf = `#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`, qf = `float roughnessFactor = roughness; #ifdef USE_ROUGHNESSMAP vec4 texelRoughness = texture2D( roughnessMap, vRoughnessMapUv ); roughnessFactor *= texelRoughness.g; #endif`, Yf = `#ifdef USE_ROUGHNESSMAP uniform sampler2D roughnessMap; #endif`, Kf = `#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`, Zf = `#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`, Jf = `#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`, $f = `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; }`, Qf = `#ifdef USE_SKINNING mat4 boneMatX = getBoneMatrix( skinIndex.x ); mat4 boneMatY = getBoneMatrix( skinIndex.y ); mat4 boneMatZ = getBoneMatrix( skinIndex.z ); mat4 boneMatW = getBoneMatrix( skinIndex.w ); #endif`, em = `#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`, tm = `#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`, im = `#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`, rm = `float specularStrength; #ifdef USE_SPECULARMAP vec4 texelSpecular = texture2D( specularMap, vSpecularMapUv ); specularStrength = texelSpecular.r; #else specularStrength = 1.0; #endif`, sm = `#ifdef USE_SPECULARMAP uniform sampler2D specularMap; #endif`, nm = `#if defined( TONE_MAPPING ) gl_FragColor.rgb = toneMapping( gl_FragColor.rgb ); #endif`, am = `#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; }`, om = `#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`, lm = `#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`, cm = `#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`, hm = `#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`, um = `#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`, dm = `#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 pm = `varying vec2 vUv; uniform mat3 uvTransform; void main() { vUv = ( uvTransform * vec3( uv, 1 ) ).xy; gl_Position = vec4( position.xy, 1.0, 1.0 ); }`, fm = `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 }`, mm = `varying vec3 vWorldDirection; #include void main() { vWorldDirection = transformDirection( position, modelMatrix ); #include #include gl_Position.z = gl_Position.w; }`, gm = `#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 }`, vm = `varying vec3 vWorldDirection; #include void main() { vWorldDirection = transformDirection( position, modelMatrix ); #include #include gl_Position.z = gl_Position.w; }`, _m = `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 }`, xm = `#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; }`, ym = `#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 }`, Mm = `#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; }`, Sm = `#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 ); }`, bm = `varying vec3 vWorldDirection; #include void main() { vWorldDirection = transformDirection( position, modelMatrix ); #include #include }`, Tm = `uniform sampler2D tEquirect; varying vec3 vWorldDirection; #include void main() { vec3 direction = normalize( vWorldDirection ); vec2 sampleUV = equirectUv( direction ); gl_FragColor = texture2D( tEquirect, sampleUV ); #include #include }`, Em = `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 }`, wm = `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 }`, Cm = `#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 }`, Rm = `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 }`, Am = `#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 }`, Pm = `#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 }`, Dm = `#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; }`, Lm = `#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 }`, Im = `#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 }`, Um = `#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 }`, Nm = `#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 }`, Om = `#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 }`, Bm = `#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 }`, Fm = `#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 }`, zm = `#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 }`, km = `#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 }`, Hm = `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 }`, Vm = `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 }`, Gm = `#include #include #include #include #include #include #include void main() { #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include }`, Wm = `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 }`, jm = `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 }`, Xm = `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 }`, Fe = { alphahash_fragment: pp, alphahash_pars_fragment: fp, alphamap_fragment: mp, alphamap_pars_fragment: gp, alphatest_fragment: vp, alphatest_pars_fragment: _p, aomap_fragment: xp, aomap_pars_fragment: yp, batching_pars_vertex: Mp, batching_vertex: Sp, begin_vertex: bp, beginnormal_vertex: Tp, bsdfs: Ep, iridescence_fragment: wp, bumpmap_pars_fragment: Cp, clipping_planes_fragment: Rp, clipping_planes_pars_fragment: Ap, clipping_planes_pars_vertex: Pp, clipping_planes_vertex: Dp, color_fragment: Lp, color_pars_fragment: Ip, color_pars_vertex: Up, color_vertex: Np, common: Op, cube_uv_reflection_fragment: Bp, defaultnormal_vertex: Fp, displacementmap_pars_vertex: zp, displacementmap_vertex: kp, emissivemap_fragment: Hp, emissivemap_pars_fragment: Vp, colorspace_fragment: Gp, colorspace_pars_fragment: Wp, envmap_fragment: jp, envmap_common_pars_fragment: Xp, envmap_pars_fragment: qp, envmap_pars_vertex: Yp, envmap_physical_pars_fragment: af, envmap_vertex: Kp, fog_vertex: Zp, fog_pars_vertex: Jp, fog_fragment: $p, fog_pars_fragment: Qp, gradientmap_pars_fragment: ef, lightmap_pars_fragment: tf, lights_lambert_fragment: rf, lights_lambert_pars_fragment: sf, lights_pars_begin: nf, lights_toon_fragment: of, lights_toon_pars_fragment: lf, lights_phong_fragment: cf, lights_phong_pars_fragment: hf, lights_physical_fragment: uf, lights_physical_pars_fragment: df, lights_fragment_begin: pf, lights_fragment_maps: ff, lights_fragment_end: mf, logdepthbuf_fragment: gf, logdepthbuf_pars_fragment: vf, logdepthbuf_pars_vertex: _f, logdepthbuf_vertex: xf, map_fragment: yf, map_pars_fragment: Mf, map_particle_fragment: Sf, map_particle_pars_fragment: bf, metalnessmap_fragment: Tf, metalnessmap_pars_fragment: Ef, morphinstance_vertex: wf, morphcolor_vertex: Cf, morphnormal_vertex: Rf, morphtarget_pars_vertex: Af, morphtarget_vertex: Pf, normal_fragment_begin: Df, normal_fragment_maps: Lf, normal_pars_fragment: If, normal_pars_vertex: Uf, normal_vertex: Nf, normalmap_pars_fragment: Of, clearcoat_normal_fragment_begin: Bf, clearcoat_normal_fragment_maps: Ff, clearcoat_pars_fragment: zf, iridescence_pars_fragment: kf, opaque_fragment: Hf, packing: Vf, premultiplied_alpha_fragment: Gf, project_vertex: Wf, dithering_fragment: jf, dithering_pars_fragment: Xf, roughnessmap_fragment: qf, roughnessmap_pars_fragment: Yf, shadowmap_pars_fragment: Kf, shadowmap_pars_vertex: Zf, shadowmap_vertex: Jf, shadowmask_pars_fragment: $f, skinbase_vertex: Qf, skinning_pars_vertex: em, skinning_vertex: tm, skinnormal_vertex: im, specularmap_fragment: rm, specularmap_pars_fragment: sm, tonemapping_fragment: nm, tonemapping_pars_fragment: am, transmission_fragment: om, transmission_pars_fragment: lm, uv_pars_fragment: cm, uv_pars_vertex: hm, uv_vertex: um, worldpos_vertex: dm, background_vert: pm, background_frag: fm, backgroundCube_vert: mm, backgroundCube_frag: gm, cube_vert: vm, cube_frag: _m, depth_vert: xm, depth_frag: ym, distanceRGBA_vert: Mm, distanceRGBA_frag: Sm, equirect_vert: bm, equirect_frag: Tm, linedashed_vert: Em, linedashed_frag: wm, meshbasic_vert: Cm, meshbasic_frag: Rm, meshlambert_vert: Am, meshlambert_frag: Pm, meshmatcap_vert: Dm, meshmatcap_frag: Lm, meshnormal_vert: Im, meshnormal_frag: Um, meshphong_vert: Nm, meshphong_frag: Om, meshphysical_vert: Bm, meshphysical_frag: Fm, meshtoon_vert: zm, meshtoon_frag: km, points_vert: Hm, points_frag: Vm, shadow_vert: Gm, shadow_frag: Wm, sprite_vert: jm, sprite_frag: Xm }, ce = { common: { diffuse: { value: /* @__PURE__ */ new _e(16777215) }, opacity: { value: 1 }, map: { value: null }, mapTransform: { value: /* @__PURE__ */ new Be() }, alphaMap: { value: null }, alphaMapTransform: { value: /* @__PURE__ */ new Be() }, alphaTest: { value: 0 } }, specularmap: { specularMap: { value: null }, specularMapTransform: { value: /* @__PURE__ */ new Be() } }, envmap: { envMap: { value: null }, envMapRotation: { value: /* @__PURE__ */ new Be() }, flipEnvMap: { value: -1 }, reflectivity: { value: 1 }, // basic, lambert, phong ior: { value: 1.5 }, // physical refractionRatio: { value: 0.98 }, // basic, lambert, phong dfgLUT: { value: null } // DFG LUT for physically-based rendering }, aomap: { aoMap: { value: null }, aoMapIntensity: { value: 1 }, aoMapTransform: { value: /* @__PURE__ */ new Be() } }, lightmap: { lightMap: { value: null }, lightMapIntensity: { value: 1 }, lightMapTransform: { value: /* @__PURE__ */ new Be() } }, bumpmap: { bumpMap: { value: null }, bumpMapTransform: { value: /* @__PURE__ */ new Be() }, bumpScale: { value: 1 } }, normalmap: { normalMap: { value: null }, normalMapTransform: { value: /* @__PURE__ */ new Be() }, normalScale: { value: /* @__PURE__ */ new oe(1, 1) } }, displacementmap: { displacementMap: { value: null }, displacementMapTransform: { value: /* @__PURE__ */ new Be() }, displacementScale: { value: 1 }, displacementBias: { value: 0 } }, emissivemap: { emissiveMap: { value: null }, emissiveMapTransform: { value: /* @__PURE__ */ new Be() } }, metalnessmap: { metalnessMap: { value: null }, metalnessMapTransform: { value: /* @__PURE__ */ new Be() } }, roughnessmap: { roughnessMap: { value: null }, roughnessMapTransform: { value: /* @__PURE__ */ new Be() } }, gradientmap: { gradientMap: { value: null } }, fog: { fogDensity: { value: 25e-5 }, fogNear: { value: 1 }, fogFar: { value: 2e3 }, fogColor: { value: /* @__PURE__ */ new _e(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 _e(16777215) }, opacity: { value: 1 }, size: { value: 1 }, scale: { value: 1 }, map: { value: null }, alphaMap: { value: null }, alphaMapTransform: { value: /* @__PURE__ */ new Be() }, alphaTest: { value: 0 }, uvTransform: { value: /* @__PURE__ */ new Be() } }, sprite: { diffuse: { value: /* @__PURE__ */ new _e(16777215) }, opacity: { value: 1 }, center: { value: /* @__PURE__ */ new oe(0.5, 0.5) }, rotation: { value: 0 }, map: { value: null }, mapTransform: { value: /* @__PURE__ */ new Be() }, alphaMap: { value: null }, alphaMapTransform: { value: /* @__PURE__ */ new Be() }, alphaTest: { value: 0 } } }, Mi = { basic: { uniforms: /* @__PURE__ */ Ot([ ce.common, ce.specularmap, ce.envmap, ce.aomap, ce.lightmap, ce.fog ]), vertexShader: Fe.meshbasic_vert, fragmentShader: Fe.meshbasic_frag }, lambert: { uniforms: /* @__PURE__ */ Ot([ ce.common, ce.specularmap, ce.envmap, ce.aomap, ce.lightmap, ce.emissivemap, ce.bumpmap, ce.normalmap, ce.displacementmap, ce.fog, ce.lights, { emissive: { value: /* @__PURE__ */ new _e(0) } } ]), vertexShader: Fe.meshlambert_vert, fragmentShader: Fe.meshlambert_frag }, phong: { uniforms: /* @__PURE__ */ Ot([ ce.common, ce.specularmap, ce.envmap, ce.aomap, ce.lightmap, ce.emissivemap, ce.bumpmap, ce.normalmap, ce.displacementmap, ce.fog, ce.lights, { emissive: { value: /* @__PURE__ */ new _e(0) }, specular: { value: /* @__PURE__ */ new _e(1118481) }, shininess: { value: 30 } } ]), vertexShader: Fe.meshphong_vert, fragmentShader: Fe.meshphong_frag }, standard: { uniforms: /* @__PURE__ */ Ot([ ce.common, ce.envmap, ce.aomap, ce.lightmap, ce.emissivemap, ce.bumpmap, ce.normalmap, ce.displacementmap, ce.roughnessmap, ce.metalnessmap, ce.fog, ce.lights, { emissive: { value: /* @__PURE__ */ new _e(0) }, roughness: { value: 1 }, metalness: { value: 0 }, envMapIntensity: { value: 1 } } ]), vertexShader: Fe.meshphysical_vert, fragmentShader: Fe.meshphysical_frag }, toon: { uniforms: /* @__PURE__ */ Ot([ ce.common, ce.aomap, ce.lightmap, ce.emissivemap, ce.bumpmap, ce.normalmap, ce.displacementmap, ce.gradientmap, ce.fog, ce.lights, { emissive: { value: /* @__PURE__ */ new _e(0) } } ]), vertexShader: Fe.meshtoon_vert, fragmentShader: Fe.meshtoon_frag }, matcap: { uniforms: /* @__PURE__ */ Ot([ ce.common, ce.bumpmap, ce.normalmap, ce.displacementmap, ce.fog, { matcap: { value: null } } ]), vertexShader: Fe.meshmatcap_vert, fragmentShader: Fe.meshmatcap_frag }, points: { uniforms: /* @__PURE__ */ Ot([ ce.points, ce.fog ]), vertexShader: Fe.points_vert, fragmentShader: Fe.points_frag }, dashed: { uniforms: /* @__PURE__ */ Ot([ ce.common, ce.fog, { scale: { value: 1 }, dashSize: { value: 1 }, totalSize: { value: 2 } } ]), vertexShader: Fe.linedashed_vert, fragmentShader: Fe.linedashed_frag }, depth: { uniforms: /* @__PURE__ */ Ot([ ce.common, ce.displacementmap ]), vertexShader: Fe.depth_vert, fragmentShader: Fe.depth_frag }, normal: { uniforms: /* @__PURE__ */ Ot([ ce.common, ce.bumpmap, ce.normalmap, ce.displacementmap, { opacity: { value: 1 } } ]), vertexShader: Fe.meshnormal_vert, fragmentShader: Fe.meshnormal_frag }, sprite: { uniforms: /* @__PURE__ */ Ot([ ce.sprite, ce.fog ]), vertexShader: Fe.sprite_vert, fragmentShader: Fe.sprite_frag }, background: { uniforms: { uvTransform: { value: /* @__PURE__ */ new Be() }, t2D: { value: null }, backgroundIntensity: { value: 1 } }, vertexShader: Fe.background_vert, fragmentShader: Fe.background_frag }, backgroundCube: { uniforms: { envMap: { value: null }, flipEnvMap: { value: -1 }, backgroundBlurriness: { value: 0 }, backgroundIntensity: { value: 1 }, backgroundRotation: { value: /* @__PURE__ */ new Be() } }, vertexShader: Fe.backgroundCube_vert, fragmentShader: Fe.backgroundCube_frag }, cube: { uniforms: { tCube: { value: null }, tFlip: { value: -1 }, opacity: { value: 1 } }, vertexShader: Fe.cube_vert, fragmentShader: Fe.cube_frag }, equirect: { uniforms: { tEquirect: { value: null } }, vertexShader: Fe.equirect_vert, fragmentShader: Fe.equirect_frag }, distanceRGBA: { uniforms: /* @__PURE__ */ Ot([ ce.common, ce.displacementmap, { referencePosition: { value: /* @__PURE__ */ new w() }, nearDistance: { value: 1 }, farDistance: { value: 1e3 } } ]), vertexShader: Fe.distanceRGBA_vert, fragmentShader: Fe.distanceRGBA_frag }, shadow: { uniforms: /* @__PURE__ */ Ot([ ce.lights, ce.fog, { color: { value: /* @__PURE__ */ new _e(0) }, opacity: { value: 1 } } ]), vertexShader: Fe.shadow_vert, fragmentShader: Fe.shadow_frag } }; Mi.physical = { uniforms: /* @__PURE__ */ Ot([ Mi.standard.uniforms, { clearcoat: { value: 0 }, clearcoatMap: { value: null }, clearcoatMapTransform: { value: /* @__PURE__ */ new Be() }, clearcoatNormalMap: { value: null }, clearcoatNormalMapTransform: { value: /* @__PURE__ */ new Be() }, clearcoatNormalScale: { value: /* @__PURE__ */ new oe(1, 1) }, clearcoatRoughness: { value: 0 }, clearcoatRoughnessMap: { value: null }, clearcoatRoughnessMapTransform: { value: /* @__PURE__ */ new Be() }, dispersion: { value: 0 }, iridescence: { value: 0 }, iridescenceMap: { value: null }, iridescenceMapTransform: { value: /* @__PURE__ */ new Be() }, iridescenceIOR: { value: 1.3 }, iridescenceThicknessMinimum: { value: 100 }, iridescenceThicknessMaximum: { value: 400 }, iridescenceThicknessMap: { value: null }, iridescenceThicknessMapTransform: { value: /* @__PURE__ */ new Be() }, sheen: { value: 0 }, sheenColor: { value: /* @__PURE__ */ new _e(0) }, sheenColorMap: { value: null }, sheenColorMapTransform: { value: /* @__PURE__ */ new Be() }, sheenRoughness: { value: 1 }, sheenRoughnessMap: { value: null }, sheenRoughnessMapTransform: { value: /* @__PURE__ */ new Be() }, transmission: { value: 0 }, transmissionMap: { value: null }, transmissionMapTransform: { value: /* @__PURE__ */ new Be() }, transmissionSamplerSize: { value: /* @__PURE__ */ new oe() }, transmissionSamplerMap: { value: null }, thickness: { value: 0 }, thicknessMap: { value: null }, thicknessMapTransform: { value: /* @__PURE__ */ new Be() }, attenuationDistance: { value: 0 }, attenuationColor: { value: /* @__PURE__ */ new _e(0) }, specularColor: { value: /* @__PURE__ */ new _e(1, 1, 1) }, specularColorMap: { value: null }, specularColorMapTransform: { value: /* @__PURE__ */ new Be() }, specularIntensity: { value: 1 }, specularIntensityMap: { value: null }, specularIntensityMapTransform: { value: /* @__PURE__ */ new Be() }, anisotropyVector: { value: /* @__PURE__ */ new oe() }, anisotropyMap: { value: null }, anisotropyMapTransform: { value: /* @__PURE__ */ new Be() } } ]), vertexShader: Fe.meshphysical_vert, fragmentShader: Fe.meshphysical_frag }; const an = { r: 0, b: 0, g: 0 }, lr = /* @__PURE__ */ new gi(), qm = /* @__PURE__ */ new Ue(); function Ym(r, e, t, i, s, n, a) { const o = new _e(0); let l = n === !0 ? 0 : 1, c, h, u = null, d = 0, f = null; function g(_) { let E = _.isScene === !0 ? _.background : null; return E && E.isTexture && (E = (_.backgroundBlurriness > 0 ? t : e).get(E)), E; } function v(_) { let E = !1; const A = g(_); A === null ? p(o, l) : A && A.isColor && (p(A, 1), E = !0); const T = r.xr.getEnvironmentBlendMode(); T === "additive" ? i.buffers.color.setClear(0, 0, 0, 1, a) : T === "alpha-blend" && i.buffers.color.setClear(0, 0, 0, 0, a), (r.autoClear || E) && (i.buffers.depth.setTest(!0), i.buffers.depth.setMask(!0), i.buffers.color.setMask(!0), r.clear(r.autoClearColor, r.autoClearDepth, r.autoClearStencil)); } function m(_, E) { const A = g(E); A && (A.isCubeTexture || A.mapping === Pn) ? (h === void 0 && (h = new nt( new fr(1, 1, 1), new ct({ name: "BackgroundCubeMaterial", uniforms: Yr(Mi.backgroundCube.uniforms), vertexShader: Mi.backgroundCube.vertexShader, fragmentShader: Mi.backgroundCube.fragmentShader, side: Ft, depthTest: !1, depthWrite: !1, fog: !1, allowOverride: !1 }) ), h.geometry.deleteAttribute("normal"), h.geometry.deleteAttribute("uv"), h.onBeforeRender = function(T, R, I) { this.matrixWorld.copyPosition(I.matrixWorld); }, Object.defineProperty(h.material, "envMap", { get: function() { return this.uniforms.envMap.value; } }), s.update(h)), lr.copy(E.backgroundRotation), lr.x *= -1, lr.y *= -1, lr.z *= -1, A.isCubeTexture && A.isRenderTargetTexture === !1 && (lr.y *= -1, lr.z *= -1), h.material.uniforms.envMap.value = A, h.material.uniforms.flipEnvMap.value = A.isCubeTexture && A.isRenderTargetTexture === !1 ? -1 : 1, h.material.uniforms.backgroundBlurriness.value = E.backgroundBlurriness, h.material.uniforms.backgroundIntensity.value = E.backgroundIntensity, h.material.uniforms.backgroundRotation.value.setFromMatrix4(qm.makeRotationFromEuler(lr)), h.material.toneMapped = Xe.getTransfer(A.colorSpace) !== et, (u !== A || d !== A.version || f !== r.toneMapping) && (h.material.needsUpdate = !0, u = A, d = A.version, f = r.toneMapping), h.layers.enableAll(), _.unshift(h, h.geometry, h.material, 0, 0, null)) : A && A.isTexture && (c === void 0 && (c = new nt( new Rs(2, 2), new ct({ name: "BackgroundMaterial", uniforms: Yr(Mi.background.uniforms), vertexShader: Mi.background.vertexShader, fragmentShader: Mi.background.fragmentShader, side: Ti, depthTest: !1, depthWrite: !1, fog: !1, allowOverride: !1 }) ), c.geometry.deleteAttribute("normal"), Object.defineProperty(c.material, "map", { get: function() { return this.uniforms.t2D.value; } }), s.update(c)), c.material.uniforms.t2D.value = A, c.material.uniforms.backgroundIntensity.value = E.backgroundIntensity, c.material.toneMapped = Xe.getTransfer(A.colorSpace) !== et, A.matrixAutoUpdate === !0 && A.updateMatrix(), c.material.uniforms.uvTransform.value.copy(A.matrix), (u !== A || d !== A.version || f !== r.toneMapping) && (c.material.needsUpdate = !0, u = A, d = A.version, f = r.toneMapping), c.layers.enableAll(), _.unshift(c, c.geometry, c.material, 0, 0, null)); } function p(_, E) { _.getRGB(an, lh(r)), i.buffers.color.setClear(an.r, an.g, an.b, E, a); } function y() { h !== void 0 && (h.geometry.dispose(), h.material.dispose(), h = void 0), c !== void 0 && (c.geometry.dispose(), c.material.dispose(), c = void 0); } return { getClearColor: function() { return o; }, setClearColor: function(_, E = 1) { o.set(_), l = E, p(o, l); }, getClearAlpha: function() { return l; }, setClearAlpha: function(_) { l = _, p(o, l); }, render: v, addToRenderList: m, dispose: y }; } function Km(r, e) { const t = r.getParameter(r.MAX_VERTEX_ATTRIBS), i = {}, s = d(null); let n = s, a = !1; function o(S, D, N, k, H) { let j = !1; const q = u(k, N, D); n !== q && (n = q, c(n.object)), j = f(S, k, N, H), j && g(S, k, N, H), H !== null && e.update(H, r.ELEMENT_ARRAY_BUFFER), (j || a) && (a = !1, E(S, D, N, k), H !== null && r.bindBuffer(r.ELEMENT_ARRAY_BUFFER, e.get(H).buffer)); } function l() { return r.createVertexArray(); } function c(S) { return r.bindVertexArray(S); } function h(S) { return r.deleteVertexArray(S); } function u(S, D, N) { const k = N.wireframe === !0; let H = i[S.id]; H === void 0 && (H = {}, i[S.id] = H); let j = H[D.id]; j === void 0 && (j = {}, H[D.id] = j); let q = j[k]; return q === void 0 && (q = d(l()), j[k] = q), q; } function d(S) { const D = [], N = [], k = []; for (let H = 0; H < t; H++) D[H] = 0, N[H] = 0, k[H] = 0; return { // for backward compatibility on non-VAO support browser geometry: null, program: null, wireframe: !1, newAttributes: D, enabledAttributes: N, attributeDivisors: k, object: S, attributes: {}, index: null }; } function f(S, D, N, k) { const H = n.attributes, j = D.attributes; let q = 0; const te = N.getAttributes(); for (const G in te) if (te[G].location >= 0) { const Z = H[G]; let se = j[G]; if (se === void 0 && (G === "instanceMatrix" && S.instanceMatrix && (se = S.instanceMatrix), G === "instanceColor" && S.instanceColor && (se = S.instanceColor)), Z === void 0 || Z.attribute !== se || se && Z.data !== se.data) return !0; q++; } return n.attributesNum !== q || n.index !== k; } function g(S, D, N, k) { const H = {}, j = D.attributes; let q = 0; const te = N.getAttributes(); for (const G in te) if (te[G].location >= 0) { let Z = j[G]; Z === void 0 && (G === "instanceMatrix" && S.instanceMatrix && (Z = S.instanceMatrix), G === "instanceColor" && S.instanceColor && (Z = S.instanceColor)); const se = {}; se.attribute = Z, Z && Z.data && (se.data = Z.data), H[G] = se, q++; } n.attributes = H, n.attributesNum = q, n.index = k; } function v() { const S = n.newAttributes; for (let D = 0, N = S.length; D < N; D++) S[D] = 0; } function m(S) { p(S, 0); } function p(S, D) { const N = n.newAttributes, k = n.enabledAttributes, H = n.attributeDivisors; N[S] = 1, k[S] === 0 && (r.enableVertexAttribArray(S), k[S] = 1), H[S] !== D && (r.vertexAttribDivisor(S, D), H[S] = D); } function y() { const S = n.newAttributes, D = n.enabledAttributes; for (let N = 0, k = D.length; N < k; N++) D[N] !== S[N] && (r.disableVertexAttribArray(N), D[N] = 0); } function _(S, D, N, k, H, j, q) { q === !0 ? r.vertexAttribIPointer(S, D, N, H, j) : r.vertexAttribPointer(S, D, N, k, H, j); } function E(S, D, N, k) { v(); const H = k.attributes, j = N.getAttributes(), q = D.defaultAttributeValues; for (const te in j) { const G = j[te]; if (G.location >= 0) { let Z = H[te]; if (Z === void 0 && (te === "instanceMatrix" && S.instanceMatrix && (Z = S.instanceMatrix), te === "instanceColor" && S.instanceColor && (Z = S.instanceColor)), Z !== void 0) { const se = Z.normalized, Pe = Z.itemSize, ke = e.get(Z); if (ke === void 0) continue; const qe = ke.buffer, Ke = ke.type, Ze = ke.bytesPerElement, W = Ke === r.INT || Ke === r.UNSIGNED_INT || Z.gpuType === wo; if (Z.isInterleavedBufferAttribute) { const Y = Z.data, ue = Y.stride, Ce = Z.offset; if (Y.isInstancedInterleavedBuffer) { for (let be = 0; be < G.locationSize; be++) p(G.location + be, Y.meshPerAttribute); S.isInstancedMesh !== !0 && k._maxInstanceCount === void 0 && (k._maxInstanceCount = Y.meshPerAttribute * Y.count); } else for (let be = 0; be < G.locationSize; be++) m(G.location + be); r.bindBuffer(r.ARRAY_BUFFER, qe); for (let be = 0; be < G.locationSize; be++) _( G.location + be, Pe / G.locationSize, Ke, se, ue * Ze, (Ce + Pe / G.locationSize * be) * Ze, W ); } else { if (Z.isInstancedBufferAttribute) { for (let Y = 0; Y < G.locationSize; Y++) p(G.location + Y, Z.meshPerAttribute); S.isInstancedMesh !== !0 && k._maxInstanceCount === void 0 && (k._maxInstanceCount = Z.meshPerAttribute * Z.count); } else for (let Y = 0; Y < G.locationSize; Y++) m(G.location + Y); r.bindBuffer(r.ARRAY_BUFFER, qe); for (let Y = 0; Y < G.locationSize; Y++) _( G.location + Y, Pe / G.locationSize, Ke, se, Pe * Ze, Pe / G.locationSize * Y * Ze, W ); } } else if (q !== void 0) { const se = q[te]; if (se !== void 0) switch (se.length) { case 2: r.vertexAttrib2fv(G.location, se); break; case 3: r.vertexAttrib3fv(G.location, se); break; case 4: r.vertexAttrib4fv(G.location, se); break; default: r.vertexAttrib1fv(G.location, se); } } } } y(); } function A() { I(); for (const S in i) { const D = i[S]; for (const N in D) { const k = D[N]; for (const H in k) h(k[H].object), delete k[H]; delete D[N]; } delete i[S]; } } function T(S) { if (i[S.id] === void 0) return; const D = i[S.id]; for (const N in D) { const k = D[N]; for (const H in k) h(k[H].object), delete k[H]; delete D[N]; } delete i[S.id]; } function R(S) { for (const D in i) { const N = i[D]; if (N[S.id] === void 0) continue; const k = N[S.id]; for (const H in k) h(k[H].object), delete k[H]; delete N[S.id]; } } function I() { b(), a = !0, n !== s && (n = s, c(n.object)); } function b() { s.geometry = null, s.program = null, s.wireframe = !1; } return { setup: o, reset: I, resetDefaultState: b, dispose: A, releaseStatesOfGeometry: T, releaseStatesOfProgram: R, initAttributes: v, enableAttribute: m, disableUnusedAttributes: y }; } function Zm(r, e, t) { let i; function s(c) { i = c; } function n(c, h) { r.drawArrays(i, c, h), t.update(h, i, 1); } function a(c, h, u) { u !== 0 && (r.drawArraysInstanced(i, c, h, u), t.update(h, i, u)); } function o(c, h, u) { if (u === 0) return; e.get("WEBGL_multi_draw").multiDrawArraysWEBGL(i, c, 0, h, 0, u); let d = 0; for (let f = 0; f < u; f++) d += h[f]; t.update(d, i, 1); } function l(c, h, u, d) { if (u === 0) return; const f = e.get("WEBGL_multi_draw"); if (f === null) for (let g = 0; g < c.length; g++) a(c[g], h[g], d[g]); else { f.multiDrawArraysInstancedWEBGL(i, c, 0, h, 0, d, 0, u); let g = 0; for (let v = 0; v < u; v++) g += h[v] * d[v]; t.update(g, i, 1); } } this.setMode = s, this.render = n, this.renderInstances = a, this.renderMultiDraw = o, this.renderMultiDrawInstances = l; } function Jm(r, e, t, i) { let s; function n() { if (s !== void 0) return s; if (e.has("EXT_texture_filter_anisotropic") === !0) { const R = e.get("EXT_texture_filter_anisotropic"); s = r.getParameter(R.MAX_TEXTURE_MAX_ANISOTROPY_EXT); } else s = 0; return s; } function a(R) { return !(R !== qt && i.convert(R) !== r.getParameter(r.IMPLEMENTATION_COLOR_READ_FORMAT)); } function o(R) { const I = R === ft && (e.has("EXT_color_buffer_half_float") || e.has("EXT_color_buffer_float")); return !(R !== fi && i.convert(R) !== r.getParameter(r.IMPLEMENTATION_COLOR_READ_TYPE) && // Edge and Chrome Mac < 52 (#9513) R !== Gt && !I); } function l(R) { if (R === "highp") { if (r.getShaderPrecisionFormat(r.VERTEX_SHADER, r.HIGH_FLOAT).precision > 0 && r.getShaderPrecisionFormat(r.FRAGMENT_SHADER, r.HIGH_FLOAT).precision > 0) return "highp"; R = "mediump"; } return R === "mediump" && r.getShaderPrecisionFormat(r.VERTEX_SHADER, r.MEDIUM_FLOAT).precision > 0 && r.getShaderPrecisionFormat(r.FRAGMENT_SHADER, r.MEDIUM_FLOAT).precision > 0 ? "mediump" : "lowp"; } let c = t.precision !== void 0 ? t.precision : "highp"; const h = l(c); h !== c && (Se("WebGLRenderer:", c, "not supported, using", h, "instead."), c = h); const u = t.logarithmicDepthBuffer === !0, d = t.reversedDepthBuffer === !0 && e.has("EXT_clip_control"), f = r.getParameter(r.MAX_TEXTURE_IMAGE_UNITS), g = r.getParameter(r.MAX_VERTEX_TEXTURE_IMAGE_UNITS), v = r.getParameter(r.MAX_TEXTURE_SIZE), m = r.getParameter(r.MAX_CUBE_MAP_TEXTURE_SIZE), p = r.getParameter(r.MAX_VERTEX_ATTRIBS), y = r.getParameter(r.MAX_VERTEX_UNIFORM_VECTORS), _ = r.getParameter(r.MAX_VARYING_VECTORS), E = r.getParameter(r.MAX_FRAGMENT_UNIFORM_VECTORS), A = g > 0, T = r.getParameter(r.MAX_SAMPLES); return { isWebGL2: !0, // keeping this for backwards compatibility getMaxAnisotropy: n, getMaxPrecision: l, textureFormatReadable: a, textureTypeReadable: o, precision: c, logarithmicDepthBuffer: u, reversedDepthBuffer: d, maxTextures: f, maxVertexTextures: g, maxTextureSize: v, maxCubemapSize: m, maxAttributes: p, maxVertexUniforms: y, maxVaryings: _, maxFragmentUniforms: E, vertexTextures: A, maxSamples: T }; } function $m(r) { const e = this; let t = null, i = 0, s = !1, n = !1; const a = new yi(), o = new Be(), l = { value: null, needsUpdate: !1 }; this.uniform = l, this.numPlanes = 0, this.numIntersection = 0, this.init = function(u, d) { const f = u.length !== 0 || d || // enable state of previous frame - the clipping code has to // run another frame in order to reset the state: i !== 0 || s; return s = d, i = u.length, f; }, this.beginShadows = function() { n = !0, h(null); }, this.endShadows = function() { n = !1; }, this.setGlobalState = function(u, d) { t = h(u, d, 0); }, this.setState = function(u, d, f) { const g = u.clippingPlanes, v = u.clipIntersection, m = u.clipShadows, p = r.get(u); if (!s || g === null || g.length === 0 || n && !m) n ? h(null) : c(); else { const y = n ? 0 : i, _ = y * 4; let E = p.clippingState || null; l.value = E, E = h(g, d, _, f); for (let A = 0; A !== _; ++A) E[A] = t[A]; p.clippingState = E, this.numIntersection = v ? this.numPlanes : 0, this.numPlanes += y; } }; function c() { l.value !== t && (l.value = t, l.needsUpdate = i > 0), e.numPlanes = i, e.numIntersection = 0; } function h(u, d, f, g) { const v = u !== null ? u.length : 0; let m = null; if (v !== 0) { if (m = l.value, g !== !0 || m === null) { const p = f + v * 4, y = d.matrixWorldInverse; o.getNormalMatrix(y), (m === null || m.length < p) && (m = new Float32Array(p)); for (let _ = 0, E = f; _ !== v; ++_, E += 4) a.copy(u[_]).applyMatrix4(y, o), a.normal.toArray(m, E), m[E + 3] = a.constant; } l.value = m, l.needsUpdate = !0; } return e.numPlanes = v, e.numIntersection = 0, m; } } function Qm(r) { let e = /* @__PURE__ */ new WeakMap(); function t(a, o) { return o === Mn ? a.mapping = Gr : o === Na && (a.mapping = Wr), a; } function i(a) { if (a && a.isTexture) { const o = a.mapping; if (o === Mn || o === Na) if (e.has(a)) { const l = e.get(a).texture; return t(l, a.mapping); } else { const l = a.image; if (l && l.height > 0) { const c = new gd(l.height); return c.fromEquirectangularTexture(r, a), e.set(a, c), a.addEventListener("dispose", s), t(c.texture, a.mapping); } else return null; } } return a; } function s(a) { const o = a.target; o.removeEventListener("dispose", s); const l = e.get(o); l !== void 0 && (e.delete(o), l.dispose()); } function n() { e = /* @__PURE__ */ new WeakMap(); } return { get: i, dispose: n }; } const Zi = 4, ec = [0.125, 0.215, 0.35, 0.446, 0.526, 0.582], ur = 20, eg = 256, ps = /* @__PURE__ */ new mr(), tc = /* @__PURE__ */ new _e(); let pa = null, fa = 0, ma = 0, ga = !1; const tg = /* @__PURE__ */ new w(); class ic { /** * Constructs a new PMREM generator. * * @param {WebGLRenderer} renderer - The renderer. */ constructor(e) { this._renderer = e, this._pingPongRenderTarget = null, this._lodMax = 0, this._cubeSize = 0, this._sizeLods = [], this._sigmas = [], this._lodMeshes = [], this._backgroundBox = null, this._cubemapMaterial = null, this._equirectMaterial = null, this._blurMaterial = null, this._ggxMaterial = null; } /** * Generates a PMREM from a supplied Scene, which can be faster than using an * image if networking bandwidth is low. Optional sigma specifies a blur radius * in radians to be applied to the scene before PMREM generation. Optional near * and far planes ensure the scene is rendered in its entirety. * * @param {Scene} scene - The scene to be captured. * @param {number} [sigma=0] - The blur radius in radians. * @param {number} [near=0.1] - The near plane distance. * @param {number} [far=100] - The far plane distance. * @param {Object} [options={}] - The configuration options. * @param {number} [options.size=256] - The texture size of the PMREM. * @param {Vector3} [options.renderTarget=origin] - The position of the internal cube camera that renders the scene. * @return {WebGLRenderTarget} The resulting PMREM. */ fromScene(e, t = 0, i = 0.1, s = 100, n = {}) { const { size: a = 256, position: o = tg } = n; pa = this._renderer.getRenderTarget(), fa = this._renderer.getActiveCubeFace(), ma = this._renderer.getActiveMipmapLevel(), ga = this._renderer.xr.enabled, this._renderer.xr.enabled = !1, this._setSize(a); const l = this._allocateTargets(); return l.depthBuffer = !0, this._sceneToCubeUV(e, i, s, l, o), t > 0 && this._blur(l, 0, 0, t), this._applyPMREM(l), this._cleanup(l), l; } /** * Generates a PMREM from an equirectangular texture, which can be either LDR * or HDR. The ideal input image size is 1k (1024 x 512), * as this matches best with the 256 x 256 cubemap output. * * @param {Texture} equirectangular - The equirectangular texture to be converted. * @param {?WebGLRenderTarget} [renderTarget=null] - The render target to use. * @return {WebGLRenderTarget} The resulting PMREM. */ fromEquirectangular(e, t = null) { return this._fromTexture(e, t); } /** * Generates a PMREM from an cubemap texture, which can be either LDR * or HDR. The ideal input cube size is 256 x 256, * as this matches best with the 256 x 256 cubemap output. * * @param {Texture} cubemap - The cubemap texture to be converted. * @param {?WebGLRenderTarget} [renderTarget=null] - The render target to use. * @return {WebGLRenderTarget} The resulting PMREM. */ fromCubemap(e, t = null) { return this._fromTexture(e, t); } /** * Pre-compiles the cubemap shader. You can get faster start-up by invoking this method during * your texture's network fetch for increased concurrency. */ compileCubemapShader() { this._cubemapMaterial === null && (this._cubemapMaterial = nc(), 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 = sc(), 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(), this._backgroundBox !== null && (this._backgroundBox.geometry.dispose(), this._backgroundBox.material.dispose()); } // private interface _setSize(e) { this._lodMax = Math.floor(Math.log2(e)), this._cubeSize = Math.pow(2, this._lodMax); } _dispose() { this._blurMaterial !== null && this._blurMaterial.dispose(), this._ggxMaterial !== null && this._ggxMaterial.dispose(), this._pingPongRenderTarget !== null && this._pingPongRenderTarget.dispose(); for (let e = 0; e < this._lodMeshes.length; e++) this._lodMeshes[e].geometry.dispose(); } _cleanup(e) { this._renderer.setRenderTarget(pa, fa, ma), this._renderer.xr.enabled = ga, e.scissorTest = !1, Ir(e, 0, 0, e.width, e.height); } _fromTexture(e, t) { e.mapping === Gr || e.mapping === Wr ? this._setSize(e.image.length === 0 ? 16 : e.image[0].width || e.image[0].image.width) : this._setSize(e.image.width / 4), pa = this._renderer.getRenderTarget(), fa = this._renderer.getActiveCubeFace(), ma = this._renderer.getActiveMipmapLevel(), ga = this._renderer.xr.enabled, this._renderer.xr.enabled = !1; const i = t || this._allocateTargets(); return this._textureToCubeUV(e, i), this._applyPMREM(i), this._cleanup(i), i; } _allocateTargets() { const e = 3 * Math.max(this._cubeSize, 112), t = 4 * this._cubeSize, i = { magFilter: xt, minFilter: xt, generateMipmaps: !1, type: ft, format: qt, colorSpace: Ut, depthBuffer: !1 }, s = rc(e, t, i); if (this._pingPongRenderTarget === null || this._pingPongRenderTarget.width !== e || this._pingPongRenderTarget.height !== t) { this._pingPongRenderTarget !== null && this._dispose(), this._pingPongRenderTarget = rc(e, t, i); const { _lodMax: n } = this; ({ lodMeshes: this._lodMeshes, sizeLods: this._sizeLods, sigmas: this._sigmas } = ig(n)), this._blurMaterial = sg(n, e, t), this._ggxMaterial = rg(n, e, t); } return s; } _compileMaterial(e) { const t = new nt(new Qt(), e); this._renderer.compile(t, ps); } _sceneToCubeUV(e, t, i, s, n) { const a = new Mt(90, 1, t, i), o = [1, -1, 1, 1, 1, 1], l = [1, 1, 1, -1, -1, -1], c = this._renderer, h = c.autoClear, u = c.toneMapping; c.getClearColor(tc), c.toneMapping = $i, c.autoClear = !1, c.state.buffers.depth.getReversed() && (c.setRenderTarget(s), c.clearDepth(), c.setRenderTarget(null)), this._backgroundBox === null && (this._backgroundBox = new nt( new fr(), new Bt({ name: "PMREM.Background", side: Ft, depthWrite: !1, depthTest: !1 }) )); const d = this._backgroundBox, f = d.material; let g = !1; const v = e.background; v ? v.isColor && (f.color.copy(v), e.background = null, g = !0) : (f.color.copy(tc), g = !0); for (let m = 0; m < 6; m++) { const p = m % 3; p === 0 ? (a.up.set(0, o[m], 0), a.position.set(n.x, n.y, n.z), a.lookAt(n.x + l[m], n.y, n.z)) : p === 1 ? (a.up.set(0, 0, o[m]), a.position.set(n.x, n.y, n.z), a.lookAt(n.x, n.y + l[m], n.z)) : (a.up.set(0, o[m], 0), a.position.set(n.x, n.y, n.z), a.lookAt(n.x, n.y, n.z + l[m])); const y = this._cubeSize; Ir(s, p * y, m > 2 ? y : 0, y, y), c.setRenderTarget(s), g && c.render(d, a), c.render(e, a); } c.toneMapping = u, c.autoClear = h, e.background = v; } _textureToCubeUV(e, t) { const i = this._renderer, s = e.mapping === Gr || e.mapping === Wr; s ? (this._cubemapMaterial === null && (this._cubemapMaterial = nc()), this._cubemapMaterial.uniforms.flipEnvMap.value = e.isRenderTargetTexture === !1 ? -1 : 1) : this._equirectMaterial === null && (this._equirectMaterial = sc()); const n = s ? this._cubemapMaterial : this._equirectMaterial, a = this._lodMeshes[0]; a.material = n; const o = n.uniforms; o.envMap.value = e; const l = this._cubeSize; Ir(t, 0, 0, 3 * l, 2 * l), i.setRenderTarget(t), i.render(a, ps); } _applyPMREM(e) { const t = this._renderer, i = t.autoClear; t.autoClear = !1; const s = this._lodMeshes.length; for (let n = 1; n < s; n++) this._applyGGXFilter(e, n - 1, n); t.autoClear = i; } /** * Applies GGX VNDF importance sampling filter to generate a prefiltered environment map. * Uses Monte Carlo integration with VNDF importance sampling to accurately represent the * GGX BRDF for physically-based rendering. Reads from the previous LOD level and * applies incremental roughness filtering to avoid over-blurring. * * @private * @param {WebGLRenderTarget} cubeUVRenderTarget * @param {number} lodIn - Source LOD level to read from * @param {number} lodOut - Target LOD level to write to */ _applyGGXFilter(e, t, i) { const s = this._renderer, n = this._pingPongRenderTarget, a = this._ggxMaterial, o = this._lodMeshes[i]; o.material = a; const l = a.uniforms, c = i / (this._lodMeshes.length - 1), h = t / (this._lodMeshes.length - 1), u = Math.sqrt(c * c - h * h), d = 0.05 + c * 0.95, f = u * d, { _lodMax: g } = this, v = this._sizeLods[i], m = 3 * v * (i > g - Zi ? i - g + Zi : 0), p = 4 * (this._cubeSize - v); l.envMap.value = e.texture, l.roughness.value = f, l.mipInt.value = g - t, Ir(n, m, p, 3 * v, 2 * v), s.setRenderTarget(n), s.render(o, ps), l.envMap.value = n.texture, l.roughness.value = 0, l.mipInt.value = g - i, Ir(e, m, p, 3 * v, 2 * v), s.setRenderTarget(e), s.render(o, ps); } /** * 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. * * Used for initial scene blur in fromScene() method when sigma > 0. * * @private * @param {WebGLRenderTarget} cubeUVRenderTarget * @param {number} lodIn * @param {number} lodOut * @param {number} sigma * @param {Vector3} [poleAxis] */ _blur(e, t, i, s, n) { const a = this._pingPongRenderTarget; this._halfBlur( e, a, t, i, s, "latitudinal", n ), this._halfBlur( a, e, i, i, s, "longitudinal", n ); } _halfBlur(e, t, i, s, n, a, o) { const l = this._renderer, c = this._blurMaterial; a !== "latitudinal" && a !== "longitudinal" && He( "blur direction must be either latitudinal or longitudinal!" ); const h = 3, u = this._lodMeshes[s]; u.material = c; const d = c.uniforms, f = this._sizeLods[i] - 1, g = isFinite(n) ? Math.PI / (2 * f) : 2 * Math.PI / (2 * ur - 1), v = n / g, m = isFinite(n) ? 1 + Math.floor(h * v) : ur; m > ur && Se(`sigmaRadians, ${n}, is too large and will clip, as it requested ${m} samples when the maximum is set to ${ur}`); const p = []; let y = 0; for (let R = 0; R < ur; ++R) { const I = R / v, b = Math.exp(-I * I / 2); p.push(b), R === 0 ? y += b : R < m && (y += 2 * b); } for (let R = 0; R < p.length; R++) p[R] = p[R] / y; d.envMap.value = e.texture, d.samples.value = m, d.weights.value = p, d.latitudinal.value = a === "latitudinal", o && (d.poleAxis.value = o); const { _lodMax: _ } = this; d.dTheta.value = g, d.mipInt.value = _ - i; const E = this._sizeLods[s], A = 3 * E * (s > _ - Zi ? s - _ + Zi : 0), T = 4 * (this._cubeSize - E); Ir(t, A, T, 3 * E, 2 * E), l.setRenderTarget(t), l.render(u, ps); } } function ig(r) { const e = [], t = [], i = []; let s = r; const n = r - Zi + 1 + ec.length; for (let a = 0; a < n; a++) { const o = Math.pow(2, s); e.push(o); let l = 1 / o; a > r - Zi ? l = ec[a - r + Zi - 1] : a === 0 && (l = 0), t.push(l); const c = 1 / (o - 2), h = -c, u = 1 + c, d = [h, h, u, h, u, u, h, h, u, u, h, u], f = 6, g = 6, v = 3, m = 2, p = 1, y = new Float32Array(v * g * f), _ = new Float32Array(m * g * f), E = new Float32Array(p * g * f); for (let T = 0; T < f; T++) { const R = T % 3 * 2 / 3 - 1, I = T > 2 ? 0 : -1, b = [ R, I, 0, R + 2 / 3, I, 0, R + 2 / 3, I + 1, 0, R, I, 0, R + 2 / 3, I + 1, 0, R, I + 1, 0 ]; y.set(b, v * g * T), _.set(d, m * g * T); const S = [T, T, T, T, T, T]; E.set(S, p * g * T); } const A = new Qt(); A.setAttribute("position", new zt(y, v)), A.setAttribute("uv", new zt(_, m)), A.setAttribute("faceIndex", new zt(E, p)), i.push(new nt(A, null)), s > Zi && s--; } return { lodMeshes: i, sizeLods: e, sigmas: t }; } function rc(r, e, t) { const i = new _t(r, e, t); return i.texture.mapping = Pn, i.texture.name = "PMREM.cubeUv", i.scissorTest = !0, i; } function Ir(r, e, t, i, s) { r.viewport.set(e, t, i, s), r.scissor.set(e, t, i, s); } function rg(r, e, t) { return new ct({ name: "PMREMGGXConvolution", defines: { GGX_SAMPLES: eg, CUBEUV_TEXEL_WIDTH: 1 / e, CUBEUV_TEXEL_HEIGHT: 1 / t, CUBEUV_MAX_MIP: `${r}.0` }, uniforms: { envMap: { value: null }, roughness: { value: 0 }, mipInt: { value: 0 } }, vertexShader: Ln(), fragmentShader: ( /* glsl */ ` precision highp float; precision highp int; varying vec3 vOutputDirection; uniform sampler2D envMap; uniform float roughness; uniform float mipInt; #define ENVMAP_TYPE_CUBE_UV #include #define PI 3.14159265359 // Van der Corput radical inverse float radicalInverse_VdC(uint bits) { bits = (bits << 16u) | (bits >> 16u); bits = ((bits & 0x55555555u) << 1u) | ((bits & 0xAAAAAAAAu) >> 1u); bits = ((bits & 0x33333333u) << 2u) | ((bits & 0xCCCCCCCCu) >> 2u); bits = ((bits & 0x0F0F0F0Fu) << 4u) | ((bits & 0xF0F0F0F0u) >> 4u); bits = ((bits & 0x00FF00FFu) << 8u) | ((bits & 0xFF00FF00u) >> 8u); return float(bits) * 2.3283064365386963e-10; // / 0x100000000 } // Hammersley sequence vec2 hammersley(uint i, uint N) { return vec2(float(i) / float(N), radicalInverse_VdC(i)); } // GGX VNDF importance sampling (Eric Heitz 2018) // "Sampling the GGX Distribution of Visible Normals" // https://jcgt.org/published/0007/04/01/ vec3 importanceSampleGGX_VNDF(vec2 Xi, vec3 V, float roughness) { float alpha = roughness * roughness; // Section 3.2: Transform view direction to hemisphere configuration vec3 Vh = normalize(vec3(alpha * V.x, alpha * V.y, V.z)); // Section 4.1: Orthonormal basis float lensq = Vh.x * Vh.x + Vh.y * Vh.y; vec3 T1 = lensq > 0.0 ? vec3(-Vh.y, Vh.x, 0.0) / sqrt(lensq) : vec3(1.0, 0.0, 0.0); vec3 T2 = cross(Vh, T1); // Section 4.2: Parameterization of projected area float r = sqrt(Xi.x); float phi = 2.0 * PI * Xi.y; float t1 = r * cos(phi); float t2 = r * sin(phi); float s = 0.5 * (1.0 + Vh.z); t2 = (1.0 - s) * sqrt(1.0 - t1 * t1) + s * t2; // Section 4.3: Reprojection onto hemisphere vec3 Nh = t1 * T1 + t2 * T2 + sqrt(max(0.0, 1.0 - t1 * t1 - t2 * t2)) * Vh; // Section 3.4: Transform back to ellipsoid configuration return normalize(vec3(alpha * Nh.x, alpha * Nh.y, max(0.0, Nh.z))); } void main() { vec3 N = normalize(vOutputDirection); vec3 V = N; // Assume view direction equals normal for pre-filtering vec3 prefilteredColor = vec3(0.0); float totalWeight = 0.0; // For very low roughness, just sample the environment directly if (roughness < 0.001) { gl_FragColor = vec4(bilinearCubeUV(envMap, N, mipInt), 1.0); return; } // Tangent space basis for VNDF sampling vec3 up = abs(N.z) < 0.999 ? vec3(0.0, 0.0, 1.0) : vec3(1.0, 0.0, 0.0); vec3 tangent = normalize(cross(up, N)); vec3 bitangent = cross(N, tangent); for(uint i = 0u; i < uint(GGX_SAMPLES); i++) { vec2 Xi = hammersley(i, uint(GGX_SAMPLES)); // For PMREM, V = N, so in tangent space V is always (0, 0, 1) vec3 H_tangent = importanceSampleGGX_VNDF(Xi, vec3(0.0, 0.0, 1.0), roughness); // Transform H back to world space vec3 H = normalize(tangent * H_tangent.x + bitangent * H_tangent.y + N * H_tangent.z); vec3 L = normalize(2.0 * dot(V, H) * H - V); float NdotL = max(dot(N, L), 0.0); if(NdotL > 0.0) { // Sample environment at fixed mip level // VNDF importance sampling handles the distribution filtering vec3 sampleColor = bilinearCubeUV(envMap, L, mipInt); // Weight by NdotL for the split-sum approximation // VNDF PDF naturally accounts for the visible microfacet distribution prefilteredColor += sampleColor * NdotL; totalWeight += NdotL; } } if (totalWeight > 0.0) { prefilteredColor = prefilteredColor / totalWeight; } gl_FragColor = vec4(prefilteredColor, 1.0); } ` ), blending: vt, depthTest: !1, depthWrite: !1 }); } function sg(r, e, t) { const i = new Float32Array(ur), s = new w(0, 1, 0); return new ct({ name: "SphericalGaussianBlur", defines: { n: ur, CUBEUV_TEXEL_WIDTH: 1 / e, CUBEUV_TEXEL_HEIGHT: 1 / t, CUBEUV_MAX_MIP: `${r}.0` }, uniforms: { envMap: { value: null }, samples: { value: 1 }, weights: { value: i }, latitudinal: { value: !1 }, dTheta: { value: 0 }, mipInt: { value: 0 }, poleAxis: { value: s } }, vertexShader: Ln(), 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: vt, depthTest: !1, depthWrite: !1 }); } function sc() { return new ct({ name: "EquirectangularToCubeUV", uniforms: { envMap: { value: null } }, vertexShader: Ln(), 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: vt, depthTest: !1, depthWrite: !1 }); } function nc() { return new ct({ name: "CubemapToCubeUV", uniforms: { envMap: { value: null }, flipEnvMap: { value: -1 } }, vertexShader: Ln(), 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: vt, depthTest: !1, depthWrite: !1 }); } function Ln() { 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 ng(r) { let e = /* @__PURE__ */ new WeakMap(), t = null; function i(o) { if (o && o.isTexture) { const l = o.mapping, c = l === Mn || l === Na, h = l === Gr || l === Wr; if (c || h) { let u = e.get(o); const d = u !== void 0 ? u.texture.pmremVersion : 0; if (o.isRenderTargetTexture && o.pmremVersion !== d) return t === null && (t = new ic(r)), u = c ? t.fromEquirectangular(o, u) : t.fromCubemap(o, u), u.texture.pmremVersion = o.pmremVersion, e.set(o, u), u.texture; if (u !== void 0) return u.texture; { const f = o.image; return c && f && f.height > 0 || h && f && s(f) ? (t === null && (t = new ic(r)), u = c ? t.fromEquirectangular(o) : t.fromCubemap(o), u.texture.pmremVersion = o.pmremVersion, e.set(o, u), o.addEventListener("dispose", n), u.texture) : null; } } } return o; } function s(o) { let l = 0; const c = 6; for (let h = 0; h < c; h++) o[h] !== void 0 && l++; return l === c; } function n(o) { const l = o.target; l.removeEventListener("dispose", n); const c = e.get(l); c !== void 0 && (e.delete(l), c.dispose()); } function a() { e = /* @__PURE__ */ new WeakMap(), t !== null && (t.dispose(), t = null); } return { get: i, dispose: a }; } function ag(r) { const e = {}; function t(i) { if (e[i] !== void 0) return e[i]; const s = r.getExtension(i); return e[i] = s, s; } return { has: function(i) { return t(i) !== null; }, init: function() { t("EXT_color_buffer_float"), t("WEBGL_clip_cull_distance"), t("OES_texture_float_linear"), t("EXT_color_buffer_half_float"), t("WEBGL_multisampled_render_to_texture"), t("WEBGL_render_shared_exponent"); }, get: function(i) { const s = t(i); return s === null && Cs("WebGLRenderer: " + i + " extension not supported."), s; } }; } function og(r, e, t, i) { const s = {}, n = /* @__PURE__ */ new WeakMap(); function a(u) { const d = u.target; d.index !== null && e.remove(d.index); for (const g in d.attributes) e.remove(d.attributes[g]); d.removeEventListener("dispose", a), delete s[d.id]; const f = n.get(d); f && (e.remove(f), n.delete(d)), i.releaseStatesOfGeometry(d), d.isInstancedBufferGeometry === !0 && delete d._maxInstanceCount, t.memory.geometries--; } function o(u, d) { return s[d.id] === !0 || (d.addEventListener("dispose", a), s[d.id] = !0, t.memory.geometries++), d; } function l(u) { const d = u.attributes; for (const f in d) e.update(d[f], r.ARRAY_BUFFER); } function c(u) { const d = [], f = u.index, g = u.attributes.position; let v = 0; if (f !== null) { const y = f.array; v = f.version; for (let _ = 0, E = y.length; _ < E; _ += 3) { const A = y[_ + 0], T = y[_ + 1], R = y[_ + 2]; d.push(A, T, T, R, R, A); } } else if (g !== void 0) { const y = g.array; v = g.version; for (let _ = 0, E = y.length / 3 - 1; _ < E; _ += 3) { const A = _ + 0, T = _ + 1, R = _ + 2; d.push(A, T, T, R, R, A); } } else return; const m = new (rh(d) ? oh : ah)(d, 1); m.version = v; const p = n.get(u); p && e.remove(p), n.set(u, m); } function h(u) { const d = n.get(u); if (d) { const f = u.index; f !== null && d.version < f.version && c(u); } else c(u); return n.get(u); } return { get: o, update: l, getWireframeAttribute: h }; } function lg(r, e, t) { let i; function s(d) { i = d; } let n, a; function o(d) { n = d.type, a = d.bytesPerElement; } function l(d, f) { r.drawElements(i, f, n, d * a), t.update(f, i, 1); } function c(d, f, g) { g !== 0 && (r.drawElementsInstanced(i, f, n, d * a, g), t.update(f, i, g)); } function h(d, f, g) { if (g === 0) return; e.get("WEBGL_multi_draw").multiDrawElementsWEBGL(i, f, 0, n, d, 0, g); let v = 0; for (let m = 0; m < g; m++) v += f[m]; t.update(v, i, 1); } function u(d, f, g, v) { if (g === 0) return; const m = e.get("WEBGL_multi_draw"); if (m === null) for (let p = 0; p < d.length; p++) c(d[p] / a, f[p], v[p]); else { m.multiDrawElementsInstancedWEBGL(i, f, 0, n, d, 0, v, 0, g); let p = 0; for (let y = 0; y < g; y++) p += f[y] * v[y]; t.update(p, i, 1); } } this.setMode = s, this.setIndex = o, this.render = l, this.renderInstances = c, this.renderMultiDraw = h, this.renderMultiDrawInstances = u; } function cg(r) { const e = { geometries: 0, textures: 0 }, t = { frame: 0, calls: 0, triangles: 0, points: 0, lines: 0 }; function i(n, a, o) { switch (t.calls++, a) { case r.TRIANGLES: t.triangles += o * (n / 3); break; case r.LINES: t.lines += o * (n / 2); break; case r.LINE_STRIP: t.lines += o * (n - 1); break; case r.LINE_LOOP: t.lines += o * n; break; case r.POINTS: t.points += o * n; break; default: He("WebGLInfo: Unknown draw mode:", a); break; } } function s() { t.calls = 0, t.triangles = 0, t.points = 0, t.lines = 0; } return { memory: e, render: t, programs: null, autoReset: !0, reset: s, update: i }; } function hg(r, e, t) { const i = /* @__PURE__ */ new WeakMap(), s = new Je(); function n(a, o, l) { const c = a.morphTargetInfluences, h = o.morphAttributes.position || o.morphAttributes.normal || o.morphAttributes.color, u = h !== void 0 ? h.length : 0; let d = i.get(o); if (d === void 0 || d.count !== u) { let f = function() { I.dispose(), i.delete(o), o.removeEventListener("dispose", f); }; d !== void 0 && d.texture.dispose(); const g = o.morphAttributes.position !== void 0, v = o.morphAttributes.normal !== void 0, m = o.morphAttributes.color !== void 0, p = o.morphAttributes.position || [], y = o.morphAttributes.normal || [], _ = o.morphAttributes.color || []; let E = 0; g === !0 && (E = 1), v === !0 && (E = 2), m === !0 && (E = 3); let A = o.attributes.position.count * E, T = 1; A > e.maxTextureSize && (T = Math.ceil(A / e.maxTextureSize), A = e.maxTextureSize); const R = new Float32Array(A * T * 4 * u), I = new sh(R, A, T, u); I.type = Gt, I.needsUpdate = !0; const b = E * 4; for (let S = 0; S < u; S++) { const D = p[S], N = y[S], k = _[S], H = A * T * 4 * S; for (let j = 0; j < D.count; j++) { const q = j * b; g === !0 && (s.fromBufferAttribute(D, j), R[H + q + 0] = s.x, R[H + q + 1] = s.y, R[H + q + 2] = s.z, R[H + q + 3] = 0), v === !0 && (s.fromBufferAttribute(N, j), R[H + q + 4] = s.x, R[H + q + 5] = s.y, R[H + q + 6] = s.z, R[H + q + 7] = 0), m === !0 && (s.fromBufferAttribute(k, j), R[H + q + 8] = s.x, R[H + q + 9] = s.y, R[H + q + 10] = s.z, R[H + q + 11] = k.itemSize === 4 ? s.w : 1); } } d = { count: u, texture: I, size: new oe(A, T) }, i.set(o, d), o.addEventListener("dispose", f); } if (a.isInstancedMesh === !0 && a.morphTexture !== null) l.getUniforms().setValue(r, "morphTexture", a.morphTexture, t); else { let f = 0; for (let v = 0; v < c.length; v++) f += c[v]; const g = o.morphTargetsRelative ? 1 : 1 - f; l.getUniforms().setValue(r, "morphTargetBaseInfluence", g), l.getUniforms().setValue(r, "morphTargetInfluences", c); } l.getUniforms().setValue(r, "morphTargetsTexture", d.texture, t), l.getUniforms().setValue(r, "morphTargetsTextureSize", d.size); } return { update: n }; } function ug(r, e, t, i) { let s = /* @__PURE__ */ new WeakMap(); function n(l) { const c = i.render.frame, h = l.geometry, u = e.get(l, h); if (s.get(u) !== c && (e.update(u), s.set(u, c)), l.isInstancedMesh && (l.hasEventListener("dispose", o) === !1 && l.addEventListener("dispose", o), s.get(l) !== c && (t.update(l.instanceMatrix, r.ARRAY_BUFFER), l.instanceColor !== null && t.update(l.instanceColor, r.ARRAY_BUFFER), s.set(l, c))), l.isSkinnedMesh) { const d = l.skeleton; s.get(d) !== c && (d.update(), s.set(d, c)); } return u; } function a() { s = /* @__PURE__ */ new WeakMap(); } function o(l) { const c = l.target; c.removeEventListener("dispose", o), t.remove(c.instanceMatrix), c.instanceColor !== null && t.remove(c.instanceColor); } return { update: n, dispose: a }; } const bh = /* @__PURE__ */ new Ct(), ac = /* @__PURE__ */ new Wo(1, 1), Th = /* @__PURE__ */ new sh(), Eh = /* @__PURE__ */ new Ju(), wh = /* @__PURE__ */ new Fo(), oc = [], lc = [], cc = new Float32Array(16), hc = new Float32Array(9), uc = new Float32Array(4); function rs(r, e, t) { const i = r[0]; if (i <= 0 || i > 0) return r; const s = e * t; let n = oc[s]; if (n === void 0 && (n = new Float32Array(s), oc[s] = n), e !== 0) { i.toArray(n, 0); for (let a = 1, o = 0; a !== e; ++a) o += t, r[a].toArray(n, o); } return n; } function St(r, e) { if (r.length !== e.length) return !1; for (let t = 0, i = r.length; t < i; t++) if (r[t] !== e[t]) return !1; return !0; } function bt(r, e) { for (let t = 0, i = e.length; t < i; t++) r[t] = e[t]; } function In(r, e) { let t = lc[e]; t === void 0 && (t = new Int32Array(e), lc[e] = t); for (let i = 0; i !== e; ++i) t[i] = r.allocateTextureUnit(); return t; } function dg(r, e) { const t = this.cache; t[0] !== e && (r.uniform1f(this.addr, e), t[0] = e); } function pg(r, e) { const t = this.cache; if (e.x !== void 0) (t[0] !== e.x || t[1] !== e.y) && (r.uniform2f(this.addr, e.x, e.y), t[0] = e.x, t[1] = e.y); else { if (St(t, e)) return; r.uniform2fv(this.addr, e), bt(t, e); } } function fg(r, e) { const t = this.cache; if (e.x !== void 0) (t[0] !== e.x || t[1] !== e.y || t[2] !== e.z) && (r.uniform3f(this.addr, e.x, e.y, e.z), t[0] = e.x, t[1] = e.y, t[2] = e.z); else if (e.r !== void 0) (t[0] !== e.r || t[1] !== e.g || t[2] !== e.b) && (r.uniform3f(this.addr, e.r, e.g, e.b), t[0] = e.r, t[1] = e.g, t[2] = e.b); else { if (St(t, e)) return; r.uniform3fv(this.addr, e), bt(t, e); } } function mg(r, e) { const t = this.cache; if (e.x !== void 0) (t[0] !== e.x || t[1] !== e.y || t[2] !== e.z || t[3] !== e.w) && (r.uniform4f(this.addr, e.x, e.y, e.z, e.w), t[0] = e.x, t[1] = e.y, t[2] = e.z, t[3] = e.w); else { if (St(t, e)) return; r.uniform4fv(this.addr, e), bt(t, e); } } function gg(r, e) { const t = this.cache, i = e.elements; if (i === void 0) { if (St(t, e)) return; r.uniformMatrix2fv(this.addr, !1, e), bt(t, e); } else { if (St(t, i)) return; uc.set(i), r.uniformMatrix2fv(this.addr, !1, uc), bt(t, i); } } function vg(r, e) { const t = this.cache, i = e.elements; if (i === void 0) { if (St(t, e)) return; r.uniformMatrix3fv(this.addr, !1, e), bt(t, e); } else { if (St(t, i)) return; hc.set(i), r.uniformMatrix3fv(this.addr, !1, hc), bt(t, i); } } function _g(r, e) { const t = this.cache, i = e.elements; if (i === void 0) { if (St(t, e)) return; r.uniformMatrix4fv(this.addr, !1, e), bt(t, e); } else { if (St(t, i)) return; cc.set(i), r.uniformMatrix4fv(this.addr, !1, cc), bt(t, i); } } function xg(r, e) { const t = this.cache; t[0] !== e && (r.uniform1i(this.addr, e), t[0] = e); } function yg(r, e) { const t = this.cache; if (e.x !== void 0) (t[0] !== e.x || t[1] !== e.y) && (r.uniform2i(this.addr, e.x, e.y), t[0] = e.x, t[1] = e.y); else { if (St(t, e)) return; r.uniform2iv(this.addr, e), bt(t, e); } } function Mg(r, e) { const t = this.cache; if (e.x !== void 0) (t[0] !== e.x || t[1] !== e.y || t[2] !== e.z) && (r.uniform3i(this.addr, e.x, e.y, e.z), t[0] = e.x, t[1] = e.y, t[2] = e.z); else { if (St(t, e)) return; r.uniform3iv(this.addr, e), bt(t, e); } } function Sg(r, e) { const t = this.cache; if (e.x !== void 0) (t[0] !== e.x || t[1] !== e.y || t[2] !== e.z || t[3] !== e.w) && (r.uniform4i(this.addr, e.x, e.y, e.z, e.w), t[0] = e.x, t[1] = e.y, t[2] = e.z, t[3] = e.w); else { if (St(t, e)) return; r.uniform4iv(this.addr, e), bt(t, e); } } function bg(r, e) { const t = this.cache; t[0] !== e && (r.uniform1ui(this.addr, e), t[0] = e); } function Tg(r, e) { const t = this.cache; if (e.x !== void 0) (t[0] !== e.x || t[1] !== e.y) && (r.uniform2ui(this.addr, e.x, e.y), t[0] = e.x, t[1] = e.y); else { if (St(t, e)) return; r.uniform2uiv(this.addr, e), bt(t, e); } } function Eg(r, e) { const t = this.cache; if (e.x !== void 0) (t[0] !== e.x || t[1] !== e.y || t[2] !== e.z) && (r.uniform3ui(this.addr, e.x, e.y, e.z), t[0] = e.x, t[1] = e.y, t[2] = e.z); else { if (St(t, e)) return; r.uniform3uiv(this.addr, e), bt(t, e); } } function wg(r, e) { const t = this.cache; if (e.x !== void 0) (t[0] !== e.x || t[1] !== e.y || t[2] !== e.z || t[3] !== e.w) && (r.uniform4ui(this.addr, e.x, e.y, e.z, e.w), t[0] = e.x, t[1] = e.y, t[2] = e.z, t[3] = e.w); else { if (St(t, e)) return; r.uniform4uiv(this.addr, e), bt(t, e); } } function Cg(r, e, t) { const i = this.cache, s = t.allocateTextureUnit(); i[0] !== s && (r.uniform1i(this.addr, s), i[0] = s); let n; this.type === r.SAMPLER_2D_SHADOW ? (ac.compareFunction = ih, n = ac) : n = bh, t.setTexture2D(e || n, s); } function Rg(r, e, t) { const i = this.cache, s = t.allocateTextureUnit(); i[0] !== s && (r.uniform1i(this.addr, s), i[0] = s), t.setTexture3D(e || Eh, s); } function Ag(r, e, t) { const i = this.cache, s = t.allocateTextureUnit(); i[0] !== s && (r.uniform1i(this.addr, s), i[0] = s), t.setTextureCube(e || wh, s); } function Pg(r, e, t) { const i = this.cache, s = t.allocateTextureUnit(); i[0] !== s && (r.uniform1i(this.addr, s), i[0] = s), t.setTexture2DArray(e || Th, s); } function Dg(r) { switch (r) { case 5126: return dg; // FLOAT case 35664: return pg; // _VEC2 case 35665: return fg; // _VEC3 case 35666: return mg; // _VEC4 case 35674: return gg; // _MAT2 case 35675: return vg; // _MAT3 case 35676: return _g; // _MAT4 case 5124: case 35670: return xg; // INT, BOOL case 35667: case 35671: return yg; // _VEC2 case 35668: case 35672: return Mg; // _VEC3 case 35669: case 35673: return Sg; // _VEC4 case 5125: return bg; // UINT case 36294: return Tg; // _VEC2 case 36295: return Eg; // _VEC3 case 36296: return wg; // _VEC4 case 35678: // SAMPLER_2D case 36198: // SAMPLER_EXTERNAL_OES case 36298: // INT_SAMPLER_2D case 36306: // UNSIGNED_INT_SAMPLER_2D case 35682: return Cg; case 35679: // SAMPLER_3D case 36299: // INT_SAMPLER_3D case 36307: return Rg; case 35680: // SAMPLER_CUBE case 36300: // INT_SAMPLER_CUBE case 36308: // UNSIGNED_INT_SAMPLER_CUBE case 36293: return Ag; case 36289: // SAMPLER_2D_ARRAY case 36303: // INT_SAMPLER_2D_ARRAY case 36311: // UNSIGNED_INT_SAMPLER_2D_ARRAY case 36292: return Pg; } } function Lg(r, e) { r.uniform1fv(this.addr, e); } function Ig(r, e) { const t = rs(e, this.size, 2); r.uniform2fv(this.addr, t); } function Ug(r, e) { const t = rs(e, this.size, 3); r.uniform3fv(this.addr, t); } function Ng(r, e) { const t = rs(e, this.size, 4); r.uniform4fv(this.addr, t); } function Og(r, e) { const t = rs(e, this.size, 4); r.uniformMatrix2fv(this.addr, !1, t); } function Bg(r, e) { const t = rs(e, this.size, 9); r.uniformMatrix3fv(this.addr, !1, t); } function Fg(r, e) { const t = rs(e, this.size, 16); r.uniformMatrix4fv(this.addr, !1, t); } function zg(r, e) { r.uniform1iv(this.addr, e); } function kg(r, e) { r.uniform2iv(this.addr, e); } function Hg(r, e) { r.uniform3iv(this.addr, e); } function Vg(r, e) { r.uniform4iv(this.addr, e); } function Gg(r, e) { r.uniform1uiv(this.addr, e); } function Wg(r, e) { r.uniform2uiv(this.addr, e); } function jg(r, e) { r.uniform3uiv(this.addr, e); } function Xg(r, e) { r.uniform4uiv(this.addr, e); } function qg(r, e, t) { const i = this.cache, s = e.length, n = In(t, s); St(i, n) || (r.uniform1iv(this.addr, n), bt(i, n)); for (let a = 0; a !== s; ++a) t.setTexture2D(e[a] || bh, n[a]); } function Yg(r, e, t) { const i = this.cache, s = e.length, n = In(t, s); St(i, n) || (r.uniform1iv(this.addr, n), bt(i, n)); for (let a = 0; a !== s; ++a) t.setTexture3D(e[a] || Eh, n[a]); } function Kg(r, e, t) { const i = this.cache, s = e.length, n = In(t, s); St(i, n) || (r.uniform1iv(this.addr, n), bt(i, n)); for (let a = 0; a !== s; ++a) t.setTextureCube(e[a] || wh, n[a]); } function Zg(r, e, t) { const i = this.cache, s = e.length, n = In(t, s); St(i, n) || (r.uniform1iv(this.addr, n), bt(i, n)); for (let a = 0; a !== s; ++a) t.setTexture2DArray(e[a] || Th, n[a]); } function Jg(r) { switch (r) { case 5126: return Lg; // FLOAT case 35664: return Ig; // _VEC2 case 35665: return Ug; // _VEC3 case 35666: return Ng; // _VEC4 case 35674: return Og; // _MAT2 case 35675: return Bg; // _MAT3 case 35676: return Fg; // _MAT4 case 5124: case 35670: return zg; // INT, BOOL case 35667: case 35671: return kg; // _VEC2 case 35668: case 35672: return Hg; // _VEC3 case 35669: case 35673: return Vg; // _VEC4 case 5125: return Gg; // UINT case 36294: return Wg; // _VEC2 case 36295: return jg; // _VEC3 case 36296: return Xg; // _VEC4 case 35678: // SAMPLER_2D case 36198: // SAMPLER_EXTERNAL_OES case 36298: // INT_SAMPLER_2D case 36306: // UNSIGNED_INT_SAMPLER_2D case 35682: return qg; case 35679: // SAMPLER_3D case 36299: // INT_SAMPLER_3D case 36307: return Yg; case 35680: // SAMPLER_CUBE case 36300: // INT_SAMPLER_CUBE case 36308: // UNSIGNED_INT_SAMPLER_CUBE case 36293: return Kg; case 36289: // SAMPLER_2D_ARRAY case 36303: // INT_SAMPLER_2D_ARRAY case 36311: // UNSIGNED_INT_SAMPLER_2D_ARRAY case 36292: return Zg; } } class $g { constructor(e, t, i) { this.id = e, this.addr = i, this.cache = [], this.type = t.type, this.setValue = Dg(t.type); } } class Qg { constructor(e, t, i) { this.id = e, this.addr = i, this.cache = [], this.type = t.type, this.size = t.size, this.setValue = Jg(t.type); } } class ev { constructor(e) { this.id = e, this.seq = [], this.map = {}; } setValue(e, t, i) { const s = this.seq; for (let n = 0, a = s.length; n !== a; ++n) { const o = s[n]; o.setValue(e, t[o.id], i); } } } const va = /(\w+)(\])?(\[|\.)?/g; function dc(r, e) { r.seq.push(e), r.map[e.id] = e; } function tv(r, e, t) { const i = r.name, s = i.length; for (va.lastIndex = 0; ; ) { const n = va.exec(i), a = va.lastIndex; let o = n[1]; const l = n[2] === "]", c = n[3]; if (l && (o = o | 0), c === void 0 || c === "[" && a + 2 === s) { dc(t, c === void 0 ? new $g(o, r, e) : new Qg(o, r, e)); break; } else { let h = t.map[o]; h === void 0 && (h = new ev(o), dc(t, h)), t = h; } } } class _n { constructor(e, t) { this.seq = [], this.map = {}; const i = e.getProgramParameter(t, e.ACTIVE_UNIFORMS); for (let s = 0; s < i; ++s) { const n = e.getActiveUniform(t, s), a = e.getUniformLocation(t, n.name); tv(n, a, this); } } setValue(e, t, i, s) { const n = this.map[t]; n !== void 0 && n.setValue(e, i, s); } setOptional(e, t, i) { const s = t[i]; s !== void 0 && this.setValue(e, i, s); } static upload(e, t, i, s) { for (let n = 0, a = t.length; n !== a; ++n) { const o = t[n], l = i[o.id]; l.needsUpdate !== !1 && o.setValue(e, l.value, s); } } static seqWithValue(e, t) { const i = []; for (let s = 0, n = e.length; s !== n; ++s) { const a = e[s]; a.id in t && i.push(a); } return i; } } function pc(r, e, t) { const i = r.createShader(e); return r.shaderSource(i, t), r.compileShader(i), i; } const iv = 37297; let rv = 0; function sv(r, e) { const t = r.split(` `), i = [], s = Math.max(e - 6, 0), n = Math.min(e + 6, t.length); for (let a = s; a < n; a++) { const o = a + 1; i.push(`${o === e ? ">" : " "} ${o}: ${t[a]}`); } return i.join(` `); } const fc = /* @__PURE__ */ new Be(); function nv(r) { Xe._getMatrix(fc, Xe.workingColorSpace, r); const e = `mat3( ${fc.elements.map((t) => t.toFixed(4))} )`; switch (Xe.getTransfer(r)) { case bn: return [e, "LinearTransferOETF"]; case et: return [e, "sRGBTransferOETF"]; default: return Se("WebGLProgram: Unsupported color space: ", r), [e, "LinearTransferOETF"]; } } function mc(r, e, t) { const i = r.getShaderParameter(e, r.COMPILE_STATUS), s = (r.getShaderInfoLog(e) || "").trim(); if (i && s === "") return ""; const n = /ERROR: 0:(\d+)/.exec(s); if (n) { const a = parseInt(n[1]); return t.toUpperCase() + ` ` + s + ` ` + sv(r.getShaderSource(e), a); } else return s; } function av(r, e) { const t = nv(e); return [ `vec4 ${r}( vec4 value ) {`, ` return ${t[1]}( vec4( value.rgb * ${t[0]}, value.a ) );`, "}" ].join(` `); } function ov(r, e) { let t; switch (e) { case kc: t = "Linear"; break; case Hc: t = "Reinhard"; break; case Vc: t = "Cineon"; break; case Eo: t = "ACESFilmic"; break; case Wc: t = "AgX"; break; case jc: t = "Neutral"; break; case Gc: t = "Custom"; break; default: Se("WebGLProgram: Unsupported toneMapping:", e), t = "Linear"; } return "vec3 " + r + "( vec3 color ) { return " + t + "ToneMapping( color ); }"; } const on = /* @__PURE__ */ new w(); function lv() { Xe.getLuminanceCoefficients(on); const r = on.x.toFixed(4), e = on.y.toFixed(4), t = on.z.toFixed(4); return [ "float luminance( const in vec3 rgb ) {", ` const vec3 weights = vec3( ${r}, ${e}, ${t} );`, " return dot( weights, rgb );", "}" ].join(` `); } function cv(r) { return [ r.extensionClipCullDistance ? "#extension GL_ANGLE_clip_cull_distance : require" : "", r.extensionMultiDraw ? "#extension GL_ANGLE_multi_draw : require" : "" ].filter(vs).join(` `); } function hv(r) { const e = []; for (const t in r) { const i = r[t]; i !== !1 && e.push("#define " + t + " " + i); } return e.join(` `); } function uv(r, e) { const t = {}, i = r.getProgramParameter(e, r.ACTIVE_ATTRIBUTES); for (let s = 0; s < i; s++) { const n = r.getActiveAttrib(e, s), a = n.name; let o = 1; n.type === r.FLOAT_MAT2 && (o = 2), n.type === r.FLOAT_MAT3 && (o = 3), n.type === r.FLOAT_MAT4 && (o = 4), t[a] = { type: n.type, location: r.getAttribLocation(e, a), locationSize: o }; } return t; } function vs(r) { return r !== ""; } function gc(r, e) { const t = e.numSpotLightShadows + e.numSpotLightMaps - e.numSpotLightShadowsWithMaps; return r.replace(/NUM_DIR_LIGHTS/g, e.numDirLights).replace(/NUM_SPOT_LIGHTS/g, e.numSpotLights).replace(/NUM_SPOT_LIGHT_MAPS/g, e.numSpotLightMaps).replace(/NUM_SPOT_LIGHT_COORDS/g, t).replace(/NUM_RECT_AREA_LIGHTS/g, e.numRectAreaLights).replace(/NUM_POINT_LIGHTS/g, e.numPointLights).replace(/NUM_HEMI_LIGHTS/g, e.numHemiLights).replace(/NUM_DIR_LIGHT_SHADOWS/g, e.numDirLightShadows).replace(/NUM_SPOT_LIGHT_SHADOWS_WITH_MAPS/g, e.numSpotLightShadowsWithMaps).replace(/NUM_SPOT_LIGHT_SHADOWS/g, e.numSpotLightShadows).replace(/NUM_POINT_LIGHT_SHADOWS/g, e.numPointLightShadows); } function vc(r, e) { return r.replace(/NUM_CLIPPING_PLANES/g, e.numClippingPlanes).replace(/UNION_CLIPPING_PLANES/g, e.numClippingPlanes - e.numClipIntersection); } const dv = /^[ \t]*#include +<([\w\d./]+)>/gm; function vo(r) { return r.replace(dv, fv); } const pv = /* @__PURE__ */ new Map(); function fv(r, e) { let t = Fe[e]; if (t === void 0) { const i = pv.get(e); if (i !== void 0) t = Fe[i], Se('WebGLRenderer: Shader chunk "%s" has been deprecated. Use "%s" instead.', e, i); else throw new Error("Can not resolve #include <" + e + ">"); } return vo(t); } const mv = /#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 _c(r) { return r.replace(mv, gv); } function gv(r, e, t, i) { let s = ""; for (let n = parseInt(e); n < parseInt(t); n++) s += i.replace(/\[\s*i\s*\]/g, "[ " + n + " ]").replace(/UNROLLED_LOOP_INDEX/g, n); return s; } function xc(r) { let e = `precision ${r.precision} float; precision ${r.precision} int; precision ${r.precision} sampler2D; precision ${r.precision} samplerCube; precision ${r.precision} sampler3D; precision ${r.precision} sampler2DArray; precision ${r.precision} sampler2DShadow; precision ${r.precision} samplerCubeShadow; precision ${r.precision} sampler2DArrayShadow; precision ${r.precision} isampler2D; precision ${r.precision} isampler3D; precision ${r.precision} isamplerCube; precision ${r.precision} isampler2DArray; precision ${r.precision} usampler2D; precision ${r.precision} usampler3D; precision ${r.precision} usamplerCube; precision ${r.precision} usampler2DArray; `; return r.precision === "highp" ? e += ` #define HIGH_PRECISION` : r.precision === "mediump" ? e += ` #define MEDIUM_PRECISION` : r.precision === "lowp" && (e += ` #define LOW_PRECISION`), e; } function vv(r) { let e = "SHADOWMAP_TYPE_BASIC"; return r.shadowMapType === Bc ? e = "SHADOWMAP_TYPE_PCF" : r.shadowMapType === Fc ? e = "SHADOWMAP_TYPE_PCF_SOFT" : r.shadowMapType === Bi && (e = "SHADOWMAP_TYPE_VSM"), e; } function _v(r) { let e = "ENVMAP_TYPE_CUBE"; if (r.envMap) switch (r.envMapMode) { case Gr: case Wr: e = "ENVMAP_TYPE_CUBE"; break; case Pn: e = "ENVMAP_TYPE_CUBE_UV"; break; } return e; } function xv(r) { let e = "ENVMAP_MODE_REFLECTION"; if (r.envMap) switch (r.envMapMode) { case Wr: e = "ENVMAP_MODE_REFRACTION"; break; } return e; } function yv(r) { let e = "ENVMAP_BLENDING_NONE"; if (r.envMap) switch (r.combine) { case To: e = "ENVMAP_BLENDING_MULTIPLY"; break; case pu: e = "ENVMAP_BLENDING_MIX"; break; case fu: e = "ENVMAP_BLENDING_ADD"; break; } return e; } function Mv(r) { const e = r.envMapCubeUVHeight; if (e === null) return null; const t = Math.log2(e) - 2, i = 1 / e; return { texelWidth: 1 / (3 * Math.max(Math.pow(2, t), 112)), texelHeight: i, maxMip: t }; } function Sv(r, e, t, i) { const s = r.getContext(), n = t.defines; let a = t.vertexShader, o = t.fragmentShader; const l = vv(t), c = _v(t), h = xv(t), u = yv(t), d = Mv(t), f = cv(t), g = hv(n), v = s.createProgram(); let m, p, y = t.glslVersion ? "#version " + t.glslVersion + ` ` : ""; t.isRawShaderMaterial ? (m = [ "#define SHADER_TYPE " + t.shaderType, "#define SHADER_NAME " + t.shaderName, g ].filter(vs).join(` `), m.length > 0 && (m += ` `), p = [ "#define SHADER_TYPE " + t.shaderType, "#define SHADER_NAME " + t.shaderName, g ].filter(vs).join(` `), p.length > 0 && (p += ` `)) : (m = [ xc(t), "#define SHADER_TYPE " + t.shaderType, "#define SHADER_NAME " + t.shaderName, g, t.extensionClipCullDistance ? "#define USE_CLIP_DISTANCE" : "", t.batching ? "#define USE_BATCHING" : "", t.batchingColor ? "#define USE_BATCHING_COLOR" : "", t.instancing ? "#define USE_INSTANCING" : "", t.instancingColor ? "#define USE_INSTANCING_COLOR" : "", t.instancingMorph ? "#define USE_INSTANCING_MORPH" : "", t.useFog && t.fog ? "#define USE_FOG" : "", t.useFog && t.fogExp2 ? "#define FOG_EXP2" : "", t.map ? "#define USE_MAP" : "", t.envMap ? "#define USE_ENVMAP" : "", t.envMap ? "#define " + h : "", t.lightMap ? "#define USE_LIGHTMAP" : "", t.aoMap ? "#define USE_AOMAP" : "", t.bumpMap ? "#define USE_BUMPMAP" : "", t.normalMap ? "#define USE_NORMALMAP" : "", t.normalMapObjectSpace ? "#define USE_NORMALMAP_OBJECTSPACE" : "", t.normalMapTangentSpace ? "#define USE_NORMALMAP_TANGENTSPACE" : "", t.displacementMap ? "#define USE_DISPLACEMENTMAP" : "", t.emissiveMap ? "#define USE_EMISSIVEMAP" : "", t.anisotropy ? "#define USE_ANISOTROPY" : "", t.anisotropyMap ? "#define USE_ANISOTROPYMAP" : "", t.clearcoatMap ? "#define USE_CLEARCOATMAP" : "", t.clearcoatRoughnessMap ? "#define USE_CLEARCOAT_ROUGHNESSMAP" : "", t.clearcoatNormalMap ? "#define USE_CLEARCOAT_NORMALMAP" : "", t.iridescenceMap ? "#define USE_IRIDESCENCEMAP" : "", t.iridescenceThicknessMap ? "#define USE_IRIDESCENCE_THICKNESSMAP" : "", t.specularMap ? "#define USE_SPECULARMAP" : "", t.specularColorMap ? "#define USE_SPECULAR_COLORMAP" : "", t.specularIntensityMap ? "#define USE_SPECULAR_INTENSITYMAP" : "", t.roughnessMap ? "#define USE_ROUGHNESSMAP" : "", t.metalnessMap ? "#define USE_METALNESSMAP" : "", t.alphaMap ? "#define USE_ALPHAMAP" : "", t.alphaHash ? "#define USE_ALPHAHASH" : "", t.transmission ? "#define USE_TRANSMISSION" : "", t.transmissionMap ? "#define USE_TRANSMISSIONMAP" : "", t.thicknessMap ? "#define USE_THICKNESSMAP" : "", t.sheenColorMap ? "#define USE_SHEEN_COLORMAP" : "", t.sheenRoughnessMap ? "#define USE_SHEEN_ROUGHNESSMAP" : "", // t.mapUv ? "#define MAP_UV " + t.mapUv : "", t.alphaMapUv ? "#define ALPHAMAP_UV " + t.alphaMapUv : "", t.lightMapUv ? "#define LIGHTMAP_UV " + t.lightMapUv : "", t.aoMapUv ? "#define AOMAP_UV " + t.aoMapUv : "", t.emissiveMapUv ? "#define EMISSIVEMAP_UV " + t.emissiveMapUv : "", t.bumpMapUv ? "#define BUMPMAP_UV " + t.bumpMapUv : "", t.normalMapUv ? "#define NORMALMAP_UV " + t.normalMapUv : "", t.displacementMapUv ? "#define DISPLACEMENTMAP_UV " + t.displacementMapUv : "", t.metalnessMapUv ? "#define METALNESSMAP_UV " + t.metalnessMapUv : "", t.roughnessMapUv ? "#define ROUGHNESSMAP_UV " + t.roughnessMapUv : "", t.anisotropyMapUv ? "#define ANISOTROPYMAP_UV " + t.anisotropyMapUv : "", t.clearcoatMapUv ? "#define CLEARCOATMAP_UV " + t.clearcoatMapUv : "", t.clearcoatNormalMapUv ? "#define CLEARCOAT_NORMALMAP_UV " + t.clearcoatNormalMapUv : "", t.clearcoatRoughnessMapUv ? "#define CLEARCOAT_ROUGHNESSMAP_UV " + t.clearcoatRoughnessMapUv : "", t.iridescenceMapUv ? "#define IRIDESCENCEMAP_UV " + t.iridescenceMapUv : "", t.iridescenceThicknessMapUv ? "#define IRIDESCENCE_THICKNESSMAP_UV " + t.iridescenceThicknessMapUv : "", t.sheenColorMapUv ? "#define SHEEN_COLORMAP_UV " + t.sheenColorMapUv : "", t.sheenRoughnessMapUv ? "#define SHEEN_ROUGHNESSMAP_UV " + t.sheenRoughnessMapUv : "", t.specularMapUv ? "#define SPECULARMAP_UV " + t.specularMapUv : "", t.specularColorMapUv ? "#define SPECULAR_COLORMAP_UV " + t.specularColorMapUv : "", t.specularIntensityMapUv ? "#define SPECULAR_INTENSITYMAP_UV " + t.specularIntensityMapUv : "", t.transmissionMapUv ? "#define TRANSMISSIONMAP_UV " + t.transmissionMapUv : "", t.thicknessMapUv ? "#define THICKNESSMAP_UV " + t.thicknessMapUv : "", // t.vertexTangents && t.flatShading === !1 ? "#define USE_TANGENT" : "", t.vertexColors ? "#define USE_COLOR" : "", t.vertexAlphas ? "#define USE_COLOR_ALPHA" : "", t.vertexUv1s ? "#define USE_UV1" : "", t.vertexUv2s ? "#define USE_UV2" : "", t.vertexUv3s ? "#define USE_UV3" : "", t.pointsUvs ? "#define USE_POINTS_UV" : "", t.flatShading ? "#define FLAT_SHADED" : "", t.skinning ? "#define USE_SKINNING" : "", t.morphTargets ? "#define USE_MORPHTARGETS" : "", t.morphNormals && t.flatShading === !1 ? "#define USE_MORPHNORMALS" : "", t.morphColors ? "#define USE_MORPHCOLORS" : "", t.morphTargetsCount > 0 ? "#define MORPHTARGETS_TEXTURE_STRIDE " + t.morphTextureStride : "", t.morphTargetsCount > 0 ? "#define MORPHTARGETS_COUNT " + t.morphTargetsCount : "", t.doubleSided ? "#define DOUBLE_SIDED" : "", t.flipSided ? "#define FLIP_SIDED" : "", t.shadowMapEnabled ? "#define USE_SHADOWMAP" : "", t.shadowMapEnabled ? "#define " + l : "", t.sizeAttenuation ? "#define USE_SIZEATTENUATION" : "", t.numLightProbes > 0 ? "#define USE_LIGHT_PROBES" : "", t.logarithmicDepthBuffer ? "#define USE_LOGARITHMIC_DEPTH_BUFFER" : "", t.reversedDepthBuffer ? "#define USE_REVERSED_DEPTH_BUFFER" : "", "uniform mat4 modelMatrix;", "uniform mat4 modelViewMatrix;", "uniform mat4 projectionMatrix;", "uniform mat4 viewMatrix;", "uniform mat3 normalMatrix;", "uniform vec3 cameraPosition;", "uniform bool isOrthographic;", "#ifdef USE_INSTANCING", " attribute mat4 instanceMatrix;", "#endif", "#ifdef USE_INSTANCING_COLOR", " attribute vec3 instanceColor;", "#endif", "#ifdef USE_INSTANCING_MORPH", " uniform sampler2D morphTexture;", "#endif", "attribute vec3 position;", "attribute vec3 normal;", "attribute vec2 uv;", "#ifdef USE_UV1", " attribute vec2 uv1;", "#endif", "#ifdef USE_UV2", " attribute vec2 uv2;", "#endif", "#ifdef USE_UV3", " attribute vec2 uv3;", "#endif", "#ifdef USE_TANGENT", " attribute vec4 tangent;", "#endif", "#if defined( USE_COLOR_ALPHA )", " attribute vec4 color;", "#elif defined( USE_COLOR )", " attribute vec3 color;", "#endif", "#ifdef USE_SKINNING", " attribute vec4 skinIndex;", " attribute vec4 skinWeight;", "#endif", ` ` ].filter(vs).join(` `), p = [ xc(t), "#define SHADER_TYPE " + t.shaderType, "#define SHADER_NAME " + t.shaderName, g, t.useFog && t.fog ? "#define USE_FOG" : "", t.useFog && t.fogExp2 ? "#define FOG_EXP2" : "", t.alphaToCoverage ? "#define ALPHA_TO_COVERAGE" : "", t.map ? "#define USE_MAP" : "", t.matcap ? "#define USE_MATCAP" : "", t.envMap ? "#define USE_ENVMAP" : "", t.envMap ? "#define " + c : "", t.envMap ? "#define " + h : "", t.envMap ? "#define " + u : "", d ? "#define CUBEUV_TEXEL_WIDTH " + d.texelWidth : "", d ? "#define CUBEUV_TEXEL_HEIGHT " + d.texelHeight : "", d ? "#define CUBEUV_MAX_MIP " + d.maxMip + ".0" : "", t.lightMap ? "#define USE_LIGHTMAP" : "", t.aoMap ? "#define USE_AOMAP" : "", t.bumpMap ? "#define USE_BUMPMAP" : "", t.normalMap ? "#define USE_NORMALMAP" : "", t.normalMapObjectSpace ? "#define USE_NORMALMAP_OBJECTSPACE" : "", t.normalMapTangentSpace ? "#define USE_NORMALMAP_TANGENTSPACE" : "", t.emissiveMap ? "#define USE_EMISSIVEMAP" : "", t.anisotropy ? "#define USE_ANISOTROPY" : "", t.anisotropyMap ? "#define USE_ANISOTROPYMAP" : "", t.clearcoat ? "#define USE_CLEARCOAT" : "", t.clearcoatMap ? "#define USE_CLEARCOATMAP" : "", t.clearcoatRoughnessMap ? "#define USE_CLEARCOAT_ROUGHNESSMAP" : "", t.clearcoatNormalMap ? "#define USE_CLEARCOAT_NORMALMAP" : "", t.dispersion ? "#define USE_DISPERSION" : "", t.iridescence ? "#define USE_IRIDESCENCE" : "", t.iridescenceMap ? "#define USE_IRIDESCENCEMAP" : "", t.iridescenceThicknessMap ? "#define USE_IRIDESCENCE_THICKNESSMAP" : "", t.specularMap ? "#define USE_SPECULARMAP" : "", t.specularColorMap ? "#define USE_SPECULAR_COLORMAP" : "", t.specularIntensityMap ? "#define USE_SPECULAR_INTENSITYMAP" : "", t.roughnessMap ? "#define USE_ROUGHNESSMAP" : "", t.metalnessMap ? "#define USE_METALNESSMAP" : "", t.alphaMap ? "#define USE_ALPHAMAP" : "", t.alphaTest ? "#define USE_ALPHATEST" : "", t.alphaHash ? "#define USE_ALPHAHASH" : "", t.sheen ? "#define USE_SHEEN" : "", t.sheenColorMap ? "#define USE_SHEEN_COLORMAP" : "", t.sheenRoughnessMap ? "#define USE_SHEEN_ROUGHNESSMAP" : "", t.transmission ? "#define USE_TRANSMISSION" : "", t.transmissionMap ? "#define USE_TRANSMISSIONMAP" : "", t.thicknessMap ? "#define USE_THICKNESSMAP" : "", t.vertexTangents && t.flatShading === !1 ? "#define USE_TANGENT" : "", t.vertexColors || t.instancingColor || t.batchingColor ? "#define USE_COLOR" : "", t.vertexAlphas ? "#define USE_COLOR_ALPHA" : "", t.vertexUv1s ? "#define USE_UV1" : "", t.vertexUv2s ? "#define USE_UV2" : "", t.vertexUv3s ? "#define USE_UV3" : "", t.pointsUvs ? "#define USE_POINTS_UV" : "", t.gradientMap ? "#define USE_GRADIENTMAP" : "", t.flatShading ? "#define FLAT_SHADED" : "", t.doubleSided ? "#define DOUBLE_SIDED" : "", t.flipSided ? "#define FLIP_SIDED" : "", t.shadowMapEnabled ? "#define USE_SHADOWMAP" : "", t.shadowMapEnabled ? "#define " + l : "", t.premultipliedAlpha ? "#define PREMULTIPLIED_ALPHA" : "", t.numLightProbes > 0 ? "#define USE_LIGHT_PROBES" : "", t.decodeVideoTexture ? "#define DECODE_VIDEO_TEXTURE" : "", t.decodeVideoTextureEmissive ? "#define DECODE_VIDEO_TEXTURE_EMISSIVE" : "", t.logarithmicDepthBuffer ? "#define USE_LOGARITHMIC_DEPTH_BUFFER" : "", t.reversedDepthBuffer ? "#define USE_REVERSED_DEPTH_BUFFER" : "", "uniform mat4 viewMatrix;", "uniform vec3 cameraPosition;", "uniform bool isOrthographic;", t.toneMapping !== $i ? "#define TONE_MAPPING" : "", t.toneMapping !== $i ? Fe.tonemapping_pars_fragment : "", // this code is required here because it is used by the toneMapping() function defined below t.toneMapping !== $i ? ov("toneMapping", t.toneMapping) : "", t.dithering ? "#define DITHERING" : "", t.opaque ? "#define OPAQUE" : "", Fe.colorspace_pars_fragment, // this code is required here because it is used by the various encoding/decoding function defined below av("linearToOutputTexel", t.outputColorSpace), lv(), t.useDepthPacking ? "#define DEPTH_PACKING " + t.depthPacking : "", ` ` ].filter(vs).join(` `)), a = vo(a), a = gc(a, t), a = vc(a, t), o = vo(o), o = gc(o, t), o = vc(o, t), a = _c(a), o = _c(o), t.isRawShaderMaterial !== !0 && (y = `#version 300 es `, m = [ f, "#define attribute in", "#define varying out", "#define texture2D texture" ].join(` `) + ` ` + m, p = [ "#define varying in", t.glslVersion === dl ? "" : "layout(location = 0) out highp vec4 pc_fragColor;", t.glslVersion === dl ? "" : "#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(` `) + ` ` + p); const _ = y + m + a, E = y + p + o, A = pc(s, s.VERTEX_SHADER, _), T = pc(s, s.FRAGMENT_SHADER, E); s.attachShader(v, A), s.attachShader(v, T), t.index0AttributeName !== void 0 ? s.bindAttribLocation(v, 0, t.index0AttributeName) : t.morphTargets === !0 && s.bindAttribLocation(v, 0, "position"), s.linkProgram(v); function R(D) { if (r.debug.checkShaderErrors) { const N = s.getProgramInfoLog(v) || "", k = s.getShaderInfoLog(A) || "", H = s.getShaderInfoLog(T) || "", j = N.trim(), q = k.trim(), te = H.trim(); let G = !0, Z = !0; if (s.getProgramParameter(v, s.LINK_STATUS) === !1) if (G = !1, typeof r.debug.onShaderError == "function") r.debug.onShaderError(s, v, A, T); else { const se = mc(s, A, "vertex"), Pe = mc(s, T, "fragment"); He( "THREE.WebGLProgram: Shader Error " + s.getError() + " - VALIDATE_STATUS " + s.getProgramParameter(v, s.VALIDATE_STATUS) + ` Material Name: ` + D.name + ` Material Type: ` + D.type + ` Program Info Log: ` + j + ` ` + se + ` ` + Pe ); } else j !== "" ? Se("WebGLProgram: Program Info Log:", j) : (q === "" || te === "") && (Z = !1); Z && (D.diagnostics = { runnable: G, programLog: j, vertexShader: { log: q, prefix: m }, fragmentShader: { log: te, prefix: p } }); } s.deleteShader(A), s.deleteShader(T), I = new _n(s, v), b = uv(s, v); } let I; this.getUniforms = function() { return I === void 0 && R(this), I; }; let b; this.getAttributes = function() { return b === void 0 && R(this), b; }; let S = t.rendererExtensionParallelShaderCompile === !1; return this.isReady = function() { return S === !1 && (S = s.getProgramParameter(v, iv)), S; }, this.destroy = function() { i.releaseStatesOfProgram(this), s.deleteProgram(v), this.program = void 0; }, this.type = t.shaderType, this.name = t.shaderName, this.id = rv++, this.cacheKey = e, this.usedTimes = 1, this.program = v, this.vertexShader = A, this.fragmentShader = T, this; } let bv = 0; class Tv { constructor() { this.shaderCache = /* @__PURE__ */ new Map(), this.materialCache = /* @__PURE__ */ new Map(); } update(e) { const t = e.vertexShader, i = e.fragmentShader, s = this._getShaderStage(t), n = this._getShaderStage(i), a = this._getShaderCacheForMaterial(e); return a.has(s) === !1 && (a.add(s), s.usedTimes++), a.has(n) === !1 && (a.add(n), n.usedTimes++), this; } remove(e) { const t = this.materialCache.get(e); for (const i of t) i.usedTimes--, i.usedTimes === 0 && this.shaderCache.delete(i.code); return this.materialCache.delete(e), this; } getVertexShaderID(e) { return this._getShaderStage(e.vertexShader).id; } getFragmentShaderID(e) { return this._getShaderStage(e.fragmentShader).id; } dispose() { this.shaderCache.clear(), this.materialCache.clear(); } _getShaderCacheForMaterial(e) { const t = this.materialCache; let i = t.get(e); return i === void 0 && (i = /* @__PURE__ */ new Set(), t.set(e, i)), i; } _getShaderStage(e) { const t = this.shaderCache; let i = t.get(e); return i === void 0 && (i = new Ev(e), t.set(e, i)), i; } } class Ev { constructor(e) { this.id = bv++, this.code = e, this.usedTimes = 0; } } function wv(r, e, t, i, s, n, a) { const o = new Bo(), l = new Tv(), c = /* @__PURE__ */ new Set(), h = [], u = s.logarithmicDepthBuffer, d = s.vertexTextures; let f = s.precision; const g = { 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 v(b) { return c.add(b), b === 0 ? "uv" : `uv${b}`; } function m(b, S, D, N, k) { const H = N.fog, j = k.geometry, q = b.isMeshStandardMaterial ? N.environment : null, te = (b.isMeshStandardMaterial ? t : e).get(b.envMap || q), G = te && te.mapping === Pn ? te.image.height : null, Z = g[b.type]; b.precision !== null && (f = s.getMaxPrecision(b.precision), f !== b.precision && Se("WebGLProgram.getParameters:", b.precision, "not supported, using", f, "instead.")); const se = j.morphAttributes.position || j.morphAttributes.normal || j.morphAttributes.color, Pe = se !== void 0 ? se.length : 0; let ke = 0; j.morphAttributes.position !== void 0 && (ke = 1), j.morphAttributes.normal !== void 0 && (ke = 2), j.morphAttributes.color !== void 0 && (ke = 3); let qe, Ke, Ze, W; if (Z) { const rt = Mi[Z]; qe = rt.vertexShader, Ke = rt.fragmentShader; } else qe = b.vertexShader, Ke = b.fragmentShader, l.update(b), Ze = l.getVertexShaderID(b), W = l.getFragmentShaderID(b); const Y = r.getRenderTarget(), ue = r.state.buffers.depth.getReversed(), Ce = k.isInstancedMesh === !0, be = k.isBatchedMesh === !0, Ee = !!b.map, $e = !!b.matcap, je = !!te, Ve = !!b.aoMap, L = !!b.lightMap, mt = !!b.bumpMap, We = !!b.normalMap, Qe = !!b.displacementMap, fe = !!b.emissiveMap, at = !!b.metalnessMap, Me = !!b.roughnessMap, De = b.anisotropy > 0, C = b.clearcoat > 0, x = b.dispersion > 0, B = b.iridescence > 0, X = b.sheen > 0, K = b.transmission > 0, V = De && !!b.anisotropyMap, xe = C && !!b.clearcoatMap, ne = C && !!b.clearcoatNormalMap, Te = C && !!b.clearcoatRoughnessMap, de = B && !!b.iridescenceMap, $ = B && !!b.iridescenceThicknessMap, re = X && !!b.sheenColorMap, Oe = X && !!b.sheenRoughnessMap, we = !!b.specularMap, he = !!b.specularColorMap, Re = !!b.specularIntensityMap, P = K && !!b.transmissionMap, ae = K && !!b.thicknessMap, ie = !!b.gradientMap, le = !!b.alphaMap, Q = b.alphaTest > 0, J = !!b.alphaHash, ve = !!b.extensions; let Ae = $i; b.toneMapped && (Y === null || Y.isXRRenderTarget === !0) && (Ae = r.toneMapping); const Tt = { shaderID: Z, shaderType: b.type, shaderName: b.name, vertexShader: qe, fragmentShader: Ke, defines: b.defines, customVertexShaderID: Ze, customFragmentShaderID: W, isRawShaderMaterial: b.isRawShaderMaterial === !0, glslVersion: b.glslVersion, precision: f, batching: be, batchingColor: be && k._colorsTexture !== null, instancing: Ce, instancingColor: Ce && k.instanceColor !== null, instancingMorph: Ce && k.morphTexture !== null, supportsVertexTextures: d, outputColorSpace: Y === null ? r.outputColorSpace : Y.isXRRenderTarget === !0 ? Y.texture.colorSpace : Ut, alphaToCoverage: !!b.alphaToCoverage, map: Ee, matcap: $e, envMap: je, envMapMode: je && te.mapping, envMapCubeUVHeight: G, aoMap: Ve, lightMap: L, bumpMap: mt, normalMap: We, displacementMap: d && Qe, emissiveMap: fe, normalMapObjectSpace: We && b.normalMapType === xu, normalMapTangentSpace: We && b.normalMapType === Dn, metalnessMap: at, roughnessMap: Me, anisotropy: De, anisotropyMap: V, clearcoat: C, clearcoatMap: xe, clearcoatNormalMap: ne, clearcoatRoughnessMap: Te, dispersion: x, iridescence: B, iridescenceMap: de, iridescenceThicknessMap: $, sheen: X, sheenColorMap: re, sheenRoughnessMap: Oe, specularMap: we, specularColorMap: he, specularIntensityMap: Re, transmission: K, transmissionMap: P, thicknessMap: ae, gradientMap: ie, opaque: b.transparent === !1 && b.blending === Br && b.alphaToCoverage === !1, alphaMap: le, alphaTest: Q, alphaHash: J, combine: b.combine, // mapUv: Ee && v(b.map.channel), aoMapUv: Ve && v(b.aoMap.channel), lightMapUv: L && v(b.lightMap.channel), bumpMapUv: mt && v(b.bumpMap.channel), normalMapUv: We && v(b.normalMap.channel), displacementMapUv: Qe && v(b.displacementMap.channel), emissiveMapUv: fe && v(b.emissiveMap.channel), metalnessMapUv: at && v(b.metalnessMap.channel), roughnessMapUv: Me && v(b.roughnessMap.channel), anisotropyMapUv: V && v(b.anisotropyMap.channel), clearcoatMapUv: xe && v(b.clearcoatMap.channel), clearcoatNormalMapUv: ne && v(b.clearcoatNormalMap.channel), clearcoatRoughnessMapUv: Te && v(b.clearcoatRoughnessMap.channel), iridescenceMapUv: de && v(b.iridescenceMap.channel), iridescenceThicknessMapUv: $ && v(b.iridescenceThicknessMap.channel), sheenColorMapUv: re && v(b.sheenColorMap.channel), sheenRoughnessMapUv: Oe && v(b.sheenRoughnessMap.channel), specularMapUv: we && v(b.specularMap.channel), specularColorMapUv: he && v(b.specularColorMap.channel), specularIntensityMapUv: Re && v(b.specularIntensityMap.channel), transmissionMapUv: P && v(b.transmissionMap.channel), thicknessMapUv: ae && v(b.thicknessMap.channel), alphaMapUv: le && v(b.alphaMap.channel), // vertexTangents: !!j.attributes.tangent && (We || De), vertexColors: b.vertexColors, vertexAlphas: b.vertexColors === !0 && !!j.attributes.color && j.attributes.color.itemSize === 4, pointsUvs: k.isPoints === !0 && !!j.attributes.uv && (Ee || le), fog: !!H, useFog: b.fog === !0, fogExp2: !!H && H.isFogExp2, flatShading: b.flatShading === !0 && b.wireframe === !1, sizeAttenuation: b.sizeAttenuation === !0, logarithmicDepthBuffer: u, reversedDepthBuffer: ue, skinning: k.isSkinnedMesh === !0, morphTargets: j.morphAttributes.position !== void 0, morphNormals: j.morphAttributes.normal !== void 0, morphColors: j.morphAttributes.color !== void 0, morphTargetsCount: Pe, morphTextureStride: ke, numDirLights: S.directional.length, numPointLights: S.point.length, numSpotLights: S.spot.length, numSpotLightMaps: S.spotLightMap.length, numRectAreaLights: S.rectArea.length, numHemiLights: S.hemi.length, numDirLightShadows: S.directionalShadowMap.length, numPointLightShadows: S.pointShadowMap.length, numSpotLightShadows: S.spotShadowMap.length, numSpotLightShadowsWithMaps: S.numSpotLightShadowsWithMaps, numLightProbes: S.numLightProbes, numClippingPlanes: a.numPlanes, numClipIntersection: a.numIntersection, dithering: b.dithering, shadowMapEnabled: r.shadowMap.enabled && D.length > 0, shadowMapType: r.shadowMap.type, toneMapping: Ae, decodeVideoTexture: Ee && b.map.isVideoTexture === !0 && Xe.getTransfer(b.map.colorSpace) === et, decodeVideoTextureEmissive: fe && b.emissiveMap.isVideoTexture === !0 && Xe.getTransfer(b.emissiveMap.colorSpace) === et, premultipliedAlpha: b.premultipliedAlpha, doubleSided: b.side === Vt, flipSided: b.side === Ft, useDepthPacking: b.depthPacking >= 0, depthPacking: b.depthPacking || 0, index0AttributeName: b.index0AttributeName, extensionClipCullDistance: ve && b.extensions.clipCullDistance === !0 && i.has("WEBGL_clip_cull_distance"), extensionMultiDraw: (ve && b.extensions.multiDraw === !0 || be) && i.has("WEBGL_multi_draw"), rendererExtensionParallelShaderCompile: i.has("KHR_parallel_shader_compile"), customProgramCacheKey: b.customProgramCacheKey() }; return Tt.vertexUv1s = c.has(1), Tt.vertexUv2s = c.has(2), Tt.vertexUv3s = c.has(3), c.clear(), Tt; } function p(b) { const S = []; if (b.shaderID ? S.push(b.shaderID) : (S.push(b.customVertexShaderID), S.push(b.customFragmentShaderID)), b.defines !== void 0) for (const D in b.defines) S.push(D), S.push(b.defines[D]); return b.isRawShaderMaterial === !1 && (y(S, b), _(S, b), S.push(r.outputColorSpace)), S.push(b.customProgramCacheKey), S.join(); } function y(b, S) { b.push(S.precision), b.push(S.outputColorSpace), b.push(S.envMapMode), b.push(S.envMapCubeUVHeight), b.push(S.mapUv), b.push(S.alphaMapUv), b.push(S.lightMapUv), b.push(S.aoMapUv), b.push(S.bumpMapUv), b.push(S.normalMapUv), b.push(S.displacementMapUv), b.push(S.emissiveMapUv), b.push(S.metalnessMapUv), b.push(S.roughnessMapUv), b.push(S.anisotropyMapUv), b.push(S.clearcoatMapUv), b.push(S.clearcoatNormalMapUv), b.push(S.clearcoatRoughnessMapUv), b.push(S.iridescenceMapUv), b.push(S.iridescenceThicknessMapUv), b.push(S.sheenColorMapUv), b.push(S.sheenRoughnessMapUv), b.push(S.specularMapUv), b.push(S.specularColorMapUv), b.push(S.specularIntensityMapUv), b.push(S.transmissionMapUv), b.push(S.thicknessMapUv), b.push(S.combine), b.push(S.fogExp2), b.push(S.sizeAttenuation), b.push(S.morphTargetsCount), b.push(S.morphAttributeCount), b.push(S.numDirLights), b.push(S.numPointLights), b.push(S.numSpotLights), b.push(S.numSpotLightMaps), b.push(S.numHemiLights), b.push(S.numRectAreaLights), b.push(S.numDirLightShadows), b.push(S.numPointLightShadows), b.push(S.numSpotLightShadows), b.push(S.numSpotLightShadowsWithMaps), b.push(S.numLightProbes), b.push(S.shadowMapType), b.push(S.toneMapping), b.push(S.numClippingPlanes), b.push(S.numClipIntersection), b.push(S.depthPacking); } function _(b, S) { o.disableAll(), S.supportsVertexTextures && o.enable(0), S.instancing && o.enable(1), S.instancingColor && o.enable(2), S.instancingMorph && o.enable(3), S.matcap && o.enable(4), S.envMap && o.enable(5), S.normalMapObjectSpace && o.enable(6), S.normalMapTangentSpace && o.enable(7), S.clearcoat && o.enable(8), S.iridescence && o.enable(9), S.alphaTest && o.enable(10), S.vertexColors && o.enable(11), S.vertexAlphas && o.enable(12), S.vertexUv1s && o.enable(13), S.vertexUv2s && o.enable(14), S.vertexUv3s && o.enable(15), S.vertexTangents && o.enable(16), S.anisotropy && o.enable(17), S.alphaHash && o.enable(18), S.batching && o.enable(19), S.dispersion && o.enable(20), S.batchingColor && o.enable(21), S.gradientMap && o.enable(22), b.push(o.mask), o.disableAll(), S.fog && o.enable(0), S.useFog && o.enable(1), S.flatShading && o.enable(2), S.logarithmicDepthBuffer && o.enable(3), S.reversedDepthBuffer && o.enable(4), S.skinning && o.enable(5), S.morphTargets && o.enable(6), S.morphNormals && o.enable(7), S.morphColors && o.enable(8), S.premultipliedAlpha && o.enable(9), S.shadowMapEnabled && o.enable(10), S.doubleSided && o.enable(11), S.flipSided && o.enable(12), S.useDepthPacking && o.enable(13), S.dithering && o.enable(14), S.transmission && o.enable(15), S.sheen && o.enable(16), S.opaque && o.enable(17), S.pointsUvs && o.enable(18), S.decodeVideoTexture && o.enable(19), S.decodeVideoTextureEmissive && o.enable(20), S.alphaToCoverage && o.enable(21), b.push(o.mask); } function E(b) { const S = g[b.type]; let D; if (S) { const N = Mi[S]; D = ui.clone(N.uniforms); } else D = b.uniforms; return D; } function A(b, S) { let D; for (let N = 0, k = h.length; N < k; N++) { const H = h[N]; if (H.cacheKey === S) { D = H, ++D.usedTimes; break; } } return D === void 0 && (D = new Sv(r, S, b, n), h.push(D)), D; } function T(b) { if (--b.usedTimes === 0) { const S = h.indexOf(b); h[S] = h[h.length - 1], h.pop(), b.destroy(); } } function R(b) { l.remove(b); } function I() { l.dispose(); } return { getParameters: m, getProgramCacheKey: p, getUniforms: E, acquireProgram: A, releaseProgram: T, releaseShaderCache: R, // Exposed for resource monitoring & error feedback via renderer.info: programs: h, dispose: I }; } function Cv() { let r = /* @__PURE__ */ new WeakMap(); function e(a) { return r.has(a); } function t(a) { let o = r.get(a); return o === void 0 && (o = {}, r.set(a, o)), o; } function i(a) { r.delete(a); } function s(a, o, l) { r.get(a)[o] = l; } function n() { r = /* @__PURE__ */ new WeakMap(); } return { has: e, get: t, remove: i, update: s, dispose: n }; } function Rv(r, e) { return r.groupOrder !== e.groupOrder ? r.groupOrder - e.groupOrder : r.renderOrder !== e.renderOrder ? r.renderOrder - e.renderOrder : r.material.id !== e.material.id ? r.material.id - e.material.id : r.z !== e.z ? r.z - e.z : r.id - e.id; } function yc(r, e) { return r.groupOrder !== e.groupOrder ? r.groupOrder - e.groupOrder : r.renderOrder !== e.renderOrder ? r.renderOrder - e.renderOrder : r.z !== e.z ? e.z - r.z : r.id - e.id; } function Mc() { const r = []; let e = 0; const t = [], i = [], s = []; function n() { e = 0, t.length = 0, i.length = 0, s.length = 0; } function a(u, d, f, g, v, m) { let p = r[e]; return p === void 0 ? (p = { id: u.id, object: u, geometry: d, material: f, groupOrder: g, renderOrder: u.renderOrder, z: v, group: m }, r[e] = p) : (p.id = u.id, p.object = u, p.geometry = d, p.material = f, p.groupOrder = g, p.renderOrder = u.renderOrder, p.z = v, p.group = m), e++, p; } function o(u, d, f, g, v, m) { const p = a(u, d, f, g, v, m); f.transmission > 0 ? i.push(p) : f.transparent === !0 ? s.push(p) : t.push(p); } function l(u, d, f, g, v, m) { const p = a(u, d, f, g, v, m); f.transmission > 0 ? i.unshift(p) : f.transparent === !0 ? s.unshift(p) : t.unshift(p); } function c(u, d) { t.length > 1 && t.sort(u || Rv), i.length > 1 && i.sort(d || yc), s.length > 1 && s.sort(d || yc); } function h() { for (let u = e, d = r.length; u < d; u++) { const f = r[u]; if (f.id === null) break; f.id = null, f.object = null, f.geometry = null, f.material = null, f.group = null; } } return { opaque: t, transmissive: i, transparent: s, init: n, push: o, unshift: l, finish: h, sort: c }; } function Av() { let r = /* @__PURE__ */ new WeakMap(); function e(i, s) { const n = r.get(i); let a; return n === void 0 ? (a = new Mc(), r.set(i, [a])) : s >= n.length ? (a = new Mc(), n.push(a)) : a = n[s], a; } function t() { r = /* @__PURE__ */ new WeakMap(); } return { get: e, dispose: t }; } function Pv() { const r = {}; return { get: function(e) { if (r[e.id] !== void 0) return r[e.id]; let t; switch (e.type) { case "DirectionalLight": t = { direction: new w(), color: new _e() }; break; case "SpotLight": t = { position: new w(), direction: new w(), color: new _e(), distance: 0, coneCos: 0, penumbraCos: 0, decay: 0 }; break; case "PointLight": t = { position: new w(), color: new _e(), distance: 0, decay: 0 }; break; case "HemisphereLight": t = { direction: new w(), skyColor: new _e(), groundColor: new _e() }; break; case "RectAreaLight": t = { color: new _e(), position: new w(), halfWidth: new w(), halfHeight: new w() }; break; } return r[e.id] = t, t; } }; } function Dv() { const r = {}; return { get: function(e) { if (r[e.id] !== void 0) return r[e.id]; let t; switch (e.type) { case "DirectionalLight": t = { shadowIntensity: 1, shadowBias: 0, shadowNormalBias: 0, shadowRadius: 1, shadowMapSize: new oe() }; break; case "SpotLight": t = { shadowIntensity: 1, shadowBias: 0, shadowNormalBias: 0, shadowRadius: 1, shadowMapSize: new oe() }; break; case "PointLight": t = { shadowIntensity: 1, shadowBias: 0, shadowNormalBias: 0, shadowRadius: 1, shadowMapSize: new oe(), shadowCameraNear: 1, shadowCameraFar: 1e3 }; break; } return r[e.id] = t, t; } }; } let Lv = 0; function Iv(r, e) { return (e.castShadow ? 2 : 0) - (r.castShadow ? 2 : 0) + (e.map ? 1 : 0) - (r.map ? 1 : 0); } function Uv(r) { const e = new Pv(), t = Dv(), i = { version: 0, hash: { directionalLength: -1, pointLength: -1, spotLength: -1, rectAreaLength: -1, hemiLength: -1, numDirectionalShadows: -1, numPointShadows: -1, numSpotShadows: -1, numSpotMaps: -1, numLightProbes: -1 }, ambient: [0, 0, 0], probe: [], directional: [], directionalShadow: [], directionalShadowMap: [], directionalShadowMatrix: [], spot: [], spotLightMap: [], spotShadow: [], spotShadowMap: [], spotLightMatrix: [], rectArea: [], rectAreaLTC1: null, rectAreaLTC2: null, point: [], pointShadow: [], pointShadowMap: [], pointShadowMatrix: [], hemi: [], numSpotLightShadowsWithMaps: 0, numLightProbes: 0 }; for (let c = 0; c < 9; c++) i.probe.push(new w()); const s = new w(), n = new Ue(), a = new Ue(); function o(c) { let h = 0, u = 0, d = 0; for (let b = 0; b < 9; b++) i.probe[b].set(0, 0, 0); let f = 0, g = 0, v = 0, m = 0, p = 0, y = 0, _ = 0, E = 0, A = 0, T = 0, R = 0; c.sort(Iv); for (let b = 0, S = c.length; b < S; b++) { const D = c[b], N = D.color, k = D.intensity, H = D.distance, j = D.shadow && D.shadow.map ? D.shadow.map.texture : null; if (D.isAmbientLight) h += N.r * k, u += N.g * k, d += N.b * k; else if (D.isLightProbe) { for (let q = 0; q < 9; q++) i.probe[q].addScaledVector(D.sh.coefficients[q], k); R++; } else if (D.isDirectionalLight) { const q = e.get(D); if (q.color.copy(D.color).multiplyScalar(D.intensity), D.castShadow) { const te = D.shadow, G = t.get(D); G.shadowIntensity = te.intensity, G.shadowBias = te.bias, G.shadowNormalBias = te.normalBias, G.shadowRadius = te.radius, G.shadowMapSize = te.mapSize, i.directionalShadow[f] = G, i.directionalShadowMap[f] = j, i.directionalShadowMatrix[f] = D.shadow.matrix, y++; } i.directional[f] = q, f++; } else if (D.isSpotLight) { const q = e.get(D); q.position.setFromMatrixPosition(D.matrixWorld), q.color.copy(N).multiplyScalar(k), q.distance = H, q.coneCos = Math.cos(D.angle), q.penumbraCos = Math.cos(D.angle * (1 - D.penumbra)), q.decay = D.decay, i.spot[v] = q; const te = D.shadow; if (D.map && (i.spotLightMap[A] = D.map, A++, te.updateMatrices(D), D.castShadow && T++), i.spotLightMatrix[v] = te.matrix, D.castShadow) { const G = t.get(D); G.shadowIntensity = te.intensity, G.shadowBias = te.bias, G.shadowNormalBias = te.normalBias, G.shadowRadius = te.radius, G.shadowMapSize = te.mapSize, i.spotShadow[v] = G, i.spotShadowMap[v] = j, E++; } v++; } else if (D.isRectAreaLight) { const q = e.get(D); q.color.copy(N).multiplyScalar(k), q.halfWidth.set(D.width * 0.5, 0, 0), q.halfHeight.set(0, D.height * 0.5, 0), i.rectArea[m] = q, m++; } else if (D.isPointLight) { const q = e.get(D); if (q.color.copy(D.color).multiplyScalar(D.intensity), q.distance = D.distance, q.decay = D.decay, D.castShadow) { const te = D.shadow, G = t.get(D); G.shadowIntensity = te.intensity, G.shadowBias = te.bias, G.shadowNormalBias = te.normalBias, G.shadowRadius = te.radius, G.shadowMapSize = te.mapSize, G.shadowCameraNear = te.camera.near, G.shadowCameraFar = te.camera.far, i.pointShadow[g] = G, i.pointShadowMap[g] = j, i.pointShadowMatrix[g] = D.shadow.matrix, _++; } i.point[g] = q, g++; } else if (D.isHemisphereLight) { const q = e.get(D); q.skyColor.copy(D.color).multiplyScalar(k), q.groundColor.copy(D.groundColor).multiplyScalar(k), i.hemi[p] = q, p++; } } m > 0 && (r.has("OES_texture_float_linear") === !0 ? (i.rectAreaLTC1 = ce.LTC_FLOAT_1, i.rectAreaLTC2 = ce.LTC_FLOAT_2) : (i.rectAreaLTC1 = ce.LTC_HALF_1, i.rectAreaLTC2 = ce.LTC_HALF_2)), i.ambient[0] = h, i.ambient[1] = u, i.ambient[2] = d; const I = i.hash; (I.directionalLength !== f || I.pointLength !== g || I.spotLength !== v || I.rectAreaLength !== m || I.hemiLength !== p || I.numDirectionalShadows !== y || I.numPointShadows !== _ || I.numSpotShadows !== E || I.numSpotMaps !== A || I.numLightProbes !== R) && (i.directional.length = f, i.spot.length = v, i.rectArea.length = m, i.point.length = g, i.hemi.length = p, i.directionalShadow.length = y, i.directionalShadowMap.length = y, i.pointShadow.length = _, i.pointShadowMap.length = _, i.spotShadow.length = E, i.spotShadowMap.length = E, i.directionalShadowMatrix.length = y, i.pointShadowMatrix.length = _, i.spotLightMatrix.length = E + A - T, i.spotLightMap.length = A, i.numSpotLightShadowsWithMaps = T, i.numLightProbes = R, I.directionalLength = f, I.pointLength = g, I.spotLength = v, I.rectAreaLength = m, I.hemiLength = p, I.numDirectionalShadows = y, I.numPointShadows = _, I.numSpotShadows = E, I.numSpotMaps = A, I.numLightProbes = R, i.version = Lv++); } function l(c, h) { let u = 0, d = 0, f = 0, g = 0, v = 0; const m = h.matrixWorldInverse; for (let p = 0, y = c.length; p < y; p++) { const _ = c[p]; if (_.isDirectionalLight) { const E = i.directional[u]; E.direction.setFromMatrixPosition(_.matrixWorld), s.setFromMatrixPosition(_.target.matrixWorld), E.direction.sub(s), E.direction.transformDirection(m), u++; } else if (_.isSpotLight) { const E = i.spot[f]; E.position.setFromMatrixPosition(_.matrixWorld), E.position.applyMatrix4(m), E.direction.setFromMatrixPosition(_.matrixWorld), s.setFromMatrixPosition(_.target.matrixWorld), E.direction.sub(s), E.direction.transformDirection(m), f++; } else if (_.isRectAreaLight) { const E = i.rectArea[g]; E.position.setFromMatrixPosition(_.matrixWorld), E.position.applyMatrix4(m), a.identity(), n.copy(_.matrixWorld), n.premultiply(m), a.extractRotation(n), E.halfWidth.set(_.width * 0.5, 0, 0), E.halfHeight.set(0, _.height * 0.5, 0), E.halfWidth.applyMatrix4(a), E.halfHeight.applyMatrix4(a), g++; } else if (_.isPointLight) { const E = i.point[d]; E.position.setFromMatrixPosition(_.matrixWorld), E.position.applyMatrix4(m), d++; } else if (_.isHemisphereLight) { const E = i.hemi[v]; E.direction.setFromMatrixPosition(_.matrixWorld), E.direction.transformDirection(m), v++; } } } return { setup: o, setupView: l, state: i }; } function Sc(r) { const e = new Uv(r), t = [], i = []; function s(h) { c.camera = h, t.length = 0, i.length = 0; } function n(h) { t.push(h); } function a(h) { i.push(h); } function o() { e.setup(t); } function l(h) { e.setupView(t, h); } const c = { lightsArray: t, shadowsArray: i, camera: null, lights: e, transmissionRenderTarget: {} }; return { init: s, state: c, setupLights: o, setupLightsView: l, pushLight: n, pushShadow: a }; } function Nv(r) { let e = /* @__PURE__ */ new WeakMap(); function t(s, n = 0) { const a = e.get(s); let o; return a === void 0 ? (o = new Sc(r), e.set(s, [o])) : n >= a.length ? (o = new Sc(r), a.push(o)) : o = a[n], o; } function i() { e = /* @__PURE__ */ new WeakMap(); } return { get: t, dispose: i }; } const Ov = `void main() { gl_Position = vec4( position, 1.0 ); }`, Bv = `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 Fv(r, e, t) { let i = new Vo(); const s = new oe(), n = new oe(), a = new Je(), o = new fh({ depthPacking: th }), l = new Id(), c = {}, h = t.maxTextureSize, u = { [Ti]: Ft, [Ft]: Ti, [Vt]: Vt }, d = new ct({ defines: { VSM_SAMPLES: 8 }, uniforms: { shadow_pass: { value: null }, resolution: { value: new oe() }, radius: { value: 4 } }, vertexShader: Ov, fragmentShader: Bv }), f = d.clone(); f.defines.HORIZONTAL_PASS = 1; const g = new Qt(); g.setAttribute( "position", new zt( new Float32Array([-1, -1, 0.5, 3, -1, 0.5, -1, 3, 0.5]), 3 ) ); const v = new nt(g, d), m = this; this.enabled = !1, this.autoUpdate = !0, this.needsUpdate = !1, this.type = Bc; let p = this.type; this.render = function(T, R, I) { if (m.enabled === !1 || m.autoUpdate === !1 && m.needsUpdate === !1 || T.length === 0) return; const b = r.getRenderTarget(), S = r.getActiveCubeFace(), D = r.getActiveMipmapLevel(), N = r.state; N.setBlending(vt), N.buffers.depth.getReversed() === !0 ? N.buffers.color.setClear(0, 0, 0, 0) : N.buffers.color.setClear(1, 1, 1, 1), N.buffers.depth.setTest(!0), N.setScissorTest(!1); const k = p !== Bi && this.type === Bi, H = p === Bi && this.type !== Bi; for (let j = 0, q = T.length; j < q; j++) { const te = T[j], G = te.shadow; if (G === void 0) { Se("WebGLShadowMap:", te, "has no shadow."); continue; } if (G.autoUpdate === !1 && G.needsUpdate === !1) continue; s.copy(G.mapSize); const Z = G.getFrameExtents(); if (s.multiply(Z), n.copy(G.mapSize), (s.x > h || s.y > h) && (s.x > h && (n.x = Math.floor(h / Z.x), s.x = n.x * Z.x, G.mapSize.x = n.x), s.y > h && (n.y = Math.floor(h / Z.y), s.y = n.y * Z.y, G.mapSize.y = n.y)), G.map === null || k === !0 || H === !0) { const Pe = this.type !== Bi ? { minFilter: Dt, magFilter: Dt } : {}; G.map !== null && G.map.dispose(), G.map = new _t(s.x, s.y, Pe), G.map.texture.name = te.name + ".shadowMap", G.camera.updateProjectionMatrix(); } r.setRenderTarget(G.map), r.clear(); const se = G.getViewportCount(); for (let Pe = 0; Pe < se; Pe++) { const ke = G.getViewport(Pe); a.set( n.x * ke.x, n.y * ke.y, n.x * ke.z, n.y * ke.w ), N.viewport(a), G.updateMatrices(te, Pe), i = G.getFrustum(), E(R, I, G.camera, te, this.type); } G.isPointLightShadow !== !0 && this.type === Bi && y(G, I), G.needsUpdate = !1; } p = this.type, m.needsUpdate = !1, r.setRenderTarget(b, S, D); }; function y(T, R) { const I = e.update(v); d.defines.VSM_SAMPLES !== T.blurSamples && (d.defines.VSM_SAMPLES = T.blurSamples, f.defines.VSM_SAMPLES = T.blurSamples, d.needsUpdate = !0, f.needsUpdate = !0), T.mapPass === null && (T.mapPass = new _t(s.x, s.y)), d.uniforms.shadow_pass.value = T.map.texture, d.uniforms.resolution.value = T.mapSize, d.uniforms.radius.value = T.radius, r.setRenderTarget(T.mapPass), r.clear(), r.renderBufferDirect(R, null, I, d, v, null), f.uniforms.shadow_pass.value = T.mapPass.texture, f.uniforms.resolution.value = T.mapSize, f.uniforms.radius.value = T.radius, r.setRenderTarget(T.map), r.clear(), r.renderBufferDirect(R, null, I, f, v, null); } function _(T, R, I, b) { let S = null; const D = I.isPointLight === !0 ? T.customDistanceMaterial : T.customDepthMaterial; if (D !== void 0) S = D; else if (S = I.isPointLight === !0 ? l : o, r.localClippingEnabled && R.clipShadows === !0 && Array.isArray(R.clippingPlanes) && R.clippingPlanes.length !== 0 || R.displacementMap && R.displacementScale !== 0 || R.alphaMap && R.alphaTest > 0 || R.map && R.alphaTest > 0 || R.alphaToCoverage === !0) { const N = S.uuid, k = R.uuid; let H = c[N]; H === void 0 && (H = {}, c[N] = H); let j = H[k]; j === void 0 && (j = S.clone(), H[k] = j, R.addEventListener("dispose", A)), S = j; } if (S.visible = R.visible, S.wireframe = R.wireframe, b === Bi ? S.side = R.shadowSide !== null ? R.shadowSide : R.side : S.side = R.shadowSide !== null ? R.shadowSide : u[R.side], S.alphaMap = R.alphaMap, S.alphaTest = R.alphaToCoverage === !0 ? 0.5 : R.alphaTest, S.map = R.map, S.clipShadows = R.clipShadows, S.clippingPlanes = R.clippingPlanes, S.clipIntersection = R.clipIntersection, S.displacementMap = R.displacementMap, S.displacementScale = R.displacementScale, S.displacementBias = R.displacementBias, S.wireframeLinewidth = R.wireframeLinewidth, S.linewidth = R.linewidth, I.isPointLight === !0 && S.isMeshDistanceMaterial === !0) { const N = r.properties.get(S); N.light = I; } return S; } function E(T, R, I, b, S) { if (T.visible === !1) return; if (T.layers.test(R.layers) && (T.isMesh || T.isLine || T.isPoints) && (T.castShadow || T.receiveShadow && S === Bi) && (!T.frustumCulled || i.intersectsObject(T))) { T.modelViewMatrix.multiplyMatrices(I.matrixWorldInverse, T.matrixWorld); const N = e.update(T), k = T.material; if (Array.isArray(k)) { const H = N.groups; for (let j = 0, q = H.length; j < q; j++) { const te = H[j], G = k[te.materialIndex]; if (G && G.visible) { const Z = _(T, G, b, S); T.onBeforeShadow(r, T, R, I, N, Z, te), r.renderBufferDirect(I, null, N, Z, T, te), T.onAfterShadow(r, T, R, I, N, Z, te); } } } else if (k.visible) { const H = _(T, k, b, S); T.onBeforeShadow(r, T, R, I, N, H, null), r.renderBufferDirect(I, null, N, H, T, null), T.onAfterShadow(r, T, R, I, N, H, null); } } const D = T.children; for (let N = 0, k = D.length; N < k; N++) E(D[N], R, I, b, S); } function A(T) { T.target.removeEventListener("dispose", A); for (const R in c) { const I = c[R], b = T.target.uuid; b in I && (I[b].dispose(), delete I[b]); } } } const zv = { [Ra]: Aa, [Pa]: Ia, [Da]: Ua, [Vr]: La, [Aa]: Ra, [Ia]: Pa, [Ua]: Da, [La]: Vr }; function kv(r, e) { function t() { let P = !1; const ae = new Je(); let ie = null; const le = new Je(0, 0, 0, 0); return { setMask: function(Q) { ie !== Q && !P && (r.colorMask(Q, Q, Q, Q), ie = Q); }, setLocked: function(Q) { P = Q; }, setClear: function(Q, J, ve, Ae, Tt) { Tt === !0 && (Q *= Ae, J *= Ae, ve *= Ae), ae.set(Q, J, ve, Ae), le.equals(ae) === !1 && (r.clearColor(Q, J, ve, Ae), le.copy(ae)); }, reset: function() { P = !1, ie = null, le.set(-1, 0, 0, 0); } }; } function i() { let P = !1, ae = !1, ie = null, le = null, Q = null; return { setReversed: function(J) { if (ae !== J) { const ve = e.get("EXT_clip_control"); J ? ve.clipControlEXT(ve.LOWER_LEFT_EXT, ve.ZERO_TO_ONE_EXT) : ve.clipControlEXT(ve.LOWER_LEFT_EXT, ve.NEGATIVE_ONE_TO_ONE_EXT), ae = J; const Ae = Q; Q = null, this.setClear(Ae); } }, getReversed: function() { return ae; }, setTest: function(J) { J ? Y(r.DEPTH_TEST) : ue(r.DEPTH_TEST); }, setMask: function(J) { ie !== J && !P && (r.depthMask(J), ie = J); }, setFunc: function(J) { if (ae && (J = zv[J]), le !== J) { switch (J) { case Ra: r.depthFunc(r.NEVER); break; case Aa: r.depthFunc(r.ALWAYS); break; case Pa: r.depthFunc(r.LESS); break; case Vr: r.depthFunc(r.LEQUAL); break; case Da: r.depthFunc(r.EQUAL); break; case La: r.depthFunc(r.GEQUAL); break; case Ia: r.depthFunc(r.GREATER); break; case Ua: r.depthFunc(r.NOTEQUAL); break; default: r.depthFunc(r.LEQUAL); } le = J; } }, setLocked: function(J) { P = J; }, setClear: function(J) { Q !== J && (ae && (J = 1 - J), r.clearDepth(J), Q = J); }, reset: function() { P = !1, ie = null, le = null, Q = null, ae = !1; } }; } function s() { let P = !1, ae = null, ie = null, le = null, Q = null, J = null, ve = null, Ae = null, Tt = null; return { setTest: function(rt) { P || (rt ? Y(r.STENCIL_TEST) : ue(r.STENCIL_TEST)); }, setMask: function(rt) { ae !== rt && !P && (r.stencilMask(rt), ae = rt); }, setFunc: function(rt, _i, ei) { (ie !== rt || le !== _i || Q !== ei) && (r.stencilFunc(rt, _i, ei), ie = rt, le = _i, Q = ei); }, setOp: function(rt, _i, ei) { (J !== rt || ve !== _i || Ae !== ei) && (r.stencilOp(rt, _i, ei), J = rt, ve = _i, Ae = ei); }, setLocked: function(rt) { P = rt; }, setClear: function(rt) { Tt !== rt && (r.clearStencil(rt), Tt = rt); }, reset: function() { P = !1, ae = null, ie = null, le = null, Q = null, J = null, ve = null, Ae = null, Tt = null; } }; } const n = new t(), a = new i(), o = new s(), l = /* @__PURE__ */ new WeakMap(), c = /* @__PURE__ */ new WeakMap(); let h = {}, u = {}, d = /* @__PURE__ */ new WeakMap(), f = [], g = null, v = !1, m = null, p = null, y = null, _ = null, E = null, A = null, T = null, R = new _e(0, 0, 0), I = 0, b = !1, S = null, D = null, N = null, k = null, H = null; const j = r.getParameter(r.MAX_COMBINED_TEXTURE_IMAGE_UNITS); let q = !1, te = 0; const G = r.getParameter(r.VERSION); G.indexOf("WebGL") !== -1 ? (te = parseFloat(/^WebGL (\d)/.exec(G)[1]), q = te >= 1) : G.indexOf("OpenGL ES") !== -1 && (te = parseFloat(/^OpenGL ES (\d)/.exec(G)[1]), q = te >= 2); let Z = null, se = {}; const Pe = r.getParameter(r.SCISSOR_BOX), ke = r.getParameter(r.VIEWPORT), qe = new Je().fromArray(Pe), Ke = new Je().fromArray(ke); function Ze(P, ae, ie, le) { const Q = new Uint8Array(4), J = r.createTexture(); r.bindTexture(P, J), r.texParameteri(P, r.TEXTURE_MIN_FILTER, r.NEAREST), r.texParameteri(P, r.TEXTURE_MAG_FILTER, r.NEAREST); for (let ve = 0; ve < ie; ve++) P === r.TEXTURE_3D || P === r.TEXTURE_2D_ARRAY ? r.texImage3D(ae, 0, r.RGBA, 1, 1, le, 0, r.RGBA, r.UNSIGNED_BYTE, Q) : r.texImage2D(ae + ve, 0, r.RGBA, 1, 1, 0, r.RGBA, r.UNSIGNED_BYTE, Q); return J; } const W = {}; W[r.TEXTURE_2D] = Ze(r.TEXTURE_2D, r.TEXTURE_2D, 1), W[r.TEXTURE_CUBE_MAP] = Ze(r.TEXTURE_CUBE_MAP, r.TEXTURE_CUBE_MAP_POSITIVE_X, 6), W[r.TEXTURE_2D_ARRAY] = Ze(r.TEXTURE_2D_ARRAY, r.TEXTURE_2D_ARRAY, 1, 1), W[r.TEXTURE_3D] = Ze(r.TEXTURE_3D, r.TEXTURE_3D, 1, 1), n.setClear(0, 0, 0, 1), a.setClear(1), o.setClear(0), Y(r.DEPTH_TEST), a.setFunc(Vr), mt(!1), We(nl), Y(r.CULL_FACE), Ve(vt); function Y(P) { h[P] !== !0 && (r.enable(P), h[P] = !0); } function ue(P) { h[P] !== !1 && (r.disable(P), h[P] = !1); } function Ce(P, ae) { return u[P] !== ae ? (r.bindFramebuffer(P, ae), u[P] = ae, P === r.DRAW_FRAMEBUFFER && (u[r.FRAMEBUFFER] = ae), P === r.FRAMEBUFFER && (u[r.DRAW_FRAMEBUFFER] = ae), !0) : !1; } function be(P, ae) { let ie = f, le = !1; if (P) { ie = d.get(ae), ie === void 0 && (ie = [], d.set(ae, ie)); const Q = P.textures; if (ie.length !== Q.length || ie[0] !== r.COLOR_ATTACHMENT0) { for (let J = 0, ve = Q.length; J < ve; J++) ie[J] = r.COLOR_ATTACHMENT0 + J; ie.length = Q.length, le = !0; } } else ie[0] !== r.BACK && (ie[0] = r.BACK, le = !0); le && r.drawBuffers(ie); } function Ee(P) { return g !== P ? (r.useProgram(P), g = P, !0) : !1; } const $e = { [li]: r.FUNC_ADD, [Qh]: r.FUNC_SUBTRACT, [eu]: r.FUNC_REVERSE_SUBTRACT }; $e[tu] = r.MIN, $e[iu] = r.MAX; const je = { [ms]: r.ZERO, [ru]: r.ONE, [su]: r.SRC_COLOR, [Ta]: r.SRC_ALPHA, [lu]: r.SRC_ALPHA_SATURATE, [Ca]: r.DST_COLOR, [wa]: r.DST_ALPHA, [nu]: r.ONE_MINUS_SRC_COLOR, [Ea]: r.ONE_MINUS_SRC_ALPHA, [ou]: r.ONE_MINUS_DST_COLOR, [au]: r.ONE_MINUS_DST_ALPHA, [cu]: r.CONSTANT_COLOR, [hu]: r.ONE_MINUS_CONSTANT_COLOR, [uu]: r.CONSTANT_ALPHA, [du]: r.ONE_MINUS_CONSTANT_ALPHA }; function Ve(P, ae, ie, le, Q, J, ve, Ae, Tt, rt) { if (P === vt) { v === !0 && (ue(r.BLEND), v = !1); return; } if (v === !1 && (Y(r.BLEND), v = !0), P !== zc) { if (P !== m || rt !== b) { if ((p !== li || E !== li) && (r.blendEquation(r.FUNC_ADD), p = li, E = li), rt) switch (P) { case Br: r.blendFuncSeparate(r.ONE, r.ONE_MINUS_SRC_ALPHA, r.ONE, r.ONE_MINUS_SRC_ALPHA); break; case yn: r.blendFunc(r.ONE, r.ONE); break; case al: r.blendFuncSeparate(r.ZERO, r.ONE_MINUS_SRC_COLOR, r.ZERO, r.ONE); break; case ol: r.blendFuncSeparate(r.DST_COLOR, r.ONE_MINUS_SRC_ALPHA, r.ZERO, r.ONE); break; default: He("WebGLState: Invalid blending: ", P); break; } else switch (P) { case Br: r.blendFuncSeparate(r.SRC_ALPHA, r.ONE_MINUS_SRC_ALPHA, r.ONE, r.ONE_MINUS_SRC_ALPHA); break; case yn: r.blendFuncSeparate(r.SRC_ALPHA, r.ONE, r.ONE, r.ONE); break; case al: He("WebGLState: SubtractiveBlending requires material.premultipliedAlpha = true"); break; case ol: He("WebGLState: MultiplyBlending requires material.premultipliedAlpha = true"); break; default: He("WebGLState: Invalid blending: ", P); break; } y = null, _ = null, A = null, T = null, R.set(0, 0, 0), I = 0, m = P, b = rt; } return; } Q = Q || ae, J = J || ie, ve = ve || le, (ae !== p || Q !== E) && (r.blendEquationSeparate($e[ae], $e[Q]), p = ae, E = Q), (ie !== y || le !== _ || J !== A || ve !== T) && (r.blendFuncSeparate(je[ie], je[le], je[J], je[ve]), y = ie, _ = le, A = J, T = ve), (Ae.equals(R) === !1 || Tt !== I) && (r.blendColor(Ae.r, Ae.g, Ae.b, Tt), R.copy(Ae), I = Tt), m = P, b = !1; } function L(P, ae) { P.side === Vt ? ue(r.CULL_FACE) : Y(r.CULL_FACE); let ie = P.side === Ft; ae && (ie = !ie), mt(ie), P.blending === Br && P.transparent === !1 ? Ve(vt) : Ve(P.blending, P.blendEquation, P.blendSrc, P.blendDst, P.blendEquationAlpha, P.blendSrcAlpha, P.blendDstAlpha, P.blendColor, P.blendAlpha, P.premultipliedAlpha), a.setFunc(P.depthFunc), a.setTest(P.depthTest), a.setMask(P.depthWrite), n.setMask(P.colorWrite); const le = P.stencilWrite; o.setTest(le), le && (o.setMask(P.stencilWriteMask), o.setFunc(P.stencilFunc, P.stencilRef, P.stencilFuncMask), o.setOp(P.stencilFail, P.stencilZFail, P.stencilZPass)), fe(P.polygonOffset, P.polygonOffsetFactor, P.polygonOffsetUnits), P.alphaToCoverage === !0 ? Y(r.SAMPLE_ALPHA_TO_COVERAGE) : ue(r.SAMPLE_ALPHA_TO_COVERAGE); } function mt(P) { S !== P && (P ? r.frontFace(r.CW) : r.frontFace(r.CCW), S = P); } function We(P) { P !== Jh ? (Y(r.CULL_FACE), P !== D && (P === nl ? r.cullFace(r.BACK) : P === $h ? r.cullFace(r.FRONT) : r.cullFace(r.FRONT_AND_BACK))) : ue(r.CULL_FACE), D = P; } function Qe(P) { P !== N && (q && r.lineWidth(P), N = P); } function fe(P, ae, ie) { P ? (Y(r.POLYGON_OFFSET_FILL), (k !== ae || H !== ie) && (r.polygonOffset(ae, ie), k = ae, H = ie)) : ue(r.POLYGON_OFFSET_FILL); } function at(P) { P ? Y(r.SCISSOR_TEST) : ue(r.SCISSOR_TEST); } function Me(P) { P === void 0 && (P = r.TEXTURE0 + j - 1), Z !== P && (r.activeTexture(P), Z = P); } function De(P, ae, ie) { ie === void 0 && (Z === null ? ie = r.TEXTURE0 + j - 1 : ie = Z); let le = se[ie]; le === void 0 && (le = { type: void 0, texture: void 0 }, se[ie] = le), (le.type !== P || le.texture !== ae) && (Z !== ie && (r.activeTexture(ie), Z = ie), r.bindTexture(P, ae || W[P]), le.type = P, le.texture = ae); } function C() { const P = se[Z]; P !== void 0 && P.type !== void 0 && (r.bindTexture(P.type, null), P.type = void 0, P.texture = void 0); } function x() { try { r.compressedTexImage2D(...arguments); } catch (P) { P("WebGLState:", P); } } function B() { try { r.compressedTexImage3D(...arguments); } catch (P) { P("WebGLState:", P); } } function X() { try { r.texSubImage2D(...arguments); } catch (P) { P("WebGLState:", P); } } function K() { try { r.texSubImage3D(...arguments); } catch (P) { P("WebGLState:", P); } } function V() { try { r.compressedTexSubImage2D(...arguments); } catch (P) { P("WebGLState:", P); } } function xe() { try { r.compressedTexSubImage3D(...arguments); } catch (P) { P("WebGLState:", P); } } function ne() { try { r.texStorage2D(...arguments); } catch (P) { P("WebGLState:", P); } } function Te() { try { r.texStorage3D(...arguments); } catch (P) { P("WebGLState:", P); } } function de() { try { r.texImage2D(...arguments); } catch (P) { P("WebGLState:", P); } } function $() { try { r.texImage3D(...arguments); } catch (P) { P("WebGLState:", P); } } function re(P) { qe.equals(P) === !1 && (r.scissor(P.x, P.y, P.z, P.w), qe.copy(P)); } function Oe(P) { Ke.equals(P) === !1 && (r.viewport(P.x, P.y, P.z, P.w), Ke.copy(P)); } function we(P, ae) { let ie = c.get(ae); ie === void 0 && (ie = /* @__PURE__ */ new WeakMap(), c.set(ae, ie)); let le = ie.get(P); le === void 0 && (le = r.getUniformBlockIndex(ae, P.name), ie.set(P, le)); } function he(P, ae) { const ie = c.get(ae).get(P); l.get(ae) !== ie && (r.uniformBlockBinding(ae, ie, P.__bindingPointIndex), l.set(ae, ie)); } function Re() { r.disable(r.BLEND), r.disable(r.CULL_FACE), r.disable(r.DEPTH_TEST), r.disable(r.POLYGON_OFFSET_FILL), r.disable(r.SCISSOR_TEST), r.disable(r.STENCIL_TEST), r.disable(r.SAMPLE_ALPHA_TO_COVERAGE), r.blendEquation(r.FUNC_ADD), r.blendFunc(r.ONE, r.ZERO), r.blendFuncSeparate(r.ONE, r.ZERO, r.ONE, r.ZERO), r.blendColor(0, 0, 0, 0), r.colorMask(!0, !0, !0, !0), r.clearColor(0, 0, 0, 0), r.depthMask(!0), r.depthFunc(r.LESS), a.setReversed(!1), r.clearDepth(1), r.stencilMask(4294967295), r.stencilFunc(r.ALWAYS, 0, 4294967295), r.stencilOp(r.KEEP, r.KEEP, r.KEEP), r.clearStencil(0), r.cullFace(r.BACK), r.frontFace(r.CCW), r.polygonOffset(0, 0), r.activeTexture(r.TEXTURE0), r.bindFramebuffer(r.FRAMEBUFFER, null), r.bindFramebuffer(r.DRAW_FRAMEBUFFER, null), r.bindFramebuffer(r.READ_FRAMEBUFFER, null), r.useProgram(null), r.lineWidth(1), r.scissor(0, 0, r.canvas.width, r.canvas.height), r.viewport(0, 0, r.canvas.width, r.canvas.height), h = {}, Z = null, se = {}, u = {}, d = /* @__PURE__ */ new WeakMap(), f = [], g = null, v = !1, m = null, p = null, y = null, _ = null, E = null, A = null, T = null, R = new _e(0, 0, 0), I = 0, b = !1, S = null, D = null, N = null, k = null, H = null, qe.set(0, 0, r.canvas.width, r.canvas.height), Ke.set(0, 0, r.canvas.width, r.canvas.height), n.reset(), a.reset(), o.reset(); } return { buffers: { color: n, depth: a, stencil: o }, enable: Y, disable: ue, bindFramebuffer: Ce, drawBuffers: be, useProgram: Ee, setBlending: Ve, setMaterial: L, setFlipSided: mt, setCullFace: We, setLineWidth: Qe, setPolygonOffset: fe, setScissorTest: at, activeTexture: Me, bindTexture: De, unbindTexture: C, compressedTexImage2D: x, compressedTexImage3D: B, texImage2D: de, texImage3D: $, updateUBOMapping: we, uniformBlockBinding: he, texStorage2D: ne, texStorage3D: Te, texSubImage2D: X, texSubImage3D: K, compressedTexSubImage2D: V, compressedTexSubImage3D: xe, scissor: re, viewport: Oe, reset: Re }; } function Hv(r, e, t, i, s, n, a) { const o = e.has("WEBGL_multisampled_render_to_texture") ? e.get("WEBGL_multisampled_render_to_texture") : null, l = typeof navigator > "u" ? !1 : /OculusBrowser/g.test(navigator.userAgent), c = new oe(), h = /* @__PURE__ */ new WeakMap(); let u; const d = /* @__PURE__ */ new WeakMap(); let f = !1; try { f = typeof OffscreenCanvas < "u" && new OffscreenCanvas(1, 1).getContext("2d") !== null; } catch { } function g(C, x) { return f ? ( // eslint-disable-next-line compat/compat new OffscreenCanvas(C, x) ) : ws("canvas"); } function v(C, x, B) { let X = 1; const K = De(C); if ((K.width > B || K.height > B) && (X = B / Math.max(K.width, K.height)), X < 1) if (typeof HTMLImageElement < "u" && C instanceof HTMLImageElement || typeof HTMLCanvasElement < "u" && C instanceof HTMLCanvasElement || typeof ImageBitmap < "u" && C instanceof ImageBitmap || typeof VideoFrame < "u" && C instanceof VideoFrame) { const V = Math.floor(X * K.width), xe = Math.floor(X * K.height); u === void 0 && (u = g(V, xe)); const ne = x ? g(V, xe) : u; return ne.width = V, ne.height = xe, ne.getContext("2d").drawImage(C, 0, 0, V, xe), Se("WebGLRenderer: Texture has been resized from (" + K.width + "x" + K.height + ") to (" + V + "x" + xe + ")."), ne; } else return "data" in C && Se("WebGLRenderer: Image in DataTexture is too big (" + K.width + "x" + K.height + ")."), C; return C; } function m(C) { return C.generateMipmaps; } function p(C) { r.generateMipmap(C); } function y(C) { return C.isWebGLCubeRenderTarget ? r.TEXTURE_CUBE_MAP : C.isWebGL3DRenderTarget ? r.TEXTURE_3D : C.isWebGLArrayRenderTarget || C.isCompressedArrayTexture ? r.TEXTURE_2D_ARRAY : r.TEXTURE_2D; } function _(C, x, B, X, K = !1) { if (C !== null) { if (r[C] !== void 0) return r[C]; Se("WebGLRenderer: Attempt to use non-existing WebGL internal format '" + C + "'"); } let V = x; if (x === r.RED && (B === r.FLOAT && (V = r.R32F), B === r.HALF_FLOAT && (V = r.R16F), B === r.UNSIGNED_BYTE && (V = r.R8)), x === r.RED_INTEGER && (B === r.UNSIGNED_BYTE && (V = r.R8UI), B === r.UNSIGNED_SHORT && (V = r.R16UI), B === r.UNSIGNED_INT && (V = r.R32UI), B === r.BYTE && (V = r.R8I), B === r.SHORT && (V = r.R16I), B === r.INT && (V = r.R32I)), x === r.RG && (B === r.FLOAT && (V = r.RG32F), B === r.HALF_FLOAT && (V = r.RG16F), B === r.UNSIGNED_BYTE && (V = r.RG8)), x === r.RG_INTEGER && (B === r.UNSIGNED_BYTE && (V = r.RG8UI), B === r.UNSIGNED_SHORT && (V = r.RG16UI), B === r.UNSIGNED_INT && (V = r.RG32UI), B === r.BYTE && (V = r.RG8I), B === r.SHORT && (V = r.RG16I), B === r.INT && (V = r.RG32I)), x === r.RGB_INTEGER && (B === r.UNSIGNED_BYTE && (V = r.RGB8UI), B === r.UNSIGNED_SHORT && (V = r.RGB16UI), B === r.UNSIGNED_INT && (V = r.RGB32UI), B === r.BYTE && (V = r.RGB8I), B === r.SHORT && (V = r.RGB16I), B === r.INT && (V = r.RGB32I)), x === r.RGBA_INTEGER && (B === r.UNSIGNED_BYTE && (V = r.RGBA8UI), B === r.UNSIGNED_SHORT && (V = r.RGBA16UI), B === r.UNSIGNED_INT && (V = r.RGBA32UI), B === r.BYTE && (V = r.RGBA8I), B === r.SHORT && (V = r.RGBA16I), B === r.INT && (V = r.RGBA32I)), x === r.RGB && (B === r.UNSIGNED_INT_5_9_9_9_REV && (V = r.RGB9_E5), B === r.UNSIGNED_INT_10F_11F_11F_REV && (V = r.R11F_G11F_B10F)), x === r.RGBA) { const xe = K ? bn : Xe.getTransfer(X); B === r.FLOAT && (V = r.RGBA32F), B === r.HALF_FLOAT && (V = r.RGBA16F), B === r.UNSIGNED_BYTE && (V = xe === et ? r.SRGB8_ALPHA8 : r.RGBA8), B === r.UNSIGNED_SHORT_4_4_4_4 && (V = r.RGBA4), B === r.UNSIGNED_SHORT_5_5_5_1 && (V = r.RGB5_A1); } return (V === r.R16F || V === r.R32F || V === r.RG16F || V === r.RG32F || V === r.RGBA16F || V === r.RGBA32F) && e.get("EXT_color_buffer_float"), V; } function E(C, x) { let B; return C ? x === null || x === pr || x === jr ? B = r.DEPTH24_STENCIL8 : x === Gt ? B = r.DEPTH32F_STENCIL8 : x === Ss && (B = r.DEPTH24_STENCIL8, Se("DepthTexture: 16 bit depth attachment is not supported with stencil. Using 24-bit attachment.")) : x === null || x === pr || x === jr ? B = r.DEPTH_COMPONENT24 : x === Gt ? B = r.DEPTH_COMPONENT32F : x === Ss && (B = r.DEPTH_COMPONENT16), B; } function A(C, x) { return m(C) === !0 || C.isFramebufferTexture && C.minFilter !== Dt && C.minFilter !== xt ? Math.log2(Math.max(x.width, x.height)) + 1 : C.mipmaps !== void 0 && C.mipmaps.length > 0 ? C.mipmaps.length : C.isCompressedTexture && Array.isArray(C.image) ? x.mipmaps.length : 1; } function T(C) { const x = C.target; x.removeEventListener("dispose", T), I(x), x.isVideoTexture && h.delete(x); } function R(C) { const x = C.target; x.removeEventListener("dispose", R), S(x); } function I(C) { const x = i.get(C); if (x.__webglInit === void 0) return; const B = C.source, X = d.get(B); if (X) { const K = X[x.__cacheKey]; K.usedTimes--, K.usedTimes === 0 && b(C), Object.keys(X).length === 0 && d.delete(B); } i.remove(C); } function b(C) { const x = i.get(C); r.deleteTexture(x.__webglTexture); const B = C.source, X = d.get(B); delete X[x.__cacheKey], a.memory.textures--; } function S(C) { const x = i.get(C); if (C.depthTexture && (C.depthTexture.dispose(), i.remove(C.depthTexture)), C.isWebGLCubeRenderTarget) for (let X = 0; X < 6; X++) { if (Array.isArray(x.__webglFramebuffer[X])) for (let K = 0; K < x.__webglFramebuffer[X].length; K++) r.deleteFramebuffer(x.__webglFramebuffer[X][K]); else r.deleteFramebuffer(x.__webglFramebuffer[X]); x.__webglDepthbuffer && r.deleteRenderbuffer(x.__webglDepthbuffer[X]); } else { if (Array.isArray(x.__webglFramebuffer)) for (let X = 0; X < x.__webglFramebuffer.length; X++) r.deleteFramebuffer(x.__webglFramebuffer[X]); else r.deleteFramebuffer(x.__webglFramebuffer); if (x.__webglDepthbuffer && r.deleteRenderbuffer(x.__webglDepthbuffer), x.__webglMultisampledFramebuffer && r.deleteFramebuffer(x.__webglMultisampledFramebuffer), x.__webglColorRenderbuffer) for (let X = 0; X < x.__webglColorRenderbuffer.length; X++) x.__webglColorRenderbuffer[X] && r.deleteRenderbuffer(x.__webglColorRenderbuffer[X]); x.__webglDepthRenderbuffer && r.deleteRenderbuffer(x.__webglDepthRenderbuffer); } const B = C.textures; for (let X = 0, K = B.length; X < K; X++) { const V = i.get(B[X]); V.__webglTexture && (r.deleteTexture(V.__webglTexture), a.memory.textures--), i.remove(B[X]); } i.remove(C); } let D = 0; function N() { D = 0; } function k() { const C = D; return C >= s.maxTextures && Se("WebGLTextures: Trying to use " + C + " texture units while this GPU supports only " + s.maxTextures), D += 1, C; } function H(C) { const x = []; return x.push(C.wrapS), x.push(C.wrapT), x.push(C.wrapR || 0), x.push(C.magFilter), x.push(C.minFilter), x.push(C.anisotropy), x.push(C.internalFormat), x.push(C.format), x.push(C.type), x.push(C.generateMipmaps), x.push(C.premultiplyAlpha), x.push(C.flipY), x.push(C.unpackAlignment), x.push(C.colorSpace), x.join(); } function j(C, x) { const B = i.get(C); if (C.isVideoTexture && at(C), C.isRenderTargetTexture === !1 && C.isExternalTexture !== !0 && C.version > 0 && B.__version !== C.version) { const X = C.image; if (X === null) Se("WebGLRenderer: Texture marked for update but no image data found."); else if (X.complete === !1) Se("WebGLRenderer: Texture marked for update but image is incomplete"); else { W(B, C, x); return; } } else C.isExternalTexture && (B.__webglTexture = C.sourceTexture ? C.sourceTexture : null); t.bindTexture(r.TEXTURE_2D, B.__webglTexture, r.TEXTURE0 + x); } function q(C, x) { const B = i.get(C); if (C.isRenderTargetTexture === !1 && C.version > 0 && B.__version !== C.version) { W(B, C, x); return; } else C.isExternalTexture && (B.__webglTexture = C.sourceTexture ? C.sourceTexture : null); t.bindTexture(r.TEXTURE_2D_ARRAY, B.__webglTexture, r.TEXTURE0 + x); } function te(C, x) { const B = i.get(C); if (C.isRenderTargetTexture === !1 && C.version > 0 && B.__version !== C.version) { W(B, C, x); return; } t.bindTexture(r.TEXTURE_3D, B.__webglTexture, r.TEXTURE0 + x); } function G(C, x) { const B = i.get(C); if (C.version > 0 && B.__version !== C.version) { Y(B, C, x); return; } t.bindTexture(r.TEXTURE_CUBE_MAP, B.__webglTexture, r.TEXTURE0 + x); } const Z = { [Ei]: r.REPEAT, [Jt]: r.CLAMP_TO_EDGE, [Sn]: r.MIRRORED_REPEAT }, se = { [Dt]: r.NEAREST, [qc]: r.NEAREST_MIPMAP_NEAREST, [gs]: r.NEAREST_MIPMAP_LINEAR, [xt]: r.LINEAR, [pn]: r.LINEAR_MIPMAP_NEAREST, [Si]: r.LINEAR_MIPMAP_LINEAR }, Pe = { [Mu]: r.NEVER, [Cu]: r.ALWAYS, [Su]: r.LESS, [ih]: r.LEQUAL, [bu]: r.EQUAL, [wu]: r.GEQUAL, [Tu]: r.GREATER, [Eu]: r.NOTEQUAL }; function ke(C, x) { if (x.type === Gt && e.has("OES_texture_float_linear") === !1 && (x.magFilter === xt || x.magFilter === pn || x.magFilter === gs || x.magFilter === Si || x.minFilter === xt || x.minFilter === pn || x.minFilter === gs || x.minFilter === Si) && Se("WebGLRenderer: Unable to use linear filtering with floating point textures. OES_texture_float_linear not supported on this device."), r.texParameteri(C, r.TEXTURE_WRAP_S, Z[x.wrapS]), r.texParameteri(C, r.TEXTURE_WRAP_T, Z[x.wrapT]), (C === r.TEXTURE_3D || C === r.TEXTURE_2D_ARRAY) && r.texParameteri(C, r.TEXTURE_WRAP_R, Z[x.wrapR]), r.texParameteri(C, r.TEXTURE_MAG_FILTER, se[x.magFilter]), r.texParameteri(C, r.TEXTURE_MIN_FILTER, se[x.minFilter]), x.compareFunction && (r.texParameteri(C, r.TEXTURE_COMPARE_MODE, r.COMPARE_REF_TO_TEXTURE), r.texParameteri(C, r.TEXTURE_COMPARE_FUNC, Pe[x.compareFunction])), e.has("EXT_texture_filter_anisotropic") === !0) { if (x.magFilter === Dt || x.minFilter !== gs && x.minFilter !== Si || x.type === Gt && e.has("OES_texture_float_linear") === !1) return; if (x.anisotropy > 1 || i.get(x).__currentAnisotropy) { const B = e.get("EXT_texture_filter_anisotropic"); r.texParameterf(C, B.TEXTURE_MAX_ANISOTROPY_EXT, Math.min(x.anisotropy, s.getMaxAnisotropy())), i.get(x).__currentAnisotropy = x.anisotropy; } } } function qe(C, x) { let B = !1; C.__webglInit === void 0 && (C.__webglInit = !0, x.addEventListener("dispose", T)); const X = x.source; let K = d.get(X); K === void 0 && (K = {}, d.set(X, K)); const V = H(x); if (V !== C.__cacheKey) { K[V] === void 0 && (K[V] = { texture: r.createTexture(), usedTimes: 0 }, a.memory.textures++, B = !0), K[V].usedTimes++; const xe = K[C.__cacheKey]; xe !== void 0 && (K[C.__cacheKey].usedTimes--, xe.usedTimes === 0 && b(x)), C.__cacheKey = V, C.__webglTexture = K[V].texture; } return B; } function Ke(C, x, B) { return Math.floor(Math.floor(C / B) / x); } function Ze(C, x, B, X) { const K = C.updateRanges; if (K.length === 0) t.texSubImage2D(r.TEXTURE_2D, 0, 0, 0, x.width, x.height, B, X, x.data); else { K.sort((de, $) => de.start - $.start); let V = 0; for (let de = 1; de < K.length; de++) { const $ = K[V], re = K[de], Oe = $.start + $.count, we = Ke(re.start, x.width, 4), he = Ke($.start, x.width, 4); re.start <= Oe + 1 && we === he && Ke(re.start + re.count - 1, x.width, 4) === we ? $.count = Math.max( $.count, re.start + re.count - $.start ) : (++V, K[V] = re); } K.length = V + 1; const xe = r.getParameter(r.UNPACK_ROW_LENGTH), ne = r.getParameter(r.UNPACK_SKIP_PIXELS), Te = r.getParameter(r.UNPACK_SKIP_ROWS); r.pixelStorei(r.UNPACK_ROW_LENGTH, x.width); for (let de = 0, $ = K.length; de < $; de++) { const re = K[de], Oe = Math.floor(re.start / 4), we = Math.ceil(re.count / 4), he = Oe % x.width, Re = Math.floor(Oe / x.width), P = we; r.pixelStorei(r.UNPACK_SKIP_PIXELS, he), r.pixelStorei(r.UNPACK_SKIP_ROWS, Re), t.texSubImage2D(r.TEXTURE_2D, 0, he, Re, P, 1, B, X, x.data); } C.clearUpdateRanges(), r.pixelStorei(r.UNPACK_ROW_LENGTH, xe), r.pixelStorei(r.UNPACK_SKIP_PIXELS, ne), r.pixelStorei(r.UNPACK_SKIP_ROWS, Te); } } function W(C, x, B) { let X = r.TEXTURE_2D; (x.isDataArrayTexture || x.isCompressedArrayTexture) && (X = r.TEXTURE_2D_ARRAY), x.isData3DTexture && (X = r.TEXTURE_3D); const K = qe(C, x), V = x.source; t.bindTexture(X, C.__webglTexture, r.TEXTURE0 + B); const xe = i.get(V); if (V.version !== xe.__version || K === !0) { t.activeTexture(r.TEXTURE0 + B); const ne = Xe.getPrimaries(Xe.workingColorSpace), Te = x.colorSpace === Ki ? null : Xe.getPrimaries(x.colorSpace), de = x.colorSpace === Ki || ne === Te ? r.NONE : r.BROWSER_DEFAULT_WEBGL; r.pixelStorei(r.UNPACK_FLIP_Y_WEBGL, x.flipY), r.pixelStorei(r.UNPACK_PREMULTIPLY_ALPHA_WEBGL, x.premultiplyAlpha), r.pixelStorei(r.UNPACK_ALIGNMENT, x.unpackAlignment), r.pixelStorei(r.UNPACK_COLORSPACE_CONVERSION_WEBGL, de); let $ = v(x.image, !1, s.maxTextureSize); $ = Me(x, $); const re = n.convert(x.format, x.colorSpace), Oe = n.convert(x.type); let we = _(x.internalFormat, re, Oe, x.colorSpace, x.isVideoTexture); ke(X, x); let he; const Re = x.mipmaps, P = x.isVideoTexture !== !0, ae = xe.__version === void 0 || K === !0, ie = V.dataReady, le = A(x, $); if (x.isDepthTexture) we = E(x.format === Xr, x.type), ae && (P ? t.texStorage2D(r.TEXTURE_2D, 1, we, $.width, $.height) : t.texImage2D(r.TEXTURE_2D, 0, we, $.width, $.height, 0, re, Oe, null)); else if (x.isDataTexture) if (Re.length > 0) { P && ae && t.texStorage2D(r.TEXTURE_2D, le, we, Re[0].width, Re[0].height); for (let Q = 0, J = Re.length; Q < J; Q++) he = Re[Q], P ? ie && t.texSubImage2D(r.TEXTURE_2D, Q, 0, 0, he.width, he.height, re, Oe, he.data) : t.texImage2D(r.TEXTURE_2D, Q, we, he.width, he.height, 0, re, Oe, he.data); x.generateMipmaps = !1; } else P ? (ae && t.texStorage2D(r.TEXTURE_2D, le, we, $.width, $.height), ie && Ze(x, $, re, Oe)) : t.texImage2D(r.TEXTURE_2D, 0, we, $.width, $.height, 0, re, Oe, $.data); else if (x.isCompressedTexture) if (x.isCompressedArrayTexture) { P && ae && t.texStorage3D(r.TEXTURE_2D_ARRAY, le, we, Re[0].width, Re[0].height, $.depth); for (let Q = 0, J = Re.length; Q < J; Q++) if (he = Re[Q], x.format !== qt) if (re !== null) if (P) { if (ie) if (x.layerUpdates.size > 0) { const ve = Ql(he.width, he.height, x.format, x.type); for (const Ae of x.layerUpdates) { const Tt = he.data.subarray( Ae * ve / he.data.BYTES_PER_ELEMENT, (Ae + 1) * ve / he.data.BYTES_PER_ELEMENT ); t.compressedTexSubImage3D(r.TEXTURE_2D_ARRAY, Q, 0, 0, Ae, he.width, he.height, 1, re, Tt); } x.clearLayerUpdates(); } else t.compressedTexSubImage3D(r.TEXTURE_2D_ARRAY, Q, 0, 0, 0, he.width, he.height, $.depth, re, he.data); } else t.compressedTexImage3D(r.TEXTURE_2D_ARRAY, Q, we, he.width, he.height, $.depth, 0, he.data, 0, 0); else Se("WebGLRenderer: Attempt to load unsupported compressed texture format in .uploadTexture()"); else P ? ie && t.texSubImage3D(r.TEXTURE_2D_ARRAY, Q, 0, 0, 0, he.width, he.height, $.depth, re, Oe, he.data) : t.texImage3D(r.TEXTURE_2D_ARRAY, Q, we, he.width, he.height, $.depth, 0, re, Oe, he.data); } else { P && ae && t.texStorage2D(r.TEXTURE_2D, le, we, Re[0].width, Re[0].height); for (let Q = 0, J = Re.length; Q < J; Q++) he = Re[Q], x.format !== qt ? re !== null ? P ? ie && t.compressedTexSubImage2D(r.TEXTURE_2D, Q, 0, 0, he.width, he.height, re, he.data) : t.compressedTexImage2D(r.TEXTURE_2D, Q, we, he.width, he.height, 0, he.data) : Se("WebGLRenderer: Attempt to load unsupported compressed texture format in .uploadTexture()") : P ? ie && t.texSubImage2D(r.TEXTURE_2D, Q, 0, 0, he.width, he.height, re, Oe, he.data) : t.texImage2D(r.TEXTURE_2D, Q, we, he.width, he.height, 0, re, Oe, he.data); } else if (x.isDataArrayTexture) if (P) { if (ae && t.texStorage3D(r.TEXTURE_2D_ARRAY, le, we, $.width, $.height, $.depth), ie) if (x.layerUpdates.size > 0) { const Q = Ql($.width, $.height, x.format, x.type); for (const J of x.layerUpdates) { const ve = $.data.subarray( J * Q / $.data.BYTES_PER_ELEMENT, (J + 1) * Q / $.data.BYTES_PER_ELEMENT ); t.texSubImage3D(r.TEXTURE_2D_ARRAY, 0, 0, 0, J, $.width, $.height, 1, re, Oe, ve); } x.clearLayerUpdates(); } else t.texSubImage3D(r.TEXTURE_2D_ARRAY, 0, 0, 0, 0, $.width, $.height, $.depth, re, Oe, $.data); } else t.texImage3D(r.TEXTURE_2D_ARRAY, 0, we, $.width, $.height, $.depth, 0, re, Oe, $.data); else if (x.isData3DTexture) P ? (ae && t.texStorage3D(r.TEXTURE_3D, le, we, $.width, $.height, $.depth), ie && t.texSubImage3D(r.TEXTURE_3D, 0, 0, 0, 0, $.width, $.height, $.depth, re, Oe, $.data)) : t.texImage3D(r.TEXTURE_3D, 0, we, $.width, $.height, $.depth, 0, re, Oe, $.data); else if (x.isFramebufferTexture) { if (ae) if (P) t.texStorage2D(r.TEXTURE_2D, le, we, $.width, $.height); else { let Q = $.width, J = $.height; for (let ve = 0; ve < le; ve++) t.texImage2D(r.TEXTURE_2D, ve, we, Q, J, 0, re, Oe, null), Q >>= 1, J >>= 1; } } else if (Re.length > 0) { if (P && ae) { const Q = De(Re[0]); t.texStorage2D(r.TEXTURE_2D, le, we, Q.width, Q.height); } for (let Q = 0, J = Re.length; Q < J; Q++) he = Re[Q], P ? ie && t.texSubImage2D(r.TEXTURE_2D, Q, 0, 0, re, Oe, he) : t.texImage2D(r.TEXTURE_2D, Q, we, re, Oe, he); x.generateMipmaps = !1; } else if (P) { if (ae) { const Q = De($); t.texStorage2D(r.TEXTURE_2D, le, we, Q.width, Q.height); } ie && t.texSubImage2D(r.TEXTURE_2D, 0, 0, 0, re, Oe, $); } else t.texImage2D(r.TEXTURE_2D, 0, we, re, Oe, $); m(x) && p(X), xe.__version = V.version, x.onUpdate && x.onUpdate(x); } C.__version = x.version; } function Y(C, x, B) { if (x.image.length !== 6) return; const X = qe(C, x), K = x.source; t.bindTexture(r.TEXTURE_CUBE_MAP, C.__webglTexture, r.TEXTURE0 + B); const V = i.get(K); if (K.version !== V.__version || X === !0) { t.activeTexture(r.TEXTURE0 + B); const xe = Xe.getPrimaries(Xe.workingColorSpace), ne = x.colorSpace === Ki ? null : Xe.getPrimaries(x.colorSpace), Te = x.colorSpace === Ki || xe === ne ? r.NONE : r.BROWSER_DEFAULT_WEBGL; r.pixelStorei(r.UNPACK_FLIP_Y_WEBGL, x.flipY), r.pixelStorei(r.UNPACK_PREMULTIPLY_ALPHA_WEBGL, x.premultiplyAlpha), r.pixelStorei(r.UNPACK_ALIGNMENT, x.unpackAlignment), r.pixelStorei(r.UNPACK_COLORSPACE_CONVERSION_WEBGL, Te); const de = x.isCompressedTexture || x.image[0].isCompressedTexture, $ = x.image[0] && x.image[0].isDataTexture, re = []; for (let J = 0; J < 6; J++) !de && !$ ? re[J] = v(x.image[J], !0, s.maxCubemapSize) : re[J] = $ ? x.image[J].image : x.image[J], re[J] = Me(x, re[J]); const Oe = re[0], we = n.convert(x.format, x.colorSpace), he = n.convert(x.type), Re = _(x.internalFormat, we, he, x.colorSpace), P = x.isVideoTexture !== !0, ae = V.__version === void 0 || X === !0, ie = K.dataReady; let le = A(x, Oe); ke(r.TEXTURE_CUBE_MAP, x); let Q; if (de) { P && ae && t.texStorage2D(r.TEXTURE_CUBE_MAP, le, Re, Oe.width, Oe.height); for (let J = 0; J < 6; J++) { Q = re[J].mipmaps; for (let ve = 0; ve < Q.length; ve++) { const Ae = Q[ve]; x.format !== qt ? we !== null ? P ? ie && t.compressedTexSubImage2D(r.TEXTURE_CUBE_MAP_POSITIVE_X + J, ve, 0, 0, Ae.width, Ae.height, we, Ae.data) : t.compressedTexImage2D(r.TEXTURE_CUBE_MAP_POSITIVE_X + J, ve, Re, Ae.width, Ae.height, 0, Ae.data) : Se("WebGLRenderer: Attempt to load unsupported compressed texture format in .setTextureCube()") : P ? ie && t.texSubImage2D(r.TEXTURE_CUBE_MAP_POSITIVE_X + J, ve, 0, 0, Ae.width, Ae.height, we, he, Ae.data) : t.texImage2D(r.TEXTURE_CUBE_MAP_POSITIVE_X + J, ve, Re, Ae.width, Ae.height, 0, we, he, Ae.data); } } } else { if (Q = x.mipmaps, P && ae) { Q.length > 0 && le++; const J = De(re[0]); t.texStorage2D(r.TEXTURE_CUBE_MAP, le, Re, J.width, J.height); } for (let J = 0; J < 6; J++) if ($) { P ? ie && t.texSubImage2D(r.TEXTURE_CUBE_MAP_POSITIVE_X + J, 0, 0, 0, re[J].width, re[J].height, we, he, re[J].data) : t.texImage2D(r.TEXTURE_CUBE_MAP_POSITIVE_X + J, 0, Re, re[J].width, re[J].height, 0, we, he, re[J].data); for (let ve = 0; ve < Q.length; ve++) { const Ae = Q[ve].image[J].image; P ? ie && t.texSubImage2D(r.TEXTURE_CUBE_MAP_POSITIVE_X + J, ve + 1, 0, 0, Ae.width, Ae.height, we, he, Ae.data) : t.texImage2D(r.TEXTURE_CUBE_MAP_POSITIVE_X + J, ve + 1, Re, Ae.width, Ae.height, 0, we, he, Ae.data); } } else { P ? ie && t.texSubImage2D(r.TEXTURE_CUBE_MAP_POSITIVE_X + J, 0, 0, 0, we, he, re[J]) : t.texImage2D(r.TEXTURE_CUBE_MAP_POSITIVE_X + J, 0, Re, we, he, re[J]); for (let ve = 0; ve < Q.length; ve++) { const Ae = Q[ve]; P ? ie && t.texSubImage2D(r.TEXTURE_CUBE_MAP_POSITIVE_X + J, ve + 1, 0, 0, we, he, Ae.image[J]) : t.texImage2D(r.TEXTURE_CUBE_MAP_POSITIVE_X + J, ve + 1, Re, we, he, Ae.image[J]); } } } m(x) && p(r.TEXTURE_CUBE_MAP), V.__version = K.version, x.onUpdate && x.onUpdate(x); } C.__version = x.version; } function ue(C, x, B, X, K, V) { const xe = n.convert(B.format, B.colorSpace), ne = n.convert(B.type), Te = _(B.internalFormat, xe, ne, B.colorSpace), de = i.get(x), $ = i.get(B); if ($.__renderTarget = x, !de.__hasExternalTextures) { const re = Math.max(1, x.width >> V), Oe = Math.max(1, x.height >> V); K === r.TEXTURE_3D || K === r.TEXTURE_2D_ARRAY ? t.texImage3D(K, V, Te, re, Oe, x.depth, 0, xe, ne, null) : t.texImage2D(K, V, Te, re, Oe, 0, xe, ne, null); } t.bindFramebuffer(r.FRAMEBUFFER, C), fe(x) ? o.framebufferTexture2DMultisampleEXT(r.FRAMEBUFFER, X, K, $.__webglTexture, 0, Qe(x)) : (K === r.TEXTURE_2D || K >= r.TEXTURE_CUBE_MAP_POSITIVE_X && K <= r.TEXTURE_CUBE_MAP_NEGATIVE_Z) && r.framebufferTexture2D(r.FRAMEBUFFER, X, K, $.__webglTexture, V), t.bindFramebuffer(r.FRAMEBUFFER, null); } function Ce(C, x, B) { if (r.bindRenderbuffer(r.RENDERBUFFER, C), x.depthBuffer) { const X = x.depthTexture, K = X && X.isDepthTexture ? X.type : null, V = E(x.stencilBuffer, K), xe = x.stencilBuffer ? r.DEPTH_STENCIL_ATTACHMENT : r.DEPTH_ATTACHMENT, ne = Qe(x); fe(x) ? o.renderbufferStorageMultisampleEXT(r.RENDERBUFFER, ne, V, x.width, x.height) : B ? r.renderbufferStorageMultisample(r.RENDERBUFFER, ne, V, x.width, x.height) : r.renderbufferStorage(r.RENDERBUFFER, V, x.width, x.height), r.framebufferRenderbuffer(r.FRAMEBUFFER, xe, r.RENDERBUFFER, C); } else { const X = x.textures; for (let K = 0; K < X.length; K++) { const V = X[K], xe = n.convert(V.format, V.colorSpace), ne = n.convert(V.type), Te = _(V.internalFormat, xe, ne, V.colorSpace), de = Qe(x); B && fe(x) === !1 ? r.renderbufferStorageMultisample(r.RENDERBUFFER, de, Te, x.width, x.height) : fe(x) ? o.renderbufferStorageMultisampleEXT(r.RENDERBUFFER, de, Te, x.width, x.height) : r.renderbufferStorage(r.RENDERBUFFER, Te, x.width, x.height); } } r.bindRenderbuffer(r.RENDERBUFFER, null); } function be(C, x) { if (x && x.isWebGLCubeRenderTarget) throw new Error("Depth Texture with cube render targets is not supported"); if (t.bindFramebuffer(r.FRAMEBUFFER, C), !(x.depthTexture && x.depthTexture.isDepthTexture)) throw new Error("renderTarget.depthTexture must be an instance of THREE.DepthTexture"); const B = i.get(x.depthTexture); B.__renderTarget = x, (!B.__webglTexture || x.depthTexture.image.width !== x.width || x.depthTexture.image.height !== x.height) && (x.depthTexture.image.width = x.width, x.depthTexture.image.height = x.height, x.depthTexture.needsUpdate = !0), j(x.depthTexture, 0); const X = B.__webglTexture, K = Qe(x); if (x.depthTexture.format === bs) fe(x) ? o.framebufferTexture2DMultisampleEXT(r.FRAMEBUFFER, r.DEPTH_ATTACHMENT, r.TEXTURE_2D, X, 0, K) : r.framebufferTexture2D(r.FRAMEBUFFER, r.DEPTH_ATTACHMENT, r.TEXTURE_2D, X, 0); else if (x.depthTexture.format === Xr) fe(x) ? o.framebufferTexture2DMultisampleEXT(r.FRAMEBUFFER, r.DEPTH_STENCIL_ATTACHMENT, r.TEXTURE_2D, X, 0, K) : r.framebufferTexture2D(r.FRAMEBUFFER, r.DEPTH_STENCIL_ATTACHMENT, r.TEXTURE_2D, X, 0); else throw new Error("Unknown depthTexture format"); } function Ee(C) { const x = i.get(C), B = C.isWebGLCubeRenderTarget === !0; if (x.__boundDepthTexture !== C.depthTexture) { const X = C.depthTexture; if (x.__depthDisposeCallback && x.__depthDisposeCallback(), X) { const K = () => { delete x.__boundDepthTexture, delete x.__depthDisposeCallback, X.removeEventListener("dispose", K); }; X.addEventListener("dispose", K), x.__depthDisposeCallback = K; } x.__boundDepthTexture = X; } if (C.depthTexture && !x.__autoAllocateDepthBuffer) { if (B) throw new Error("target.depthTexture not supported in Cube render targets"); const X = C.texture.mipmaps; X && X.length > 0 ? be(x.__webglFramebuffer[0], C) : be(x.__webglFramebuffer, C); } else if (B) { x.__webglDepthbuffer = []; for (let X = 0; X < 6; X++) if (t.bindFramebuffer(r.FRAMEBUFFER, x.__webglFramebuffer[X]), x.__webglDepthbuffer[X] === void 0) x.__webglDepthbuffer[X] = r.createRenderbuffer(), Ce(x.__webglDepthbuffer[X], C, !1); else { const K = C.stencilBuffer ? r.DEPTH_STENCIL_ATTACHMENT : r.DEPTH_ATTACHMENT, V = x.__webglDepthbuffer[X]; r.bindRenderbuffer(r.RENDERBUFFER, V), r.framebufferRenderbuffer(r.FRAMEBUFFER, K, r.RENDERBUFFER, V); } } else { const X = C.texture.mipmaps; if (X && X.length > 0 ? t.bindFramebuffer(r.FRAMEBUFFER, x.__webglFramebuffer[0]) : t.bindFramebuffer(r.FRAMEBUFFER, x.__webglFramebuffer), x.__webglDepthbuffer === void 0) x.__webglDepthbuffer = r.createRenderbuffer(), Ce(x.__webglDepthbuffer, C, !1); else { const K = C.stencilBuffer ? r.DEPTH_STENCIL_ATTACHMENT : r.DEPTH_ATTACHMENT, V = x.__webglDepthbuffer; r.bindRenderbuffer(r.RENDERBUFFER, V), r.framebufferRenderbuffer(r.FRAMEBUFFER, K, r.RENDERBUFFER, V); } } t.bindFramebuffer(r.FRAMEBUFFER, null); } function $e(C, x, B) { const X = i.get(C); x !== void 0 && ue(X.__webglFramebuffer, C, C.texture, r.COLOR_ATTACHMENT0, r.TEXTURE_2D, 0), B !== void 0 && Ee(C); } function je(C) { const x = C.texture, B = i.get(C), X = i.get(x); C.addEventListener("dispose", R); const K = C.textures, V = C.isWebGLCubeRenderTarget === !0, xe = K.length > 1; if (xe || (X.__webglTexture === void 0 && (X.__webglTexture = r.createTexture()), X.__version = x.version, a.memory.textures++), V) { B.__webglFramebuffer = []; for (let ne = 0; ne < 6; ne++) if (x.mipmaps && x.mipmaps.length > 0) { B.__webglFramebuffer[ne] = []; for (let Te = 0; Te < x.mipmaps.length; Te++) B.__webglFramebuffer[ne][Te] = r.createFramebuffer(); } else B.__webglFramebuffer[ne] = r.createFramebuffer(); } else { if (x.mipmaps && x.mipmaps.length > 0) { B.__webglFramebuffer = []; for (let ne = 0; ne < x.mipmaps.length; ne++) B.__webglFramebuffer[ne] = r.createFramebuffer(); } else B.__webglFramebuffer = r.createFramebuffer(); if (xe) for (let ne = 0, Te = K.length; ne < Te; ne++) { const de = i.get(K[ne]); de.__webglTexture === void 0 && (de.__webglTexture = r.createTexture(), a.memory.textures++); } if (C.samples > 0 && fe(C) === !1) { B.__webglMultisampledFramebuffer = r.createFramebuffer(), B.__webglColorRenderbuffer = [], t.bindFramebuffer(r.FRAMEBUFFER, B.__webglMultisampledFramebuffer); for (let ne = 0; ne < K.length; ne++) { const Te = K[ne]; B.__webglColorRenderbuffer[ne] = r.createRenderbuffer(), r.bindRenderbuffer(r.RENDERBUFFER, B.__webglColorRenderbuffer[ne]); const de = n.convert(Te.format, Te.colorSpace), $ = n.convert(Te.type), re = _(Te.internalFormat, de, $, Te.colorSpace, C.isXRRenderTarget === !0), Oe = Qe(C); r.renderbufferStorageMultisample(r.RENDERBUFFER, Oe, re, C.width, C.height), r.framebufferRenderbuffer(r.FRAMEBUFFER, r.COLOR_ATTACHMENT0 + ne, r.RENDERBUFFER, B.__webglColorRenderbuffer[ne]); } r.bindRenderbuffer(r.RENDERBUFFER, null), C.depthBuffer && (B.__webglDepthRenderbuffer = r.createRenderbuffer(), Ce(B.__webglDepthRenderbuffer, C, !0)), t.bindFramebuffer(r.FRAMEBUFFER, null); } } if (V) { t.bindTexture(r.TEXTURE_CUBE_MAP, X.__webglTexture), ke(r.TEXTURE_CUBE_MAP, x); for (let ne = 0; ne < 6; ne++) if (x.mipmaps && x.mipmaps.length > 0) for (let Te = 0; Te < x.mipmaps.length; Te++) ue(B.__webglFramebuffer[ne][Te], C, x, r.COLOR_ATTACHMENT0, r.TEXTURE_CUBE_MAP_POSITIVE_X + ne, Te); else ue(B.__webglFramebuffer[ne], C, x, r.COLOR_ATTACHMENT0, r.TEXTURE_CUBE_MAP_POSITIVE_X + ne, 0); m(x) && p(r.TEXTURE_CUBE_MAP), t.unbindTexture(); } else if (xe) { for (let ne = 0, Te = K.length; ne < Te; ne++) { const de = K[ne], $ = i.get(de); let re = r.TEXTURE_2D; (C.isWebGL3DRenderTarget || C.isWebGLArrayRenderTarget) && (re = C.isWebGL3DRenderTarget ? r.TEXTURE_3D : r.TEXTURE_2D_ARRAY), t.bindTexture(re, $.__webglTexture), ke(re, de), ue(B.__webglFramebuffer, C, de, r.COLOR_ATTACHMENT0 + ne, re, 0), m(de) && p(re); } t.unbindTexture(); } else { let ne = r.TEXTURE_2D; if ((C.isWebGL3DRenderTarget || C.isWebGLArrayRenderTarget) && (ne = C.isWebGL3DRenderTarget ? r.TEXTURE_3D : r.TEXTURE_2D_ARRAY), t.bindTexture(ne, X.__webglTexture), ke(ne, x), x.mipmaps && x.mipmaps.length > 0) for (let Te = 0; Te < x.mipmaps.length; Te++) ue(B.__webglFramebuffer[Te], C, x, r.COLOR_ATTACHMENT0, ne, Te); else ue(B.__webglFramebuffer, C, x, r.COLOR_ATTACHMENT0, ne, 0); m(x) && p(ne), t.unbindTexture(); } C.depthBuffer && Ee(C); } function Ve(C) { const x = C.textures; for (let B = 0, X = x.length; B < X; B++) { const K = x[B]; if (m(K)) { const V = y(C), xe = i.get(K).__webglTexture; t.bindTexture(V, xe), p(V), t.unbindTexture(); } } } const L = [], mt = []; function We(C) { if (C.samples > 0) { if (fe(C) === !1) { const x = C.textures, B = C.width, X = C.height; let K = r.COLOR_BUFFER_BIT; const V = C.stencilBuffer ? r.DEPTH_STENCIL_ATTACHMENT : r.DEPTH_ATTACHMENT, xe = i.get(C), ne = x.length > 1; if (ne) for (let de = 0; de < x.length; de++) t.bindFramebuffer(r.FRAMEBUFFER, xe.__webglMultisampledFramebuffer), r.framebufferRenderbuffer(r.FRAMEBUFFER, r.COLOR_ATTACHMENT0 + de, r.RENDERBUFFER, null), t.bindFramebuffer(r.FRAMEBUFFER, xe.__webglFramebuffer), r.framebufferTexture2D(r.DRAW_FRAMEBUFFER, r.COLOR_ATTACHMENT0 + de, r.TEXTURE_2D, null, 0); t.bindFramebuffer(r.READ_FRAMEBUFFER, xe.__webglMultisampledFramebuffer); const Te = C.texture.mipmaps; Te && Te.length > 0 ? t.bindFramebuffer(r.DRAW_FRAMEBUFFER, xe.__webglFramebuffer[0]) : t.bindFramebuffer(r.DRAW_FRAMEBUFFER, xe.__webglFramebuffer); for (let de = 0; de < x.length; de++) { if (C.resolveDepthBuffer && (C.depthBuffer && (K |= r.DEPTH_BUFFER_BIT), C.stencilBuffer && C.resolveStencilBuffer && (K |= r.STENCIL_BUFFER_BIT)), ne) { r.framebufferRenderbuffer(r.READ_FRAMEBUFFER, r.COLOR_ATTACHMENT0, r.RENDERBUFFER, xe.__webglColorRenderbuffer[de]); const $ = i.get(x[de]).__webglTexture; r.framebufferTexture2D(r.DRAW_FRAMEBUFFER, r.COLOR_ATTACHMENT0, r.TEXTURE_2D, $, 0); } r.blitFramebuffer(0, 0, B, X, 0, 0, B, X, K, r.NEAREST), l === !0 && (L.length = 0, mt.length = 0, L.push(r.COLOR_ATTACHMENT0 + de), C.depthBuffer && C.resolveDepthBuffer === !1 && (L.push(V), mt.push(V), r.invalidateFramebuffer(r.DRAW_FRAMEBUFFER, mt)), r.invalidateFramebuffer(r.READ_FRAMEBUFFER, L)); } if (t.bindFramebuffer(r.READ_FRAMEBUFFER, null), t.bindFramebuffer(r.DRAW_FRAMEBUFFER, null), ne) for (let de = 0; de < x.length; de++) { t.bindFramebuffer(r.FRAMEBUFFER, xe.__webglMultisampledFramebuffer), r.framebufferRenderbuffer(r.FRAMEBUFFER, r.COLOR_ATTACHMENT0 + de, r.RENDERBUFFER, xe.__webglColorRenderbuffer[de]); const $ = i.get(x[de]).__webglTexture; t.bindFramebuffer(r.FRAMEBUFFER, xe.__webglFramebuffer), r.framebufferTexture2D(r.DRAW_FRAMEBUFFER, r.COLOR_ATTACHMENT0 + de, r.TEXTURE_2D, $, 0); } t.bindFramebuffer(r.DRAW_FRAMEBUFFER, xe.__webglMultisampledFramebuffer); } else if (C.depthBuffer && C.resolveDepthBuffer === !1 && l) { const x = C.stencilBuffer ? r.DEPTH_STENCIL_ATTACHMENT : r.DEPTH_ATTACHMENT; r.invalidateFramebuffer(r.DRAW_FRAMEBUFFER, [x]); } } } function Qe(C) { return Math.min(s.maxSamples, C.samples); } function fe(C) { const x = i.get(C); return C.samples > 0 && e.has("WEBGL_multisampled_render_to_texture") === !0 && x.__useRenderToTexture !== !1; } function at(C) { const x = a.render.frame; h.get(C) !== x && (h.set(C, x), C.update()); } function Me(C, x) { const B = C.colorSpace, X = C.format, K = C.type; return C.isCompressedTexture === !0 || C.isVideoTexture === !0 || B !== Ut && B !== Ki && (Xe.getTransfer(B) === et ? (X !== qt || K !== fi) && Se("WebGLTextures: sRGB encoded textures have to use RGBAFormat and UnsignedByteType.") : He("WebGLTextures: Unsupported texture color space:", B)), x; } function De(C) { return typeof HTMLImageElement < "u" && C instanceof HTMLImageElement ? (c.width = C.naturalWidth || C.width, c.height = C.naturalHeight || C.height) : typeof VideoFrame < "u" && C instanceof VideoFrame ? (c.width = C.displayWidth, c.height = C.displayHeight) : (c.width = C.width, c.height = C.height), c; } this.allocateTextureUnit = k, this.resetTextureUnits = N, this.setTexture2D = j, this.setTexture2DArray = q, this.setTexture3D = te, this.setTextureCube = G, this.rebindTextures = $e, this.setupRenderTarget = je, this.updateRenderTargetMipmap = Ve, this.updateMultisampleRenderTarget = We, this.setupDepthRenderbuffer = Ee, this.setupFrameBufferTexture = ue, this.useMultisampledRTT = fe; } function Vv(r, e) { function t(i, s = Ki) { let n; const a = Xe.getTransfer(s); if (i === fi) return r.UNSIGNED_BYTE; if (i === Co) return r.UNSIGNED_SHORT_4_4_4_4; if (i === Ro) return r.UNSIGNED_SHORT_5_5_5_1; if (i === Zc) return r.UNSIGNED_INT_5_9_9_9_REV; if (i === Jc) return r.UNSIGNED_INT_10F_11F_11F_REV; if (i === Yc) return r.BYTE; if (i === Kc) return r.SHORT; if (i === Ss) return r.UNSIGNED_SHORT; if (i === wo) return r.INT; if (i === pr) return r.UNSIGNED_INT; if (i === Gt) return r.FLOAT; if (i === ft) return r.HALF_FLOAT; if (i === $c) return r.ALPHA; if (i === Qc) return r.RGB; if (i === qt) return r.RGBA; if (i === bs) return r.DEPTH_COMPONENT; if (i === Xr) return r.DEPTH_STENCIL; if (i === Ao) return r.RED; if (i === Po) return r.RED_INTEGER; if (i === Do) return r.RG; if (i === Lo) return r.RG_INTEGER; if (i === Io) return r.RGBA_INTEGER; if (i === fn || i === mn || i === gn || i === vn) if (a === et) if (n = e.get("WEBGL_compressed_texture_s3tc_srgb"), n !== null) { if (i === fn) return n.COMPRESSED_SRGB_S3TC_DXT1_EXT; if (i === mn) return n.COMPRESSED_SRGB_ALPHA_S3TC_DXT1_EXT; if (i === gn) return n.COMPRESSED_SRGB_ALPHA_S3TC_DXT3_EXT; if (i === vn) return n.COMPRESSED_SRGB_ALPHA_S3TC_DXT5_EXT; } else return null; else if (n = e.get("WEBGL_compressed_texture_s3tc"), n !== null) { if (i === fn) return n.COMPRESSED_RGB_S3TC_DXT1_EXT; if (i === mn) return n.COMPRESSED_RGBA_S3TC_DXT1_EXT; if (i === gn) return n.COMPRESSED_RGBA_S3TC_DXT3_EXT; if (i === vn) return n.COMPRESSED_RGBA_S3TC_DXT5_EXT; } else return null; if (i === Oa || i === Ba || i === Fa || i === za) if (n = e.get("WEBGL_compressed_texture_pvrtc"), n !== null) { if (i === Oa) return n.COMPRESSED_RGB_PVRTC_4BPPV1_IMG; if (i === Ba) return n.COMPRESSED_RGB_PVRTC_2BPPV1_IMG; if (i === Fa) return n.COMPRESSED_RGBA_PVRTC_4BPPV1_IMG; if (i === za) return n.COMPRESSED_RGBA_PVRTC_2BPPV1_IMG; } else return null; if (i === ka || i === Ha || i === Va) if (n = e.get("WEBGL_compressed_texture_etc"), n !== null) { if (i === ka || i === Ha) return a === et ? n.COMPRESSED_SRGB8_ETC2 : n.COMPRESSED_RGB8_ETC2; if (i === Va) return a === et ? n.COMPRESSED_SRGB8_ALPHA8_ETC2_EAC : n.COMPRESSED_RGBA8_ETC2_EAC; } else return null; if (i === Ga || i === Wa || i === ja || i === Xa || i === qa || i === Ya || i === Ka || i === Za || i === Ja || i === $a || i === Qa || i === eo || i === to || i === io) if (n = e.get("WEBGL_compressed_texture_astc"), n !== null) { if (i === Ga) return a === et ? n.COMPRESSED_SRGB8_ALPHA8_ASTC_4x4_KHR : n.COMPRESSED_RGBA_ASTC_4x4_KHR; if (i === Wa) return a === et ? n.COMPRESSED_SRGB8_ALPHA8_ASTC_5x4_KHR : n.COMPRESSED_RGBA_ASTC_5x4_KHR; if (i === ja) return a === et ? n.COMPRESSED_SRGB8_ALPHA8_ASTC_5x5_KHR : n.COMPRESSED_RGBA_ASTC_5x5_KHR; if (i === Xa) return a === et ? n.COMPRESSED_SRGB8_ALPHA8_ASTC_6x5_KHR : n.COMPRESSED_RGBA_ASTC_6x5_KHR; if (i === qa) return a === et ? n.COMPRESSED_SRGB8_ALPHA8_ASTC_6x6_KHR : n.COMPRESSED_RGBA_ASTC_6x6_KHR; if (i === Ya) return a === et ? n.COMPRESSED_SRGB8_ALPHA8_ASTC_8x5_KHR : n.COMPRESSED_RGBA_ASTC_8x5_KHR; if (i === Ka) return a === et ? n.COMPRESSED_SRGB8_ALPHA8_ASTC_8x6_KHR : n.COMPRESSED_RGBA_ASTC_8x6_KHR; if (i === Za) return a === et ? n.COMPRESSED_SRGB8_ALPHA8_ASTC_8x8_KHR : n.COMPRESSED_RGBA_ASTC_8x8_KHR; if (i === Ja) return a === et ? n.COMPRESSED_SRGB8_ALPHA8_ASTC_10x5_KHR : n.COMPRESSED_RGBA_ASTC_10x5_KHR; if (i === $a) return a === et ? n.COMPRESSED_SRGB8_ALPHA8_ASTC_10x6_KHR : n.COMPRESSED_RGBA_ASTC_10x6_KHR; if (i === Qa) return a === et ? n.COMPRESSED_SRGB8_ALPHA8_ASTC_10x8_KHR : n.COMPRESSED_RGBA_ASTC_10x8_KHR; if (i === eo) return a === et ? n.COMPRESSED_SRGB8_ALPHA8_ASTC_10x10_KHR : n.COMPRESSED_RGBA_ASTC_10x10_KHR; if (i === to) return a === et ? n.COMPRESSED_SRGB8_ALPHA8_ASTC_12x10_KHR : n.COMPRESSED_RGBA_ASTC_12x10_KHR; if (i === io) return a === et ? n.COMPRESSED_SRGB8_ALPHA8_ASTC_12x12_KHR : n.COMPRESSED_RGBA_ASTC_12x12_KHR; } else return null; if (i === ro || i === so || i === no) if (n = e.get("EXT_texture_compression_bptc"), n !== null) { if (i === ro) return a === et ? n.COMPRESSED_SRGB_ALPHA_BPTC_UNORM_EXT : n.COMPRESSED_RGBA_BPTC_UNORM_EXT; if (i === so) return n.COMPRESSED_RGB_BPTC_SIGNED_FLOAT_EXT; if (i === no) return n.COMPRESSED_RGB_BPTC_UNSIGNED_FLOAT_EXT; } else return null; if (i === ao || i === oo || i === lo || i === co) if (n = e.get("EXT_texture_compression_rgtc"), n !== null) { if (i === ao) return n.COMPRESSED_RED_RGTC1_EXT; if (i === oo) return n.COMPRESSED_SIGNED_RED_RGTC1_EXT; if (i === lo) return n.COMPRESSED_RED_GREEN_RGTC2_EXT; if (i === co) return n.COMPRESSED_SIGNED_RED_GREEN_RGTC2_EXT; } else return null; return i === jr ? r.UNSIGNED_INT_24_8 : r[i] !== void 0 ? r[i] : null; } return { convert: t }; } const Gv = ` void main() { gl_Position = vec4( position, 1.0 ); }`, Wv = ` 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 jv { /** * Constructs a new depth sensing module. */ constructor() { this.texture = null, this.mesh = null, this.depthNear = 0, this.depthFar = 0; } /** * Inits the depth sensing module * * @param {XRWebGLDepthInformation} depthData - The XR depth data. * @param {XRRenderState} renderState - The XR render state. */ init(e, t) { if (this.texture === null) { const i = new ph(e.texture); (e.depthNear !== t.depthNear || e.depthFar !== t.depthFar) && (this.depthNear = e.depthNear, this.depthFar = e.depthFar), this.texture = i; } } /** * Returns a plane mesh that visualizes the depth texture. * * @param {ArrayCamera} cameraXR - The XR camera. * @return {?Mesh} The plane mesh. */ getMesh(e) { if (this.texture !== null && this.mesh === null) { const t = e.cameras[0].viewport, i = new ct({ vertexShader: Gv, fragmentShader: Wv, uniforms: { depthColor: { value: this.texture }, depthWidth: { value: t.z }, depthHeight: { value: t.w } } }); this.mesh = new nt(new Rs(20, 20), i); } return this.mesh; } /** * Resets the module */ reset() { this.texture = null, this.mesh = null; } /** * Returns a texture representing the depth of the user's environment. * * @return {?ExternalTexture} The depth texture. */ getDepthTexture() { return this.texture; } } class Xv extends gr { /** * Constructs a new WebGL renderer. * * @param {WebGLRenderer} renderer - The renderer. * @param {WebGL2RenderingContext} gl - The rendering context. */ constructor(e, t) { super(); const i = this; let s = null, n = 1, a = null, o = "local-floor", l = 1, c = null, h = null, u = null, d = null, f = null, g = null; const v = typeof XRWebGLBinding < "u", m = new jv(), p = {}, y = t.getContextAttributes(); let _ = null, E = null; const A = [], T = [], R = new oe(); let I = null; const b = new Mt(); b.viewport = new Je(); const S = new Mt(); S.viewport = new Je(); const D = [b, S], N = new Qd(); let k = null, H = null; this.cameraAutoUpdate = !0, this.enabled = !1, this.isPresenting = !1, this.getController = function(W) { let Y = A[W]; return Y === void 0 && (Y = new na(), A[W] = Y), Y.getTargetRaySpace(); }, this.getControllerGrip = function(W) { let Y = A[W]; return Y === void 0 && (Y = new na(), A[W] = Y), Y.getGripSpace(); }, this.getHand = function(W) { let Y = A[W]; return Y === void 0 && (Y = new na(), A[W] = Y), Y.getHandSpace(); }; function j(W) { const Y = T.indexOf(W.inputSource); if (Y === -1) return; const ue = A[Y]; ue !== void 0 && (ue.update(W.inputSource, W.frame, c || a), ue.dispatchEvent({ type: W.type, data: W.inputSource })); } function q() { s.removeEventListener("select", j), s.removeEventListener("selectstart", j), s.removeEventListener("selectend", j), s.removeEventListener("squeeze", j), s.removeEventListener("squeezestart", j), s.removeEventListener("squeezeend", j), s.removeEventListener("end", q), s.removeEventListener("inputsourceschange", te); for (let W = 0; W < A.length; W++) { const Y = T[W]; Y !== null && (T[W] = null, A[W].disconnect(Y)); } k = null, H = null, m.reset(); for (const W in p) delete p[W]; e.setRenderTarget(_), f = null, d = null, u = null, s = null, E = null, Ze.stop(), i.isPresenting = !1, e.setPixelRatio(I), e.setSize(R.width, R.height, !1), i.dispatchEvent({ type: "sessionend" }); } this.setFramebufferScaleFactor = function(W) { n = W, i.isPresenting === !0 && Se("WebXRManager: Cannot change framebuffer scale while presenting."); }, this.setReferenceSpaceType = function(W) { o = W, i.isPresenting === !0 && Se("WebXRManager: Cannot change reference space type while presenting."); }, this.getReferenceSpace = function() { return c || a; }, this.setReferenceSpace = function(W) { c = W; }, this.getBaseLayer = function() { return d !== null ? d : f; }, this.getBinding = function() { return u === null && v && (u = new XRWebGLBinding(s, t)), u; }, this.getFrame = function() { return g; }, this.getSession = function() { return s; }, this.setSession = async function(W) { if (s = W, s !== null) { if (_ = e.getRenderTarget(), s.addEventListener("select", j), s.addEventListener("selectstart", j), s.addEventListener("selectend", j), s.addEventListener("squeeze", j), s.addEventListener("squeezestart", j), s.addEventListener("squeezeend", j), s.addEventListener("end", q), s.addEventListener("inputsourceschange", te), y.xrCompatible !== !0 && await t.makeXRCompatible(), I = e.getPixelRatio(), e.getSize(R), v && "createProjectionLayer" in XRWebGLBinding.prototype) { let Y = null, ue = null, Ce = null; y.depth && (Ce = y.stencil ? t.DEPTH24_STENCIL8 : t.DEPTH_COMPONENT24, Y = y.stencil ? Xr : bs, ue = y.stencil ? jr : pr); const be = { colorFormat: t.RGBA8, depthFormat: Ce, scaleFactor: n }; u = this.getBinding(), d = u.createProjectionLayer(be), s.updateRenderState({ layers: [d] }), e.setPixelRatio(1), e.setSize(d.textureWidth, d.textureHeight, !1), E = new _t( d.textureWidth, d.textureHeight, { format: qt, type: fi, depthTexture: new Wo(d.textureWidth, d.textureHeight, ue, void 0, void 0, void 0, void 0, void 0, void 0, Y), stencilBuffer: y.stencil, colorSpace: e.outputColorSpace, samples: y.antialias ? 4 : 0, resolveDepthBuffer: d.ignoreDepthValues === !1, resolveStencilBuffer: d.ignoreDepthValues === !1 } ); } else { const Y = { antialias: y.antialias, alpha: !0, depth: y.depth, stencil: y.stencil, framebufferScaleFactor: n }; f = new XRWebGLLayer(s, t, Y), s.updateRenderState({ baseLayer: f }), e.setPixelRatio(1), e.setSize(f.framebufferWidth, f.framebufferHeight, !1), E = new _t( f.framebufferWidth, f.framebufferHeight, { format: qt, type: fi, colorSpace: e.outputColorSpace, stencilBuffer: y.stencil, resolveDepthBuffer: f.ignoreDepthValues === !1, resolveStencilBuffer: f.ignoreDepthValues === !1 } ); } E.isXRRenderTarget = !0, this.setFoveation(l), c = null, a = await s.requestReferenceSpace(o), Ze.setContext(s), Ze.start(), i.isPresenting = !0, i.dispatchEvent({ type: "sessionstart" }); } }, this.getEnvironmentBlendMode = function() { if (s !== null) return s.environmentBlendMode; }, this.getDepthTexture = function() { return m.getDepthTexture(); }; function te(W) { for (let Y = 0; Y < W.removed.length; Y++) { const ue = W.removed[Y], Ce = T.indexOf(ue); Ce >= 0 && (T[Ce] = null, A[Ce].disconnect(ue)); } for (let Y = 0; Y < W.added.length; Y++) { const ue = W.added[Y]; let Ce = T.indexOf(ue); if (Ce === -1) { for (let Ee = 0; Ee < A.length; Ee++) if (Ee >= T.length) { T.push(ue), Ce = Ee; break; } else if (T[Ee] === null) { T[Ee] = ue, Ce = Ee; break; } if (Ce === -1) break; } const be = A[Ce]; be && be.connect(ue); } } const G = new w(), Z = new w(); function se(W, Y, ue) { G.setFromMatrixPosition(Y.matrixWorld), Z.setFromMatrixPosition(ue.matrixWorld); const Ce = G.distanceTo(Z), be = Y.projectionMatrix.elements, Ee = ue.projectionMatrix.elements, $e = be[14] / (be[10] - 1), je = be[14] / (be[10] + 1), Ve = (be[9] + 1) / be[5], L = (be[9] - 1) / be[5], mt = (be[8] - 1) / be[0], We = (Ee[8] + 1) / Ee[0], Qe = $e * mt, fe = $e * We, at = Ce / (-mt + We), Me = at * -mt; if (Y.matrixWorld.decompose(W.position, W.quaternion, W.scale), W.translateX(Me), W.translateZ(at), W.matrixWorld.compose(W.position, W.quaternion, W.scale), W.matrixWorldInverse.copy(W.matrixWorld).invert(), be[10] === -1) W.projectionMatrix.copy(Y.projectionMatrix), W.projectionMatrixInverse.copy(Y.projectionMatrixInverse); else { const De = $e + at, C = je + at, x = Qe - Me, B = fe + (Ce - Me), X = Ve * je / C * De, K = L * je / C * De; W.projectionMatrix.makePerspective(x, B, X, K, De, C), W.projectionMatrixInverse.copy(W.projectionMatrix).invert(); } } function Pe(W, Y) { Y === null ? W.matrixWorld.copy(W.matrix) : W.matrixWorld.multiplyMatrices(Y.matrixWorld, W.matrix), W.matrixWorldInverse.copy(W.matrixWorld).invert(); } this.updateCamera = function(W) { if (s === null) return; let Y = W.near, ue = W.far; m.texture !== null && (m.depthNear > 0 && (Y = m.depthNear), m.depthFar > 0 && (ue = m.depthFar)), N.near = S.near = b.near = Y, N.far = S.far = b.far = ue, (k !== N.near || H !== N.far) && (s.updateRenderState({ depthNear: N.near, depthFar: N.far }), k = N.near, H = N.far), N.layers.mask = W.layers.mask | 6, b.layers.mask = N.layers.mask & 3, S.layers.mask = N.layers.mask & 5; const Ce = W.parent, be = N.cameras; Pe(N, Ce); for (let Ee = 0; Ee < be.length; Ee++) Pe(be[Ee], Ce); be.length === 2 ? se(N, b, S) : N.projectionMatrix.copy(b.projectionMatrix), ke(W, N, Ce); }; function ke(W, Y, ue) { ue === null ? W.matrix.copy(Y.matrixWorld) : (W.matrix.copy(ue.matrixWorld), W.matrix.invert(), W.matrix.multiply(Y.matrixWorld)), W.matrix.decompose(W.position, W.quaternion, W.scale), W.updateMatrixWorld(!0), W.projectionMatrix.copy(Y.projectionMatrix), W.projectionMatrixInverse.copy(Y.projectionMatrixInverse), W.isPerspectiveCamera && (W.fov = qr * 2 * Math.atan(1 / W.projectionMatrix.elements[5]), W.zoom = 1); } this.getCamera = function() { return N; }, this.getFoveation = function() { if (!(d === null && f === null)) return l; }, this.setFoveation = function(W) { l = W, d !== null && (d.fixedFoveation = W), f !== null && f.fixedFoveation !== void 0 && (f.fixedFoveation = W); }, this.hasDepthSensing = function() { return m.texture !== null; }, this.getDepthSensingMesh = function() { return m.getMesh(N); }, this.getCameraTexture = function(W) { return p[W]; }; let qe = null; function Ke(W, Y) { if (h = Y.getViewerPose(c || a), g = Y, h !== null) { const ue = h.views; f !== null && (e.setRenderTargetFramebuffer(E, f.framebuffer), e.setRenderTarget(E)); let Ce = !1; ue.length !== N.cameras.length && (N.cameras.length = 0, Ce = !0); for (let Ee = 0; Ee < ue.length; Ee++) { const $e = ue[Ee]; let je = null; if (f !== null) je = f.getViewport($e); else { const L = u.getViewSubImage(d, $e); je = L.viewport, Ee === 0 && (e.setRenderTargetTextures( E, L.colorTexture, L.depthStencilTexture ), e.setRenderTarget(E)); } let Ve = D[Ee]; Ve === void 0 && (Ve = new Mt(), Ve.layers.enable(Ee), Ve.viewport = new Je(), D[Ee] = Ve), Ve.matrix.fromArray($e.transform.matrix), Ve.matrix.decompose(Ve.position, Ve.quaternion, Ve.scale), Ve.projectionMatrix.fromArray($e.projectionMatrix), Ve.projectionMatrixInverse.copy(Ve.projectionMatrix).invert(), Ve.viewport.set(je.x, je.y, je.width, je.height), Ee === 0 && (N.matrix.copy(Ve.matrix), N.matrix.decompose(N.position, N.quaternion, N.scale)), Ce === !0 && N.cameras.push(Ve); } const be = s.enabledFeatures; if (be && be.includes("depth-sensing") && s.depthUsage == "gpu-optimized" && v) { u = i.getBinding(); const Ee = u.getDepthInformation(ue[0]); Ee && Ee.isValid && Ee.texture && m.init(Ee, s.renderState); } if (be && be.includes("camera-access") && v) { e.state.unbindTexture(), u = i.getBinding(); for (let Ee = 0; Ee < ue.length; Ee++) { const $e = ue[Ee].camera; if ($e) { let je = p[$e]; je || (je = new ph(), p[$e] = je); const Ve = u.getCameraImage($e); je.sourceTexture = Ve; } } } } for (let ue = 0; ue < A.length; ue++) { const Ce = T[ue], be = A[ue]; Ce !== null && be !== void 0 && be.update(Ce, Y, c || a); } qe && qe(W, Y), Y.detectedPlanes && i.dispatchEvent({ type: "planesdetected", data: Y }), g = null; } const Ze = new Sh(); Ze.setAnimationLoop(Ke), this.setAnimationLoop = function(W) { qe = W; }, this.dispose = function() { }; } } const cr = /* @__PURE__ */ new gi(), qv = /* @__PURE__ */ new Ue(); function Yv(r, e) { function t(m, p) { m.matrixAutoUpdate === !0 && m.updateMatrix(), p.value.copy(m.matrix); } function i(m, p) { p.color.getRGB(m.fogColor.value, lh(r)), p.isFog ? (m.fogNear.value = p.near, m.fogFar.value = p.far) : p.isFogExp2 && (m.fogDensity.value = p.density); } function s(m, p, y, _, E) { p.isMeshBasicMaterial || p.isMeshLambertMaterial ? n(m, p) : p.isMeshToonMaterial ? (n(m, p), u(m, p)) : p.isMeshPhongMaterial ? (n(m, p), h(m, p)) : p.isMeshStandardMaterial ? (n(m, p), d(m, p), p.isMeshPhysicalMaterial && f(m, p, E)) : p.isMeshMatcapMaterial ? (n(m, p), g(m, p)) : p.isMeshDepthMaterial ? n(m, p) : p.isMeshDistanceMaterial ? (n(m, p), v(m, p)) : p.isMeshNormalMaterial ? n(m, p) : p.isLineBasicMaterial ? (a(m, p), p.isLineDashedMaterial && o(m, p)) : p.isPointsMaterial ? l(m, p, y, _) : p.isSpriteMaterial ? c(m, p) : p.isShadowMaterial ? (m.color.value.copy(p.color), m.opacity.value = p.opacity) : p.isShaderMaterial && (p.uniformsNeedUpdate = !1); } function n(m, p) { m.opacity.value = p.opacity, p.color && m.diffuse.value.copy(p.color), p.emissive && m.emissive.value.copy(p.emissive).multiplyScalar(p.emissiveIntensity), p.map && (m.map.value = p.map, t(p.map, m.mapTransform)), p.alphaMap && (m.alphaMap.value = p.alphaMap, t(p.alphaMap, m.alphaMapTransform)), p.bumpMap && (m.bumpMap.value = p.bumpMap, t(p.bumpMap, m.bumpMapTransform), m.bumpScale.value = p.bumpScale, p.side === Ft && (m.bumpScale.value *= -1)), p.normalMap && (m.normalMap.value = p.normalMap, t(p.normalMap, m.normalMapTransform), m.normalScale.value.copy(p.normalScale), p.side === Ft && m.normalScale.value.negate()), p.displacementMap && (m.displacementMap.value = p.displacementMap, t(p.displacementMap, m.displacementMapTransform), m.displacementScale.value = p.displacementScale, m.displacementBias.value = p.displacementBias), p.emissiveMap && (m.emissiveMap.value = p.emissiveMap, t(p.emissiveMap, m.emissiveMapTransform)), p.specularMap && (m.specularMap.value = p.specularMap, t(p.specularMap, m.specularMapTransform)), p.alphaTest > 0 && (m.alphaTest.value = p.alphaTest); const y = e.get(p), _ = y.envMap, E = y.envMapRotation; _ && (m.envMap.value = _, cr.copy(E), cr.x *= -1, cr.y *= -1, cr.z *= -1, _.isCubeTexture && _.isRenderTargetTexture === !1 && (cr.y *= -1, cr.z *= -1), m.envMapRotation.value.setFromMatrix4(qv.makeRotationFromEuler(cr)), m.flipEnvMap.value = _.isCubeTexture && _.isRenderTargetTexture === !1 ? -1 : 1, m.reflectivity.value = p.reflectivity, m.ior.value = p.ior, m.refractionRatio.value = p.refractionRatio), p.lightMap && (m.lightMap.value = p.lightMap, m.lightMapIntensity.value = p.lightMapIntensity, t(p.lightMap, m.lightMapTransform)), p.aoMap && (m.aoMap.value = p.aoMap, m.aoMapIntensity.value = p.aoMapIntensity, t(p.aoMap, m.aoMapTransform)); } function a(m, p) { m.diffuse.value.copy(p.color), m.opacity.value = p.opacity, p.map && (m.map.value = p.map, t(p.map, m.mapTransform)); } function o(m, p) { m.dashSize.value = p.dashSize, m.totalSize.value = p.dashSize + p.gapSize, m.scale.value = p.scale; } function l(m, p, y, _) { m.diffuse.value.copy(p.color), m.opacity.value = p.opacity, m.size.value = p.size * y, m.scale.value = _ * 0.5, p.map && (m.map.value = p.map, t(p.map, m.uvTransform)), p.alphaMap && (m.alphaMap.value = p.alphaMap, t(p.alphaMap, m.alphaMapTransform)), p.alphaTest > 0 && (m.alphaTest.value = p.alphaTest); } function c(m, p) { m.diffuse.value.copy(p.color), m.opacity.value = p.opacity, m.rotation.value = p.rotation, p.map && (m.map.value = p.map, t(p.map, m.mapTransform)), p.alphaMap && (m.alphaMap.value = p.alphaMap, t(p.alphaMap, m.alphaMapTransform)), p.alphaTest > 0 && (m.alphaTest.value = p.alphaTest); } function h(m, p) { m.specular.value.copy(p.specular), m.shininess.value = Math.max(p.shininess, 1e-4); } function u(m, p) { p.gradientMap && (m.gradientMap.value = p.gradientMap); } function d(m, p) { m.metalness.value = p.metalness, p.metalnessMap && (m.metalnessMap.value = p.metalnessMap, t(p.metalnessMap, m.metalnessMapTransform)), m.roughness.value = p.roughness, p.roughnessMap && (m.roughnessMap.value = p.roughnessMap, t(p.roughnessMap, m.roughnessMapTransform)), p.envMap && (m.envMapIntensity.value = p.envMapIntensity); } function f(m, p, y) { m.ior.value = p.ior, p.sheen > 0 && (m.sheenColor.value.copy(p.sheenColor).multiplyScalar(p.sheen), m.sheenRoughness.value = p.sheenRoughness, p.sheenColorMap && (m.sheenColorMap.value = p.sheenColorMap, t(p.sheenColorMap, m.sheenColorMapTransform)), p.sheenRoughnessMap && (m.sheenRoughnessMap.value = p.sheenRoughnessMap, t(p.sheenRoughnessMap, m.sheenRoughnessMapTransform))), p.clearcoat > 0 && (m.clearcoat.value = p.clearcoat, m.clearcoatRoughness.value = p.clearcoatRoughness, p.clearcoatMap && (m.clearcoatMap.value = p.clearcoatMap, t(p.clearcoatMap, m.clearcoatMapTransform)), p.clearcoatRoughnessMap && (m.clearcoatRoughnessMap.value = p.clearcoatRoughnessMap, t(p.clearcoatRoughnessMap, m.clearcoatRoughnessMapTransform)), p.clearcoatNormalMap && (m.clearcoatNormalMap.value = p.clearcoatNormalMap, t(p.clearcoatNormalMap, m.clearcoatNormalMapTransform), m.clearcoatNormalScale.value.copy(p.clearcoatNormalScale), p.side === Ft && m.clearcoatNormalScale.value.negate())), p.dispersion > 0 && (m.dispersion.value = p.dispersion), p.iridescence > 0 && (m.iridescence.value = p.iridescence, m.iridescenceIOR.value = p.iridescenceIOR, m.iridescenceThicknessMinimum.value = p.iridescenceThicknessRange[0], m.iridescenceThicknessMaximum.value = p.iridescenceThicknessRange[1], p.iridescenceMap && (m.iridescenceMap.value = p.iridescenceMap, t(p.iridescenceMap, m.iridescenceMapTransform)), p.iridescenceThicknessMap && (m.iridescenceThicknessMap.value = p.iridescenceThicknessMap, t(p.iridescenceThicknessMap, m.iridescenceThicknessMapTransform))), p.transmission > 0 && (m.transmission.value = p.transmission, m.transmissionSamplerMap.value = y.texture, m.transmissionSamplerSize.value.set(y.width, y.height), p.transmissionMap && (m.transmissionMap.value = p.transmissionMap, t(p.transmissionMap, m.transmissionMapTransform)), m.thickness.value = p.thickness, p.thicknessMap && (m.thicknessMap.value = p.thicknessMap, t(p.thicknessMap, m.thicknessMapTransform)), m.attenuationDistance.value = p.attenuationDistance, m.attenuationColor.value.copy(p.attenuationColor)), p.anisotropy > 0 && (m.anisotropyVector.value.set(p.anisotropy * Math.cos(p.anisotropyRotation), p.anisotropy * Math.sin(p.anisotropyRotation)), p.anisotropyMap && (m.anisotropyMap.value = p.anisotropyMap, t(p.anisotropyMap, m.anisotropyMapTransform))), m.specularIntensity.value = p.specularIntensity, m.specularColor.value.copy(p.specularColor), p.specularColorMap && (m.specularColorMap.value = p.specularColorMap, t(p.specularColorMap, m.specularColorMapTransform)), p.specularIntensityMap && (m.specularIntensityMap.value = p.specularIntensityMap, t(p.specularIntensityMap, m.specularIntensityMapTransform)); } function g(m, p) { p.matcap && (m.matcap.value = p.matcap); } function v(m, p) { const y = e.get(p).light; m.referencePosition.value.setFromMatrixPosition(y.matrixWorld), m.nearDistance.value = y.shadow.camera.near, m.farDistance.value = y.shadow.camera.far; } return { refreshFogUniforms: i, refreshMaterialUniforms: s }; } function Kv(r, e, t, i) { let s = {}, n = {}, a = []; const o = r.getParameter(r.MAX_UNIFORM_BUFFER_BINDINGS); function l(y, _) { const E = _.program; i.uniformBlockBinding(y, E); } function c(y, _) { let E = s[y.id]; E === void 0 && (g(y), E = h(y), s[y.id] = E, y.addEventListener("dispose", m)); const A = _.program; i.updateUBOMapping(y, A); const T = e.render.frame; n[y.id] !== T && (d(y), n[y.id] = T); } function h(y) { const _ = u(); y.__bindingPointIndex = _; const E = r.createBuffer(), A = y.__size, T = y.usage; return r.bindBuffer(r.UNIFORM_BUFFER, E), r.bufferData(r.UNIFORM_BUFFER, A, T), r.bindBuffer(r.UNIFORM_BUFFER, null), r.bindBufferBase(r.UNIFORM_BUFFER, _, E), E; } function u() { for (let y = 0; y < o; y++) if (a.indexOf(y) === -1) return a.push(y), y; return He("WebGLRenderer: Maximum number of simultaneously usable uniforms groups reached."), 0; } function d(y) { const _ = s[y.id], E = y.uniforms, A = y.__cache; r.bindBuffer(r.UNIFORM_BUFFER, _); for (let T = 0, R = E.length; T < R; T++) { const I = Array.isArray(E[T]) ? E[T] : [E[T]]; for (let b = 0, S = I.length; b < S; b++) { const D = I[b]; if (f(D, T, b, A) === !0) { const N = D.__offset, k = Array.isArray(D.value) ? D.value : [D.value]; let H = 0; for (let j = 0; j < k.length; j++) { const q = k[j], te = v(q); typeof q == "number" || typeof q == "boolean" ? (D.__data[0] = q, r.bufferSubData(r.UNIFORM_BUFFER, N + H, D.__data)) : q.isMatrix3 ? (D.__data[0] = q.elements[0], D.__data[1] = q.elements[1], D.__data[2] = q.elements[2], D.__data[3] = 0, D.__data[4] = q.elements[3], D.__data[5] = q.elements[4], D.__data[6] = q.elements[5], D.__data[7] = 0, D.__data[8] = q.elements[6], D.__data[9] = q.elements[7], D.__data[10] = q.elements[8], D.__data[11] = 0) : (q.toArray(D.__data, H), H += te.storage / Float32Array.BYTES_PER_ELEMENT); } r.bufferSubData(r.UNIFORM_BUFFER, N, D.__data); } } } r.bindBuffer(r.UNIFORM_BUFFER, null); } function f(y, _, E, A) { const T = y.value, R = _ + "_" + E; if (A[R] === void 0) return typeof T == "number" || typeof T == "boolean" ? A[R] = T : A[R] = T.clone(), !0; { const I = A[R]; if (typeof T == "number" || typeof T == "boolean") { if (I !== T) return A[R] = T, !0; } else if (I.equals(T) === !1) return I.copy(T), !0; } return !1; } function g(y) { const _ = y.uniforms; let E = 0; const A = 16; for (let R = 0, I = _.length; R < I; R++) { const b = Array.isArray(_[R]) ? _[R] : [_[R]]; for (let S = 0, D = b.length; S < D; S++) { const N = b[S], k = Array.isArray(N.value) ? N.value : [N.value]; for (let H = 0, j = k.length; H < j; H++) { const q = k[H], te = v(q), G = E % A, Z = G % te.boundary, se = G + Z; E += Z, se !== 0 && A - se < te.storage && (E += A - se), N.__data = new Float32Array(te.storage / Float32Array.BYTES_PER_ELEMENT), N.__offset = E, E += te.storage; } } } const T = E % A; return T > 0 && (E += A - T), y.__size = E, y.__cache = {}, this; } function v(y) { const _ = { boundary: 0, // bytes storage: 0 // bytes }; return typeof y == "number" || typeof y == "boolean" ? (_.boundary = 4, _.storage = 4) : y.isVector2 ? (_.boundary = 8, _.storage = 8) : y.isVector3 || y.isColor ? (_.boundary = 16, _.storage = 12) : y.isVector4 ? (_.boundary = 16, _.storage = 16) : y.isMatrix3 ? (_.boundary = 48, _.storage = 48) : y.isMatrix4 ? (_.boundary = 64, _.storage = 64) : y.isTexture ? Se("WebGLRenderer: Texture samplers can not be part of an uniforms group.") : Se("WebGLRenderer: Unsupported uniform value type.", y), _; } function m(y) { const _ = y.target; _.removeEventListener("dispose", m); const E = a.indexOf(_.__bindingPointIndex); a.splice(E, 1), r.deleteBuffer(s[_.id]), delete s[_.id], delete n[_.id]; } function p() { for (const y in s) r.deleteBuffer(s[y]); a = [], s = {}, n = {}; } return { bind: l, update: c, dispose: p }; } const Zv = new Uint16Array([ 11481, 15204, 11534, 15171, 11808, 15015, 12385, 14843, 12894, 14716, 13396, 14600, 13693, 14483, 13976, 14366, 14237, 14171, 14405, 13961, 14511, 13770, 14605, 13598, 14687, 13444, 14760, 13305, 14822, 13066, 14876, 12857, 14923, 12675, 14963, 12517, 14997, 12379, 15025, 12230, 15049, 12023, 15070, 11843, 15086, 11687, 15100, 11551, 15111, 11433, 15120, 11330, 15127, 11217, 15132, 11060, 15135, 10922, 15138, 10801, 15139, 10695, 15139, 10600, 13012, 14923, 13020, 14917, 13064, 14886, 13176, 14800, 13349, 14666, 13513, 14526, 13724, 14398, 13960, 14230, 14200, 14020, 14383, 13827, 14488, 13651, 14583, 13491, 14667, 13348, 14740, 13132, 14803, 12908, 14856, 12713, 14901, 12542, 14938, 12394, 14968, 12241, 14992, 12017, 15010, 11822, 15024, 11654, 15034, 11507, 15041, 11380, 15044, 11269, 15044, 11081, 15042, 10913, 15037, 10764, 15031, 10635, 15023, 10520, 15014, 10419, 15003, 10330, 13657, 14676, 13658, 14673, 13670, 14660, 13698, 14622, 13750, 14547, 13834, 14442, 13956, 14317, 14112, 14093, 14291, 13889, 14407, 13704, 14499, 13538, 14586, 13389, 14664, 13201, 14733, 12966, 14792, 12758, 14842, 12577, 14882, 12418, 14915, 12272, 14940, 12033, 14959, 11826, 14972, 11646, 14980, 11490, 14983, 11355, 14983, 11212, 14979, 11008, 14971, 10830, 14961, 10675, 14950, 10540, 14936, 10420, 14923, 10315, 14909, 10204, 14894, 10041, 14089, 14460, 14090, 14459, 14096, 14452, 14112, 14431, 14141, 14388, 14186, 14305, 14252, 14130, 14341, 13941, 14399, 13756, 14467, 13585, 14539, 13430, 14610, 13272, 14677, 13026, 14737, 12808, 14790, 12617, 14833, 12449, 14869, 12303, 14896, 12065, 14916, 11845, 14929, 11655, 14937, 11490, 14939, 11347, 14936, 11184, 14930, 10970, 14921, 10783, 14912, 10621, 14900, 10480, 14885, 10356, 14867, 10247, 14848, 10062, 14827, 9894, 14805, 9745, 14400, 14208, 14400, 14206, 14402, 14198, 14406, 14174, 14415, 14122, 14427, 14035, 14444, 13913, 14469, 13767, 14504, 13613, 14548, 13463, 14598, 13324, 14651, 13082, 14704, 12858, 14752, 12658, 14795, 12483, 14831, 12330, 14860, 12106, 14881, 11875, 14895, 11675, 14903, 11501, 14905, 11351, 14903, 11178, 14900, 10953, 14892, 10757, 14880, 10589, 14865, 10442, 14847, 10313, 14827, 10162, 14805, 9965, 14782, 9792, 14757, 9642, 14731, 9507, 14562, 13883, 14562, 13883, 14563, 13877, 14566, 13862, 14570, 13830, 14576, 13773, 14584, 13689, 14595, 13582, 14613, 13461, 14637, 13336, 14668, 13120, 14704, 12897, 14741, 12695, 14776, 12516, 14808, 12358, 14835, 12150, 14856, 11910, 14870, 11701, 14878, 11519, 14882, 11361, 14884, 11187, 14880, 10951, 14871, 10748, 14858, 10572, 14842, 10418, 14823, 10286, 14801, 10099, 14777, 9897, 14751, 9722, 14725, 9567, 14696, 9430, 14666, 9309, 14702, 13604, 14702, 13604, 14702, 13600, 14703, 13591, 14705, 13570, 14707, 13533, 14709, 13477, 14712, 13400, 14718, 13305, 14727, 13106, 14743, 12907, 14762, 12716, 14784, 12539, 14807, 12380, 14827, 12190, 14844, 11943, 14855, 11727, 14863, 11539, 14870, 11376, 14871, 11204, 14868, 10960, 14858, 10748, 14845, 10565, 14829, 10406, 14809, 10269, 14786, 10058, 14761, 9852, 14734, 9671, 14705, 9512, 14674, 9374, 14641, 9253, 14608, 9076, 14821, 13366, 14821, 13365, 14821, 13364, 14821, 13358, 14821, 13344, 14821, 13320, 14819, 13252, 14817, 13145, 14815, 13011, 14814, 12858, 14817, 12698, 14823, 12539, 14832, 12389, 14841, 12214, 14850, 11968, 14856, 11750, 14861, 11558, 14866, 11390, 14867, 11226, 14862, 10972, 14853, 10754, 14840, 10565, 14823, 10401, 14803, 10259, 14780, 10032, 14754, 9820, 14725, 9635, 14694, 9473, 14661, 9333, 14627, 9203, 14593, 8988, 14557, 8798, 14923, 13014, 14922, 13014, 14922, 13012, 14922, 13004, 14920, 12987, 14919, 12957, 14915, 12907, 14909, 12834, 14902, 12738, 14894, 12623, 14888, 12498, 14883, 12370, 14880, 12203, 14878, 11970, 14875, 11759, 14873, 11569, 14874, 11401, 14872, 11243, 14865, 10986, 14855, 10762, 14842, 10568, 14825, 10401, 14804, 10255, 14781, 10017, 14754, 9799, 14725, 9611, 14692, 9445, 14658, 9301, 14623, 9139, 14587, 8920, 14548, 8729, 14509, 8562, 15008, 12672, 15008, 12672, 15008, 12671, 15007, 12667, 15005, 12656, 15001, 12637, 14997, 12605, 14989, 12556, 14978, 12490, 14966, 12407, 14953, 12313, 14940, 12136, 14927, 11934, 14914, 11742, 14903, 11563, 14896, 11401, 14889, 11247, 14879, 10992, 14866, 10767, 14851, 10570, 14833, 10400, 14812, 10252, 14789, 10007, 14761, 9784, 14731, 9592, 14698, 9424, 14663, 9279, 14627, 9088, 14588, 8868, 14548, 8676, 14508, 8508, 14467, 8360, 15080, 12386, 15080, 12386, 15079, 12385, 15078, 12383, 15076, 12378, 15072, 12367, 15066, 12347, 15057, 12315, 15045, 12253, 15030, 12138, 15012, 11998, 14993, 11845, 14972, 11685, 14951, 11530, 14935, 11383, 14920, 11228, 14904, 10981, 14887, 10762, 14870, 10567, 14850, 10397, 14827, 10248, 14803, 9997, 14774, 9771, 14743, 9578, 14710, 9407, 14674, 9259, 14637, 9048, 14596, 8826, 14555, 8632, 14514, 8464, 14471, 8317, 14427, 8182, 15139, 12008, 15139, 12008, 15138, 12008, 15137, 12007, 15135, 12003, 15130, 11990, 15124, 11969, 15115, 11929, 15102, 11872, 15086, 11794, 15064, 11693, 15041, 11581, 15013, 11459, 14987, 11336, 14966, 11170, 14944, 10944, 14921, 10738, 14898, 10552, 14875, 10387, 14850, 10239, 14824, 9983, 14794, 9758, 14762, 9563, 14728, 9392, 14692, 9244, 14653, 9014, 14611, 8791, 14569, 8597, 14526, 8427, 14481, 8281, 14436, 8110, 14391, 7885, 15188, 11617, 15188, 11617, 15187, 11617, 15186, 11618, 15183, 11617, 15179, 11612, 15173, 11601, 15163, 11581, 15150, 11546, 15133, 11495, 15110, 11427, 15083, 11346, 15051, 11246, 15024, 11057, 14996, 10868, 14967, 10687, 14938, 10517, 14911, 10362, 14882, 10206, 14853, 9956, 14821, 9737, 14787, 9543, 14752, 9375, 14715, 9228, 14675, 8980, 14632, 8760, 14589, 8565, 14544, 8395, 14498, 8248, 14451, 8049, 14404, 7824, 14357, 7630, 15228, 11298, 15228, 11298, 15227, 11299, 15226, 11301, 15223, 11303, 15219, 11302, 15213, 11299, 15204, 11290, 15191, 11271, 15174, 11217, 15150, 11129, 15119, 11015, 15087, 10886, 15057, 10744, 15024, 10599, 14990, 10455, 14957, 10318, 14924, 10143, 14891, 9911, 14856, 9701, 14820, 9516, 14782, 9352, 14744, 9200, 14703, 8946, 14659, 8725, 14615, 8533, 14568, 8366, 14521, 8220, 14472, 7992, 14423, 7770, 14374, 7578, 14315, 7408, 15260, 10819, 15260, 10819, 15259, 10822, 15258, 10826, 15256, 10832, 15251, 10836, 15246, 10841, 15237, 10838, 15225, 10821, 15207, 10788, 15183, 10734, 15151, 10660, 15120, 10571, 15087, 10469, 15049, 10359, 15012, 10249, 14974, 10041, 14937, 9837, 14900, 9647, 14860, 9475, 14820, 9320, 14779, 9147, 14736, 8902, 14691, 8688, 14646, 8499, 14598, 8335, 14549, 8189, 14499, 7940, 14448, 7720, 14397, 7529, 14347, 7363, 14256, 7218, 15285, 10410, 15285, 10411, 15285, 10413, 15284, 10418, 15282, 10425, 15278, 10434, 15272, 10442, 15264, 10449, 15252, 10445, 15235, 10433, 15210, 10403, 15179, 10358, 15149, 10301, 15113, 10218, 15073, 10059, 15033, 9894, 14991, 9726, 14951, 9565, 14909, 9413, 14865, 9273, 14822, 9073, 14777, 8845, 14730, 8641, 14682, 8459, 14633, 8300, 14583, 8129, 14531, 7883, 14479, 7670, 14426, 7482, 14373, 7321, 14305, 7176, 14201, 6939, 15305, 9939, 15305, 9940, 15305, 9945, 15304, 9955, 15302, 9967, 15298, 9989, 15293, 10010, 15286, 10033, 15274, 10044, 15258, 10045, 15233, 10022, 15205, 9975, 15174, 9903, 15136, 9808, 15095, 9697, 15053, 9578, 15009, 9451, 14965, 9327, 14918, 9198, 14871, 8973, 14825, 8766, 14775, 8579, 14725, 8408, 14675, 8259, 14622, 8058, 14569, 7821, 14515, 7615, 14460, 7435, 14405, 7276, 14350, 7108, 14256, 6866, 14149, 6653, 15321, 9444, 15321, 9445, 15321, 9448, 15320, 9458, 15317, 9470, 15314, 9490, 15310, 9515, 15302, 9540, 15292, 9562, 15276, 9579, 15251, 9577, 15226, 9559, 15195, 9519, 15156, 9463, 15116, 9389, 15071, 9304, 15025, 9208, 14978, 9023, 14927, 8838, 14878, 8661, 14827, 8496, 14774, 8344, 14722, 8206, 14667, 7973, 14612, 7749, 14556, 7555, 14499, 7382, 14443, 7229, 14385, 7025, 14322, 6791, 14210, 6588, 14100, 6409, 15333, 8920, 15333, 8921, 15332, 8927, 15332, 8943, 15329, 8965, 15326, 9002, 15322, 9048, 15316, 9106, 15307, 9162, 15291, 9204, 15267, 9221, 15244, 9221, 15212, 9196, 15175, 9134, 15133, 9043, 15088, 8930, 15040, 8801, 14990, 8665, 14938, 8526, 14886, 8391, 14830, 8261, 14775, 8087, 14719, 7866, 14661, 7664, 14603, 7482, 14544, 7322, 14485, 7178, 14426, 6936, 14367, 6713, 14281, 6517, 14166, 6348, 14054, 6198, 15341, 8360, 15341, 8361, 15341, 8366, 15341, 8379, 15339, 8399, 15336, 8431, 15332, 8473, 15326, 8527, 15318, 8585, 15302, 8632, 15281, 8670, 15258, 8690, 15227, 8690, 15191, 8664, 15149, 8612, 15104, 8543, 15055, 8456, 15001, 8360, 14948, 8259, 14892, 8122, 14834, 7923, 14776, 7734, 14716, 7558, 14656, 7397, 14595, 7250, 14534, 7070, 14472, 6835, 14410, 6628, 14350, 6443, 14243, 6283, 14125, 6135, 14010, 5889, 15348, 7715, 15348, 7717, 15348, 7725, 15347, 7745, 15345, 7780, 15343, 7836, 15339, 7905, 15334, 8e3, 15326, 8103, 15310, 8193, 15293, 8239, 15270, 8270, 15240, 8287, 15204, 8283, 15163, 8260, 15118, 8223, 15067, 8143, 15014, 8014, 14958, 7873, 14899, 7723, 14839, 7573, 14778, 7430, 14715, 7293, 14652, 7164, 14588, 6931, 14524, 6720, 14460, 6531, 14396, 6362, 14330, 6210, 14207, 6015, 14086, 5781, 13969, 5576, 15352, 7114, 15352, 7116, 15352, 7128, 15352, 7159, 15350, 7195, 15348, 7237, 15345, 7299, 15340, 7374, 15332, 7457, 15317, 7544, 15301, 7633, 15280, 7703, 15251, 7754, 15216, 7775, 15176, 7767, 15131, 7733, 15079, 7670, 15026, 7588, 14967, 7492, 14906, 7387, 14844, 7278, 14779, 7171, 14714, 6965, 14648, 6770, 14581, 6587, 14515, 6420, 14448, 6269, 14382, 6123, 14299, 5881, 14172, 5665, 14049, 5477, 13929, 5310, 15355, 6329, 15355, 6330, 15355, 6339, 15355, 6362, 15353, 6410, 15351, 6472, 15349, 6572, 15344, 6688, 15337, 6835, 15323, 6985, 15309, 7142, 15287, 7220, 15260, 7277, 15226, 7310, 15188, 7326, 15142, 7318, 15090, 7285, 15036, 7239, 14976, 7177, 14914, 7045, 14849, 6892, 14782, 6736, 14714, 6581, 14645, 6433, 14576, 6293, 14506, 6164, 14438, 5946, 14369, 5733, 14270, 5540, 14140, 5369, 14014, 5216, 13892, 5043, 15357, 5483, 15357, 5484, 15357, 5496, 15357, 5528, 15356, 5597, 15354, 5692, 15351, 5835, 15347, 6011, 15339, 6195, 15328, 6317, 15314, 6446, 15293, 6566, 15268, 6668, 15235, 6746, 15197, 6796, 15152, 6811, 15101, 6790, 15046, 6748, 14985, 6673, 14921, 6583, 14854, 6479, 14785, 6371, 14714, 6259, 14643, 6149, 14571, 5946, 14499, 5750, 14428, 5567, 14358, 5401, 14242, 5250, 14109, 5111, 13980, 4870, 13856, 4657, 15359, 4555, 15359, 4557, 15358, 4573, 15358, 4633, 15357, 4715, 15355, 4841, 15353, 5061, 15349, 5216, 15342, 5391, 15331, 5577, 15318, 5770, 15299, 5967, 15274, 6150, 15243, 6223, 15206, 6280, 15161, 6310, 15111, 6317, 15055, 6300, 14994, 6262, 14928, 6208, 14860, 6141, 14788, 5994, 14715, 5838, 14641, 5684, 14566, 5529, 14492, 5384, 14418, 5247, 14346, 5121, 14216, 4892, 14079, 4682, 13948, 4496, 13822, 4330, 15359, 3498, 15359, 3501, 15359, 3520, 15359, 3598, 15358, 3719, 15356, 3860, 15355, 4137, 15351, 4305, 15344, 4563, 15334, 4809, 15321, 5116, 15303, 5273, 15280, 5418, 15250, 5547, 15214, 5653, 15170, 5722, 15120, 5761, 15064, 5763, 15002, 5733, 14935, 5673, 14865, 5597, 14792, 5504, 14716, 5400, 14640, 5294, 14563, 5185, 14486, 5041, 14410, 4841, 14335, 4655, 14191, 4482, 14051, 4325, 13918, 4183, 13790, 4012, 15360, 2282, 15360, 2285, 15360, 2306, 15360, 2401, 15359, 2547, 15357, 2748, 15355, 3103, 15352, 3349, 15345, 3675, 15336, 4020, 15324, 4272, 15307, 4496, 15285, 4716, 15255, 4908, 15220, 5086, 15178, 5170, 15128, 5214, 15072, 5234, 15010, 5231, 14943, 5206, 14871, 5166, 14796, 5102, 14718, 4971, 14639, 4833, 14559, 4687, 14480, 4541, 14402, 4401, 14315, 4268, 14167, 4142, 14025, 3958, 13888, 3747, 13759, 3556, 15360, 923, 15360, 925, 15360, 946, 15360, 1052, 15359, 1214, 15357, 1494, 15356, 1892, 15352, 2274, 15346, 2663, 15338, 3099, 15326, 3393, 15309, 3679, 15288, 3980, 15260, 4183, 15226, 4325, 15185, 4437, 15136, 4517, 15080, 4570, 15018, 4591, 14950, 4581, 14877, 4545, 14800, 4485, 14720, 4411, 14638, 4325, 14556, 4231, 14475, 4136, 14395, 3988, 14297, 3803, 14145, 3628, 13999, 3465, 13861, 3314, 13729, 3177, 15360, 263, 15360, 264, 15360, 272, 15360, 325, 15359, 407, 15358, 548, 15356, 780, 15352, 1144, 15347, 1580, 15339, 2099, 15328, 2425, 15312, 2795, 15292, 3133, 15264, 3329, 15232, 3517, 15191, 3689, 15143, 3819, 15088, 3923, 15025, 3978, 14956, 3999, 14882, 3979, 14804, 3931, 14722, 3855, 14639, 3756, 14554, 3645, 14470, 3529, 14388, 3409, 14279, 3289, 14124, 3173, 13975, 3055, 13834, 2848, 13701, 2658, 15360, 49, 15360, 49, 15360, 52, 15360, 75, 15359, 111, 15358, 201, 15356, 283, 15353, 519, 15348, 726, 15340, 1045, 15329, 1415, 15314, 1795, 15295, 2173, 15269, 2410, 15237, 2649, 15197, 2866, 15150, 3054, 15095, 3140, 15032, 3196, 14963, 3228, 14888, 3236, 14808, 3224, 14725, 3191, 14639, 3146, 14553, 3088, 14466, 2976, 14382, 2836, 14262, 2692, 14103, 2549, 13952, 2409, 13808, 2278, 13674, 2154, 15360, 4, 15360, 4, 15360, 4, 15360, 13, 15359, 33, 15358, 59, 15357, 112, 15353, 199, 15348, 302, 15341, 456, 15331, 628, 15316, 827, 15297, 1082, 15272, 1332, 15241, 1601, 15202, 1851, 15156, 2069, 15101, 2172, 15039, 2256, 14970, 2314, 14894, 2348, 14813, 2358, 14728, 2344, 14640, 2311, 14551, 2263, 14463, 2203, 14376, 2133, 14247, 2059, 14084, 1915, 13930, 1761, 13784, 1609, 13648, 1464, 15360, 0, 15360, 0, 15360, 0, 15360, 3, 15359, 18, 15358, 26, 15357, 53, 15354, 80, 15348, 97, 15341, 165, 15332, 238, 15318, 326, 15299, 427, 15275, 529, 15245, 654, 15207, 771, 15161, 885, 15108, 994, 15046, 1089, 14976, 1170, 14900, 1229, 14817, 1266, 14731, 1284, 14641, 1282, 14550, 1260, 14460, 1223, 14370, 1174, 14232, 1116, 14066, 1050, 13909, 981, 13761, 910, 13623, 839 ]); let Oi = null; function Jv() { return Oi === null && (Oi = new es(Zv, 32, 32, Do, ft), Oi.minFilter = xt, Oi.magFilter = xt, Oi.wrapS = Jt, Oi.wrapT = Jt, Oi.generateMipmaps = !1, Oi.needsUpdate = !0), Oi; } class Rn { /** * Constructs a new WebGL renderer. * * @param {WebGLRenderer~Options} [parameters] - The configuration parameter. */ constructor(e = {}) { const { canvas: t = Ru(), context: i = null, depth: s = !0, stencil: n = !1, alpha: a = !1, antialias: o = !1, premultipliedAlpha: l = !0, preserveDrawingBuffer: c = !1, powerPreference: h = "default", failIfMajorPerformanceCaveat: u = !1, reversedDepthBuffer: d = !1 } = e; this.isWebGLRenderer = !0; let f; if (i !== null) { if (typeof WebGLRenderingContext < "u" && i instanceof WebGLRenderingContext) throw new Error("THREE.WebGLRenderer: WebGL 1 is not supported since r163."); f = i.getContextAttributes().alpha; } else f = a; const g = /* @__PURE__ */ new Set([ Io, Lo, Po ]), v = /* @__PURE__ */ new Set([ fi, pr, Ss, jr, Co, Ro ]), m = new Uint32Array(4), p = new Int32Array(4); let y = null, _ = null; const E = [], A = []; this.domElement = t, this.debug = { /** * Enables error checking and reporting when shader programs are being compiled. * @type {boolean} */ checkShaderErrors: !0, /** * Callback for custom error reporting. * @type {?Function} */ onShaderError: null }, this.autoClear = !0, this.autoClearColor = !0, this.autoClearDepth = !0, this.autoClearStencil = !0, this.sortObjects = !0, this.clippingPlanes = [], this.localClippingEnabled = !1, this.toneMapping = $i, this.toneMappingExposure = 1, this.transmissionResolutionScale = 1; const T = this; let R = !1; this._outputColorSpace = wt; let I = 0, b = 0, S = null, D = -1, N = null; const k = new Je(), H = new Je(); let j = null; const q = new _e(0); let te = 0, G = t.width, Z = t.height, se = 1, Pe = null, ke = null; const qe = new Je(0, 0, G, Z), Ke = new Je(0, 0, G, Z); let Ze = !1; const W = new Vo(); let Y = !1, ue = !1; const Ce = new Ue(), be = new w(), Ee = new Je(), $e = { background: null, fog: null, environment: null, overrideMaterial: null, isScene: !0 }; let je = !1; function Ve() { return S === null ? se : 1; } let L = i; function mt(M, O) { return t.getContext(M, O); } try { const M = { alpha: !0, depth: s, stencil: n, antialias: o, premultipliedAlpha: l, preserveDrawingBuffer: c, powerPreference: h, failIfMajorPerformanceCaveat: u }; if ("setAttribute" in t && t.setAttribute("data-engine", "three.js r181"), t.addEventListener("webglcontextlost", Q, !1), t.addEventListener("webglcontextrestored", J, !1), t.addEventListener("webglcontextcreationerror", ve, !1), L === null) { const O = "webgl2"; if (L = mt(O, M), L === null) throw mt(O) ? new Error("Error creating WebGL context with your selected attributes.") : new Error("Error creating WebGL context."); } } catch (M) { throw M("WebGLRenderer: " + M.message), M; } let We, Qe, fe, at, Me, De, C, x, B, X, K, V, xe, ne, Te, de, $, re, Oe, we, he, Re, P, ae; function ie() { We = new ag(L), We.init(), Re = new Vv(L, We), Qe = new Jm(L, We, e, Re), fe = new kv(L, We), Qe.reversedDepthBuffer && d && fe.buffers.depth.setReversed(!0), at = new cg(L), Me = new Cv(), De = new Hv(L, We, fe, Me, Qe, Re, at), C = new Qm(T), x = new ng(T), B = new dp(L), P = new Km(L, B), X = new og(L, B, at, P), K = new ug(L, X, B, at), Oe = new hg(L, Qe, De), de = new $m(Me), V = new wv(T, C, x, We, Qe, P, de), xe = new Yv(T, Me), ne = new Av(), Te = new Nv(We), re = new Ym(T, C, x, fe, K, f, l), $ = new Fv(T, K, Qe), ae = new Kv(L, at, Qe, fe), we = new Zm(L, We, at), he = new lg(L, We, at), at.programs = V.programs, T.capabilities = Qe, T.extensions = We, T.properties = Me, T.renderLists = ne, T.shadowMap = $, T.state = fe, T.info = at; } ie(); const le = new Xv(T, L); this.xr = le, this.getContext = function() { return L; }, this.getContextAttributes = function() { return L.getContextAttributes(); }, this.forceContextLoss = function() { const M = We.get("WEBGL_lose_context"); M && M.loseContext(); }, this.forceContextRestore = function() { const M = We.get("WEBGL_lose_context"); M && M.restoreContext(); }, this.getPixelRatio = function() { return se; }, this.setPixelRatio = function(M) { M !== void 0 && (se = M, this.setSize(G, Z, !1)); }, this.getSize = function(M) { return M.set(G, Z); }, this.setSize = function(M, O, F = !0) { if (le.isPresenting) { Se("WebGLRenderer: Can't change size while VR device is presenting."); return; } G = M, Z = O, t.width = Math.floor(M * se), t.height = Math.floor(O * se), F === !0 && (t.style.width = M + "px", t.style.height = O + "px"), this.setViewport(0, 0, M, O); }, this.getDrawingBufferSize = function(M) { return M.set(G * se, Z * se).floor(); }, this.setDrawingBufferSize = function(M, O, F) { G = M, Z = O, se = F, t.width = Math.floor(M * F), t.height = Math.floor(O * F), this.setViewport(0, 0, M, O); }, this.getCurrentViewport = function(M) { return M.copy(k); }, this.getViewport = function(M) { return M.copy(qe); }, this.setViewport = function(M, O, F, z) { M.isVector4 ? qe.set(M.x, M.y, M.z, M.w) : qe.set(M, O, F, z), fe.viewport(k.copy(qe).multiplyScalar(se).round()); }, this.getScissor = function(M) { return M.copy(Ke); }, this.setScissor = function(M, O, F, z) { M.isVector4 ? Ke.set(M.x, M.y, M.z, M.w) : Ke.set(M, O, F, z), fe.scissor(H.copy(Ke).multiplyScalar(se).round()); }, this.getScissorTest = function() { return Ze; }, this.setScissorTest = function(M) { fe.setScissorTest(Ze = M); }, this.setOpaqueSort = function(M) { Pe = M; }, this.setTransparentSort = function(M) { ke = M; }, this.getClearColor = function(M) { return M.copy(re.getClearColor()); }, this.setClearColor = function() { re.setClearColor(...arguments); }, this.getClearAlpha = function() { return re.getClearAlpha(); }, this.setClearAlpha = function() { re.setClearAlpha(...arguments); }, this.clear = function(M = !0, O = !0, F = !0) { let z = 0; if (M) { let U = !1; if (S !== null) { const ee = S.texture.format; U = g.has(ee); } if (U) { const ee = S.texture.type, pe = v.has(ee), me = re.getClearColor(), ge = re.getClearAlpha(), Le = me.r, Ne = me.g, Ie = me.b; pe ? (m[0] = Le, m[1] = Ne, m[2] = Ie, m[3] = ge, L.clearBufferuiv(L.COLOR, 0, m)) : (p[0] = Le, p[1] = Ne, p[2] = Ie, p[3] = ge, L.clearBufferiv(L.COLOR, 0, p)); } else z |= L.COLOR_BUFFER_BIT; } O && (z |= L.DEPTH_BUFFER_BIT), F && (z |= L.STENCIL_BUFFER_BIT, this.state.buffers.stencil.setMask(4294967295)), L.clear(z); }, this.clearColor = function() { this.clear(!0, !1, !1); }, this.clearDepth = function() { this.clear(!1, !0, !1); }, this.clearStencil = function() { this.clear(!1, !1, !0); }, this.dispose = function() { t.removeEventListener("webglcontextlost", Q, !1), t.removeEventListener("webglcontextrestored", J, !1), t.removeEventListener("webglcontextcreationerror", ve, !1), re.dispose(), ne.dispose(), Te.dispose(), Me.dispose(), C.dispose(), x.dispose(), K.dispose(), P.dispose(), ae.dispose(), V.dispose(), le.dispose(), le.removeEventListener("sessionstart", Jo), le.removeEventListener("sessionend", $o), ir.stop(); }; function Q(M) { M.preventDefault(), En("WebGLRenderer: Context Lost."), R = !0; } function J() { En("WebGLRenderer: Context Restored."), R = !1; const M = at.autoReset, O = $.enabled, F = $.autoUpdate, z = $.needsUpdate, U = $.type; ie(), at.autoReset = M, $.enabled = O, $.autoUpdate = F, $.needsUpdate = z, $.type = U; } function ve(M) { He("WebGLRenderer: A WebGL context could not be created. Reason: ", M.statusMessage); } function Ae(M) { const O = M.target; O.removeEventListener("dispose", Ae), Tt(O); } function Tt(M) { rt(M), Me.remove(M); } function rt(M) { const O = Me.get(M).programs; O !== void 0 && (O.forEach(function(F) { V.releaseProgram(F); }), M.isShaderMaterial && V.releaseShaderCache(M)); } this.renderBufferDirect = function(M, O, F, z, U, ee) { O === null && (O = $e); const pe = U.isMesh && U.matrixWorld.determinant() < 0, me = Nh(M, O, F, z, U); fe.setMaterial(z, pe); let ge = F.index, Le = 1; if (z.wireframe === !0) { if (ge = X.getWireframeAttribute(F), ge === void 0) return; Le = 2; } const Ne = F.drawRange, Ie = F.attributes.position; let Ye = Ne.start * Le, ot = (Ne.start + Ne.count) * Le; ee !== null && (Ye = Math.max(Ye, ee.start * Le), ot = Math.min(ot, (ee.start + ee.count) * Le)), ge !== null ? (Ye = Math.max(Ye, 0), ot = Math.min(ot, ge.count)) : Ie != null && (Ye = Math.max(Ye, 0), ot = Math.min(ot, Ie.count)); const pt = ot - Ye; if (pt < 0 || pt === 1 / 0) return; P.setup(U, z, me, F, ge); let ht, lt = we; if (ge !== null && (ht = B.get(ge), lt = he, lt.setIndex(ht)), U.isMesh) z.wireframe === !0 ? (fe.setLineWidth(z.wireframeLinewidth * Ve()), lt.setMode(L.LINES)) : lt.setMode(L.TRIANGLES); else if (U.isLine) { let ye = z.linewidth; ye === void 0 && (ye = 1), fe.setLineWidth(ye * Ve()), U.isLineSegments ? lt.setMode(L.LINES) : U.isLineLoop ? lt.setMode(L.LINE_LOOP) : lt.setMode(L.LINE_STRIP); } else U.isPoints ? lt.setMode(L.POINTS) : U.isSprite && lt.setMode(L.TRIANGLES); if (U.isBatchedMesh) if (U._multiDrawInstances !== null) Cs("WebGLRenderer: renderMultiDrawInstances has been deprecated and will be removed in r184. Append to renderMultiDraw arguments and use indirection."), lt.renderMultiDrawInstances(U._multiDrawStarts, U._multiDrawCounts, U._multiDrawCount, U._multiDrawInstances); else if (We.get("WEBGL_multi_draw")) lt.renderMultiDraw(U._multiDrawStarts, U._multiDrawCounts, U._multiDrawCount); else { const ye = U._multiDrawStarts, At = U._multiDrawCounts, Ai = U._multiDrawCount, ti = ge ? B.get(ge).bytesPerElement : 1, vr = Me.get(z).currentProgram.getUniforms(); for (let Wt = 0; Wt < Ai; Wt++) vr.setValue(L, "_gl_DrawID", Wt), lt.render(ye[Wt] / ti, At[Wt]); } else if (U.isInstancedMesh) lt.renderInstances(Ye, pt, U.count); else if (F.isInstancedBufferGeometry) { const ye = F._maxInstanceCount !== void 0 ? F._maxInstanceCount : 1 / 0, At = Math.min(F.instanceCount, ye); lt.renderInstances(Ye, pt, At); } else lt.render(Ye, pt); }; function _i(M, O, F) { M.transparent === !0 && M.side === Vt && M.forceSinglePass === !1 ? (M.side = Ft, M.needsUpdate = !0, Is(M, O, F), M.side = Ti, M.needsUpdate = !0, Is(M, O, F), M.side = Vt) : Is(M, O, F); } this.compile = function(M, O, F = null) { F === null && (F = M), _ = Te.get(F), _.init(O), A.push(_), F.traverseVisible(function(U) { U.isLight && U.layers.test(O.layers) && (_.pushLight(U), U.castShadow && _.pushShadow(U)); }), M !== F && M.traverseVisible(function(U) { U.isLight && U.layers.test(O.layers) && (_.pushLight(U), U.castShadow && _.pushShadow(U)); }), _.setupLights(); const z = /* @__PURE__ */ new Set(); return M.traverse(function(U) { if (!(U.isMesh || U.isPoints || U.isLine || U.isSprite)) return; const ee = U.material; if (ee) if (Array.isArray(ee)) for (let pe = 0; pe < ee.length; pe++) { const me = ee[pe]; _i(me, F, U), z.add(me); } else _i(ee, F, U), z.add(ee); }), _ = A.pop(), z; }, this.compileAsync = function(M, O, F = null) { const z = this.compile(M, O, F); return new Promise((U) => { function ee() { if (z.forEach(function(pe) { Me.get(pe).currentProgram.isReady() && z.delete(pe); }), z.size === 0) { U(M); return; } setTimeout(ee, 10); } We.get("KHR_parallel_shader_compile") !== null ? ee() : setTimeout(ee, 10); }); }; let ei = null; function Uh(M) { ei && ei(M); } function Jo() { ir.stop(); } function $o() { ir.start(); } const ir = new Sh(); ir.setAnimationLoop(Uh), typeof self < "u" && ir.setContext(self), this.setAnimationLoop = function(M) { ei = M, le.setAnimationLoop(M), M === null ? ir.stop() : ir.start(); }, le.addEventListener("sessionstart", Jo), le.addEventListener("sessionend", $o), this.render = function(M, O) { if (O !== void 0 && O.isCamera !== !0) { He("WebGLRenderer.render: camera is not an instance of THREE.Camera."); return; } if (R === !0) return; if (M.matrixWorldAutoUpdate === !0 && M.updateMatrixWorld(), O.parent === null && O.matrixWorldAutoUpdate === !0 && O.updateMatrixWorld(), le.enabled === !0 && le.isPresenting === !0 && (le.cameraAutoUpdate === !0 && le.updateCamera(O), O = le.getCamera()), M.isScene === !0 && M.onBeforeRender(T, M, O, S), _ = Te.get(M, A.length), _.init(O), A.push(_), Ce.multiplyMatrices(O.projectionMatrix, O.matrixWorldInverse), W.setFromProjectionMatrix(Ce, bi, O.reversedDepth), ue = this.localClippingEnabled, Y = de.init(this.clippingPlanes, ue), y = ne.get(M, E.length), y.init(), E.push(y), le.enabled === !0 && le.isPresenting === !0) { const ee = T.xr.getDepthSensingMesh(); ee !== null && Un(ee, O, -1 / 0, T.sortObjects); } Un(M, O, 0, T.sortObjects), y.finish(), T.sortObjects === !0 && y.sort(Pe, ke), je = le.enabled === !1 || le.isPresenting === !1 || le.hasDepthSensing() === !1, je && re.addToRenderList(y, M), this.info.render.frame++, Y === !0 && de.beginShadows(); const F = _.state.shadowsArray; $.render(F, M, O), Y === !0 && de.endShadows(), this.info.autoReset === !0 && this.info.reset(); const z = y.opaque, U = y.transmissive; if (_.setupLights(), O.isArrayCamera) { const ee = O.cameras; if (U.length > 0) for (let pe = 0, me = ee.length; pe < me; pe++) { const ge = ee[pe]; el(z, U, M, ge); } je && re.render(M); for (let pe = 0, me = ee.length; pe < me; pe++) { const ge = ee[pe]; Qo(y, M, ge, ge.viewport); } } else U.length > 0 && el(z, U, M, O), je && re.render(M), Qo(y, M, O); S !== null && b === 0 && (De.updateMultisampleRenderTarget(S), De.updateRenderTargetMipmap(S)), M.isScene === !0 && M.onAfterRender(T, M, O), P.resetDefaultState(), D = -1, N = null, A.pop(), A.length > 0 ? (_ = A[A.length - 1], Y === !0 && de.setGlobalState(T.clippingPlanes, _.state.camera)) : _ = null, E.pop(), E.length > 0 ? y = E[E.length - 1] : y = null; }; function Un(M, O, F, z) { if (M.visible === !1) return; if (M.layers.test(O.layers)) { if (M.isGroup) F = M.renderOrder; else if (M.isLOD) M.autoUpdate === !0 && M.update(O); else if (M.isLight) _.pushLight(M), M.castShadow && _.pushShadow(M); else if (M.isSprite) { if (!M.frustumCulled || W.intersectsSprite(M)) { z && Ee.setFromMatrixPosition(M.matrixWorld).applyMatrix4(Ce); const ee = K.update(M), pe = M.material; pe.visible && y.push(M, ee, pe, F, Ee.z, null); } } else if ((M.isMesh || M.isLine || M.isPoints) && (!M.frustumCulled || W.intersectsObject(M))) { const ee = K.update(M), pe = M.material; if (z && (M.boundingSphere !== void 0 ? (M.boundingSphere === null && M.computeBoundingSphere(), Ee.copy(M.boundingSphere.center)) : (ee.boundingSphere === null && ee.computeBoundingSphere(), Ee.copy(ee.boundingSphere.center)), Ee.applyMatrix4(M.matrixWorld).applyMatrix4(Ce)), Array.isArray(pe)) { const me = ee.groups; for (let ge = 0, Le = me.length; ge < Le; ge++) { const Ne = me[ge], Ie = pe[Ne.materialIndex]; Ie && Ie.visible && y.push(M, ee, Ie, F, Ee.z, Ne); } } else pe.visible && y.push(M, ee, pe, F, Ee.z, null); } } const U = M.children; for (let ee = 0, pe = U.length; ee < pe; ee++) Un(U[ee], O, F, z); } function Qo(M, O, F, z) { const { opaque: U, transmissive: ee, transparent: pe } = M; _.setupLightsView(F), Y === !0 && de.setGlobalState(T.clippingPlanes, F), z && fe.viewport(k.copy(z)), U.length > 0 && Ls(U, O, F), ee.length > 0 && Ls(ee, O, F), pe.length > 0 && Ls(pe, O, F), fe.buffers.depth.setTest(!0), fe.buffers.depth.setMask(!0), fe.buffers.color.setMask(!0), fe.setPolygonOffset(!1); } function el(M, O, F, z) { if ((F.isScene === !0 ? F.overrideMaterial : null) !== null) return; _.state.transmissionRenderTarget[z.id] === void 0 && (_.state.transmissionRenderTarget[z.id] = new _t(1, 1, { generateMipmaps: !0, type: We.has("EXT_color_buffer_half_float") || We.has("EXT_color_buffer_float") ? ft : fi, minFilter: Si, samples: 4, stencilBuffer: n, resolveDepthBuffer: !1, resolveStencilBuffer: !1, colorSpace: Xe.workingColorSpace })); const U = _.state.transmissionRenderTarget[z.id], ee = z.viewport || k; U.setSize(ee.z * T.transmissionResolutionScale, ee.w * T.transmissionResolutionScale); const pe = T.getRenderTarget(), me = T.getActiveCubeFace(), ge = T.getActiveMipmapLevel(); T.setRenderTarget(U), T.getClearColor(q), te = T.getClearAlpha(), te < 1 && T.setClearColor(16777215, 0.5), T.clear(), je && re.render(F); const Le = T.toneMapping; T.toneMapping = $i; const Ne = z.viewport; if (z.viewport !== void 0 && (z.viewport = void 0), _.setupLightsView(z), Y === !0 && de.setGlobalState(T.clippingPlanes, z), Ls(M, F, z), De.updateMultisampleRenderTarget(U), De.updateRenderTargetMipmap(U), We.has("WEBGL_multisampled_render_to_texture") === !1) { let Ie = !1; for (let Ye = 0, ot = O.length; Ye < ot; Ye++) { const pt = O[Ye], { object: ht, geometry: lt, material: ye, group: At } = pt; if (ye.side === Vt && ht.layers.test(z.layers)) { const Ai = ye.side; ye.side = Ft, ye.needsUpdate = !0, tl(ht, F, z, lt, ye, At), ye.side = Ai, ye.needsUpdate = !0, Ie = !0; } } Ie === !0 && (De.updateMultisampleRenderTarget(U), De.updateRenderTargetMipmap(U)); } T.setRenderTarget(pe, me, ge), T.setClearColor(q, te), Ne !== void 0 && (z.viewport = Ne), T.toneMapping = Le; } function Ls(M, O, F) { const z = O.isScene === !0 ? O.overrideMaterial : null; for (let U = 0, ee = M.length; U < ee; U++) { const pe = M[U], { object: me, geometry: ge, group: Le } = pe; let Ne = pe.material; Ne.allowOverride === !0 && z !== null && (Ne = z), me.layers.test(F.layers) && tl(me, O, F, ge, Ne, Le); } } function tl(M, O, F, z, U, ee) { M.onBeforeRender(T, O, F, z, U, ee), M.modelViewMatrix.multiplyMatrices(F.matrixWorldInverse, M.matrixWorld), M.normalMatrix.getNormalMatrix(M.modelViewMatrix), U.onBeforeRender(T, O, F, z, M, ee), U.transparent === !0 && U.side === Vt && U.forceSinglePass === !1 ? (U.side = Ft, U.needsUpdate = !0, T.renderBufferDirect(F, O, z, U, M, ee), U.side = Ti, U.needsUpdate = !0, T.renderBufferDirect(F, O, z, U, M, ee), U.side = Vt) : T.renderBufferDirect(F, O, z, U, M, ee), M.onAfterRender(T, O, F, z, U, ee); } function Is(M, O, F) { O.isScene !== !0 && (O = $e); const z = Me.get(M), U = _.state.lights, ee = _.state.shadowsArray, pe = U.state.version, me = V.getParameters(M, U.state, ee, O, F), ge = V.getProgramCacheKey(me); let Le = z.programs; z.environment = M.isMeshStandardMaterial ? O.environment : null, z.fog = O.fog, z.envMap = (M.isMeshStandardMaterial ? x : C).get(M.envMap || z.environment), z.envMapRotation = z.environment !== null && M.envMap === null ? O.environmentRotation : M.envMapRotation, Le === void 0 && (M.addEventListener("dispose", Ae), Le = /* @__PURE__ */ new Map(), z.programs = Le); let Ne = Le.get(ge); if (Ne !== void 0) { if (z.currentProgram === Ne && z.lightsStateVersion === pe) return rl(M, me), Ne; } else me.uniforms = V.getUniforms(M), M.onBeforeCompile(me, T), Ne = V.acquireProgram(me, ge), Le.set(ge, Ne), z.uniforms = me.uniforms; const Ie = z.uniforms; return (!M.isShaderMaterial && !M.isRawShaderMaterial || M.clipping === !0) && (Ie.clippingPlanes = de.uniform), rl(M, me), z.needsLights = Bh(M), z.lightsStateVersion = pe, z.needsLights && (Ie.ambientLightColor.value = U.state.ambient, Ie.lightProbe.value = U.state.probe, Ie.directionalLights.value = U.state.directional, Ie.directionalLightShadows.value = U.state.directionalShadow, Ie.spotLights.value = U.state.spot, Ie.spotLightShadows.value = U.state.spotShadow, Ie.rectAreaLights.value = U.state.rectArea, Ie.ltc_1.value = U.state.rectAreaLTC1, Ie.ltc_2.value = U.state.rectAreaLTC2, Ie.pointLights.value = U.state.point, Ie.pointLightShadows.value = U.state.pointShadow, Ie.hemisphereLights.value = U.state.hemi, Ie.directionalShadowMap.value = U.state.directionalShadowMap, Ie.directionalShadowMatrix.value = U.state.directionalShadowMatrix, Ie.spotShadowMap.value = U.state.spotShadowMap, Ie.spotLightMatrix.value = U.state.spotLightMatrix, Ie.spotLightMap.value = U.state.spotLightMap, Ie.pointShadowMap.value = U.state.pointShadowMap, Ie.pointShadowMatrix.value = U.state.pointShadowMatrix), z.currentProgram = Ne, z.uniformsList = null, Ne; } function il(M) { if (M.uniformsList === null) { const O = M.currentProgram.getUniforms(); M.uniformsList = _n.seqWithValue(O.seq, M.uniforms); } return M.uniformsList; } function rl(M, O) { const F = Me.get(M); F.outputColorSpace = O.outputColorSpace, F.batching = O.batching, F.batchingColor = O.batchingColor, F.instancing = O.instancing, F.instancingColor = O.instancingColor, F.instancingMorph = O.instancingMorph, F.skinning = O.skinning, F.morphTargets = O.morphTargets, F.morphNormals = O.morphNormals, F.morphColors = O.morphColors, F.morphTargetsCount = O.morphTargetsCount, F.numClippingPlanes = O.numClippingPlanes, F.numIntersection = O.numClipIntersection, F.vertexAlphas = O.vertexAlphas, F.vertexTangents = O.vertexTangents, F.toneMapping = O.toneMapping; } function Nh(M, O, F, z, U) { O.isScene !== !0 && (O = $e), De.resetTextureUnits(); const ee = O.fog, pe = z.isMeshStandardMaterial ? O.environment : null, me = S === null ? T.outputColorSpace : S.isXRRenderTarget === !0 ? S.texture.colorSpace : Ut, ge = (z.isMeshStandardMaterial ? x : C).get(z.envMap || pe), Le = z.vertexColors === !0 && !!F.attributes.color && F.attributes.color.itemSize === 4, Ne = !!F.attributes.tangent && (!!z.normalMap || z.anisotropy > 0), Ie = !!F.morphAttributes.position, Ye = !!F.morphAttributes.normal, ot = !!F.morphAttributes.color; let pt = $i; z.toneMapped && (S === null || S.isXRRenderTarget === !0) && (pt = T.toneMapping); const ht = F.morphAttributes.position || F.morphAttributes.normal || F.morphAttributes.color, lt = ht !== void 0 ? ht.length : 0, ye = Me.get(z), At = _.state.lights; if (Y === !0 && (ue === !0 || M !== N)) { const Pt = M === N && z.id === D; de.setState(z, M, Pt); } let Ai = !1; z.version === ye.__version ? (ye.needsLights && ye.lightsStateVersion !== At.state.version || ye.outputColorSpace !== me || U.isBatchedMesh && ye.batching === !1 || !U.isBatchedMesh && ye.batching === !0 || U.isBatchedMesh && ye.batchingColor === !0 && U.colorTexture === null || U.isBatchedMesh && ye.batchingColor === !1 && U.colorTexture !== null || U.isInstancedMesh && ye.instancing === !1 || !U.isInstancedMesh && ye.instancing === !0 || U.isSkinnedMesh && ye.skinning === !1 || !U.isSkinnedMesh && ye.skinning === !0 || U.isInstancedMesh && ye.instancingColor === !0 && U.instanceColor === null || U.isInstancedMesh && ye.instancingColor === !1 && U.instanceColor !== null || U.isInstancedMesh && ye.instancingMorph === !0 && U.morphTexture === null || U.isInstancedMesh && ye.instancingMorph === !1 && U.morphTexture !== null || ye.envMap !== ge || z.fog === !0 && ye.fog !== ee || ye.numClippingPlanes !== void 0 && (ye.numClippingPlanes !== de.numPlanes || ye.numIntersection !== de.numIntersection) || ye.vertexAlphas !== Le || ye.vertexTangents !== Ne || ye.morphTargets !== Ie || ye.morphNormals !== Ye || ye.morphColors !== ot || ye.toneMapping !== pt || ye.morphTargetsCount !== lt) && (Ai = !0) : (Ai = !0, ye.__version = z.version); let ti = ye.currentProgram; Ai === !0 && (ti = Is(z, O, U)); let vr = !1, Wt = !1, ss = !1; const ut = ti.getUniforms(), kt = ye.uniforms; if (fe.useProgram(ti.program) && (vr = !0, Wt = !0, ss = !0), z.id !== D && (D = z.id, Wt = !0), vr || N !== M) { fe.buffers.depth.getReversed() && M.reversedDepth !== !0 && (M._reversedDepth = !0, M.updateProjectionMatrix()), ut.setValue(L, "projectionMatrix", M.projectionMatrix), ut.setValue(L, "viewMatrix", M.matrixWorldInverse); const Pt = ut.map.cameraPosition; Pt !== void 0 && Pt.setValue(L, be.setFromMatrixPosition(M.matrixWorld)), Qe.logarithmicDepthBuffer && ut.setValue( L, "logDepthBufFC", 2 / (Math.log(M.far + 1) / Math.LN2) ), (z.isMeshPhongMaterial || z.isMeshToonMaterial || z.isMeshLambertMaterial || z.isMeshBasicMaterial || z.isMeshStandardMaterial || z.isShaderMaterial) && ut.setValue(L, "isOrthographic", M.isOrthographicCamera === !0), N !== M && (N = M, Wt = !0, ss = !0); } if (U.isSkinnedMesh) { ut.setOptional(L, U, "bindMatrix"), ut.setOptional(L, U, "bindMatrixInverse"); const Pt = U.skeleton; Pt && (Pt.boneTexture === null && Pt.computeBoneTexture(), ut.setValue(L, "boneTexture", Pt.boneTexture, De)); } U.isBatchedMesh && (ut.setOptional(L, U, "batchingTexture"), ut.setValue(L, "batchingTexture", U._matricesTexture, De), ut.setOptional(L, U, "batchingIdTexture"), ut.setValue(L, "batchingIdTexture", U._indirectTexture, De), ut.setOptional(L, U, "batchingColorTexture"), U._colorsTexture !== null && ut.setValue(L, "batchingColorTexture", U._colorsTexture, De)); const Yt = F.morphAttributes; if ((Yt.position !== void 0 || Yt.normal !== void 0 || Yt.color !== void 0) && Oe.update(U, F, ti), (Wt || ye.receiveShadow !== U.receiveShadow) && (ye.receiveShadow = U.receiveShadow, ut.setValue(L, "receiveShadow", U.receiveShadow)), z.isMeshGouraudMaterial && z.envMap !== null && (kt.envMap.value = ge, kt.flipEnvMap.value = ge.isCubeTexture && ge.isRenderTargetTexture === !1 ? -1 : 1), z.isMeshStandardMaterial && z.envMap === null && O.environment !== null && (kt.envMapIntensity.value = O.environmentIntensity), kt.dfgLUT !== void 0 && (kt.dfgLUT.value = Jv()), Wt && (ut.setValue(L, "toneMappingExposure", T.toneMappingExposure), ye.needsLights && Oh(kt, ss), ee && z.fog === !0 && xe.refreshFogUniforms(kt, ee), xe.refreshMaterialUniforms(kt, z, se, Z, _.state.transmissionRenderTarget[M.id]), _n.upload(L, il(ye), kt, De)), z.isShaderMaterial && z.uniformsNeedUpdate === !0 && (_n.upload(L, il(ye), kt, De), z.uniformsNeedUpdate = !1), z.isSpriteMaterial && ut.setValue(L, "center", U.center), ut.setValue(L, "modelViewMatrix", U.modelViewMatrix), ut.setValue(L, "normalMatrix", U.normalMatrix), ut.setValue(L, "modelMatrix", U.matrixWorld), z.isShaderMaterial || z.isRawShaderMaterial) { const Pt = z.uniformsGroups; for (let ii = 0, Nn = Pt.length; ii < Nn; ii++) { const rr = Pt[ii]; ae.update(rr, ti), ae.bind(rr, ti); } } return ti; } function Oh(M, O) { M.ambientLightColor.needsUpdate = O, M.lightProbe.needsUpdate = O, M.directionalLights.needsUpdate = O, M.directionalLightShadows.needsUpdate = O, M.pointLights.needsUpdate = O, M.pointLightShadows.needsUpdate = O, M.spotLights.needsUpdate = O, M.spotLightShadows.needsUpdate = O, M.rectAreaLights.needsUpdate = O, M.hemisphereLights.needsUpdate = O; } function Bh(M) { return M.isMeshLambertMaterial || M.isMeshToonMaterial || M.isMeshPhongMaterial || M.isMeshStandardMaterial || M.isShadowMaterial || M.isShaderMaterial && M.lights === !0; } this.getActiveCubeFace = function() { return I; }, this.getActiveMipmapLevel = function() { return b; }, this.getRenderTarget = function() { return S; }, this.setRenderTargetTextures = function(M, O, F) { const z = Me.get(M); z.__autoAllocateDepthBuffer = M.resolveDepthBuffer === !1, z.__autoAllocateDepthBuffer === !1 && (z.__useRenderToTexture = !1), Me.get(M.texture).__webglTexture = O, Me.get(M.depthTexture).__webglTexture = z.__autoAllocateDepthBuffer ? void 0 : F, z.__hasExternalTextures = !0; }, this.setRenderTargetFramebuffer = function(M, O) { const F = Me.get(M); F.__webglFramebuffer = O, F.__useDefaultFramebuffer = O === void 0; }; const Fh = L.createFramebuffer(); this.setRenderTarget = function(M, O = 0, F = 0) { S = M, I = O, b = F; let z = !0, U = null, ee = !1, pe = !1; if (M) { const me = Me.get(M); if (me.__useDefaultFramebuffer !== void 0) fe.bindFramebuffer(L.FRAMEBUFFER, null), z = !1; else if (me.__webglFramebuffer === void 0) De.setupRenderTarget(M); else if (me.__hasExternalTextures) De.rebindTextures(M, Me.get(M.texture).__webglTexture, Me.get(M.depthTexture).__webglTexture); else if (M.depthBuffer) { const Ne = M.depthTexture; if (me.__boundDepthTexture !== Ne) { if (Ne !== null && Me.has(Ne) && (M.width !== Ne.image.width || M.height !== Ne.image.height)) throw new Error("WebGLRenderTarget: Attached DepthTexture is initialized to the incorrect size."); De.setupDepthRenderbuffer(M); } } const ge = M.texture; (ge.isData3DTexture || ge.isDataArrayTexture || ge.isCompressedArrayTexture) && (pe = !0); const Le = Me.get(M).__webglFramebuffer; M.isWebGLCubeRenderTarget ? (Array.isArray(Le[O]) ? U = Le[O][F] : U = Le[O], ee = !0) : M.samples > 0 && De.useMultisampledRTT(M) === !1 ? U = Me.get(M).__webglMultisampledFramebuffer : Array.isArray(Le) ? U = Le[F] : U = Le, k.copy(M.viewport), H.copy(M.scissor), j = M.scissorTest; } else k.copy(qe).multiplyScalar(se).floor(), H.copy(Ke).multiplyScalar(se).floor(), j = Ze; if (F !== 0 && (U = Fh), fe.bindFramebuffer(L.FRAMEBUFFER, U) && z && fe.drawBuffers(M, U), fe.viewport(k), fe.scissor(H), fe.setScissorTest(j), ee) { const me = Me.get(M.texture); L.framebufferTexture2D(L.FRAMEBUFFER, L.COLOR_ATTACHMENT0, L.TEXTURE_CUBE_MAP_POSITIVE_X + O, me.__webglTexture, F); } else if (pe) { const me = O; for (let ge = 0; ge < M.textures.length; ge++) { const Le = Me.get(M.textures[ge]); L.framebufferTextureLayer(L.FRAMEBUFFER, L.COLOR_ATTACHMENT0 + ge, Le.__webglTexture, F, me); } } else if (M !== null && F !== 0) { const me = Me.get(M.texture); L.framebufferTexture2D(L.FRAMEBUFFER, L.COLOR_ATTACHMENT0, L.TEXTURE_2D, me.__webglTexture, F); } D = -1; }, this.readRenderTargetPixels = function(M, O, F, z, U, ee, pe, me = 0) { if (!(M && M.isWebGLRenderTarget)) { He("WebGLRenderer.readRenderTargetPixels: renderTarget is not THREE.WebGLRenderTarget."); return; } let ge = Me.get(M).__webglFramebuffer; if (M.isWebGLCubeRenderTarget && pe !== void 0 && (ge = ge[pe]), ge) { fe.bindFramebuffer(L.FRAMEBUFFER, ge); try { const Le = M.textures[me], Ne = Le.format, Ie = Le.type; if (!Qe.textureFormatReadable(Ne)) { He("WebGLRenderer.readRenderTargetPixels: renderTarget is not in RGBA or implementation defined format."); return; } if (!Qe.textureTypeReadable(Ie)) { He("WebGLRenderer.readRenderTargetPixels: renderTarget is not in UnsignedByteType or implementation defined type."); return; } O >= 0 && O <= M.width - z && F >= 0 && F <= M.height - U && (M.textures.length > 1 && L.readBuffer(L.COLOR_ATTACHMENT0 + me), L.readPixels(O, F, z, U, Re.convert(Ne), Re.convert(Ie), ee)); } finally { const Le = S !== null ? Me.get(S).__webglFramebuffer : null; fe.bindFramebuffer(L.FRAMEBUFFER, Le); } } }, this.readRenderTargetPixelsAsync = async function(M, O, F, z, U, ee, pe, me = 0) { if (!(M && M.isWebGLRenderTarget)) throw new Error("THREE.WebGLRenderer.readRenderTargetPixels: renderTarget is not THREE.WebGLRenderTarget."); let ge = Me.get(M).__webglFramebuffer; if (M.isWebGLCubeRenderTarget && pe !== void 0 && (ge = ge[pe]), ge) if (O >= 0 && O <= M.width - z && F >= 0 && F <= M.height - U) { fe.bindFramebuffer(L.FRAMEBUFFER, ge); const Le = M.textures[me], Ne = Le.format, Ie = Le.type; if (!Qe.textureFormatReadable(Ne)) throw new Error("THREE.WebGLRenderer.readRenderTargetPixelsAsync: renderTarget is not in RGBA or implementation defined format."); if (!Qe.textureTypeReadable(Ie)) throw new Error("THREE.WebGLRenderer.readRenderTargetPixelsAsync: renderTarget is not in UnsignedByteType or implementation defined type."); const Ye = L.createBuffer(); L.bindBuffer(L.PIXEL_PACK_BUFFER, Ye), L.bufferData(L.PIXEL_PACK_BUFFER, ee.byteLength, L.STREAM_READ), M.textures.length > 1 && L.readBuffer(L.COLOR_ATTACHMENT0 + me), L.readPixels(O, F, z, U, Re.convert(Ne), Re.convert(Ie), 0); const ot = S !== null ? Me.get(S).__webglFramebuffer : null; fe.bindFramebuffer(L.FRAMEBUFFER, ot); const pt = L.fenceSync(L.SYNC_GPU_COMMANDS_COMPLETE, 0); return L.flush(), await Au(L, pt, 4), L.bindBuffer(L.PIXEL_PACK_BUFFER, Ye), L.getBufferSubData(L.PIXEL_PACK_BUFFER, 0, ee), L.deleteBuffer(Ye), L.deleteSync(pt), ee; } else throw new Error("THREE.WebGLRenderer.readRenderTargetPixelsAsync: requested read bounds are out of range."); }, this.copyFramebufferToTexture = function(M, O = null, F = 0) { const z = Math.pow(2, -F), U = Math.floor(M.image.width * z), ee = Math.floor(M.image.height * z), pe = O !== null ? O.x : 0, me = O !== null ? O.y : 0; De.setTexture2D(M, 0), L.copyTexSubImage2D(L.TEXTURE_2D, F, 0, 0, pe, me, U, ee), fe.unbindTexture(); }; const zh = L.createFramebuffer(), kh = L.createFramebuffer(); this.copyTextureToTexture = function(M, O, F = null, z = null, U = 0, ee = null) { ee === null && (U !== 0 ? (Cs("WebGLRenderer: copyTextureToTexture function signature has changed to support src and dst mipmap levels."), ee = U, U = 0) : ee = 0); let pe, me, ge, Le, Ne, Ie, Ye, ot, pt; const ht = M.isCompressedTexture ? M.mipmaps[ee] : M.image; if (F !== null) pe = F.max.x - F.min.x, me = F.max.y - F.min.y, ge = F.isBox3 ? F.max.z - F.min.z : 1, Le = F.min.x, Ne = F.min.y, Ie = F.isBox3 ? F.min.z : 0; else { const Yt = Math.pow(2, -U); pe = Math.floor(ht.width * Yt), me = Math.floor(ht.height * Yt), M.isDataArrayTexture ? ge = ht.depth : M.isData3DTexture ? ge = Math.floor(ht.depth * Yt) : ge = 1, Le = 0, Ne = 0, Ie = 0; } z !== null ? (Ye = z.x, ot = z.y, pt = z.z) : (Ye = 0, ot = 0, pt = 0); const lt = Re.convert(O.format), ye = Re.convert(O.type); let At; O.isData3DTexture ? (De.setTexture3D(O, 0), At = L.TEXTURE_3D) : O.isDataArrayTexture || O.isCompressedArrayTexture ? (De.setTexture2DArray(O, 0), At = L.TEXTURE_2D_ARRAY) : (De.setTexture2D(O, 0), At = L.TEXTURE_2D), L.pixelStorei(L.UNPACK_FLIP_Y_WEBGL, O.flipY), L.pixelStorei(L.UNPACK_PREMULTIPLY_ALPHA_WEBGL, O.premultiplyAlpha), L.pixelStorei(L.UNPACK_ALIGNMENT, O.unpackAlignment); const Ai = L.getParameter(L.UNPACK_ROW_LENGTH), ti = L.getParameter(L.UNPACK_IMAGE_HEIGHT), vr = L.getParameter(L.UNPACK_SKIP_PIXELS), Wt = L.getParameter(L.UNPACK_SKIP_ROWS), ss = L.getParameter(L.UNPACK_SKIP_IMAGES); L.pixelStorei(L.UNPACK_ROW_LENGTH, ht.width), L.pixelStorei(L.UNPACK_IMAGE_HEIGHT, ht.height), L.pixelStorei(L.UNPACK_SKIP_PIXELS, Le), L.pixelStorei(L.UNPACK_SKIP_ROWS, Ne), L.pixelStorei(L.UNPACK_SKIP_IMAGES, Ie); const ut = M.isDataArrayTexture || M.isData3DTexture, kt = O.isDataArrayTexture || O.isData3DTexture; if (M.isDepthTexture) { const Yt = Me.get(M), Pt = Me.get(O), ii = Me.get(Yt.__renderTarget), Nn = Me.get(Pt.__renderTarget); fe.bindFramebuffer(L.READ_FRAMEBUFFER, ii.__webglFramebuffer), fe.bindFramebuffer(L.DRAW_FRAMEBUFFER, Nn.__webglFramebuffer); for (let rr = 0; rr < ge; rr++) ut && (L.framebufferTextureLayer(L.READ_FRAMEBUFFER, L.COLOR_ATTACHMENT0, Me.get(M).__webglTexture, U, Ie + rr), L.framebufferTextureLayer(L.DRAW_FRAMEBUFFER, L.COLOR_ATTACHMENT0, Me.get(O).__webglTexture, ee, pt + rr)), L.blitFramebuffer(Le, Ne, pe, me, Ye, ot, pe, me, L.DEPTH_BUFFER_BIT, L.NEAREST); fe.bindFramebuffer(L.READ_FRAMEBUFFER, null), fe.bindFramebuffer(L.DRAW_FRAMEBUFFER, null); } else if (U !== 0 || M.isRenderTargetTexture || Me.has(M)) { const Yt = Me.get(M), Pt = Me.get(O); fe.bindFramebuffer(L.READ_FRAMEBUFFER, zh), fe.bindFramebuffer(L.DRAW_FRAMEBUFFER, kh); for (let ii = 0; ii < ge; ii++) ut ? L.framebufferTextureLayer(L.READ_FRAMEBUFFER, L.COLOR_ATTACHMENT0, Yt.__webglTexture, U, Ie + ii) : L.framebufferTexture2D(L.READ_FRAMEBUFFER, L.COLOR_ATTACHMENT0, L.TEXTURE_2D, Yt.__webglTexture, U), kt ? L.framebufferTextureLayer(L.DRAW_FRAMEBUFFER, L.COLOR_ATTACHMENT0, Pt.__webglTexture, ee, pt + ii) : L.framebufferTexture2D(L.DRAW_FRAMEBUFFER, L.COLOR_ATTACHMENT0, L.TEXTURE_2D, Pt.__webglTexture, ee), U !== 0 ? L.blitFramebuffer(Le, Ne, pe, me, Ye, ot, pe, me, L.COLOR_BUFFER_BIT, L.NEAREST) : kt ? L.copyTexSubImage3D(At, ee, Ye, ot, pt + ii, Le, Ne, pe, me) : L.copyTexSubImage2D(At, ee, Ye, ot, Le, Ne, pe, me); fe.bindFramebuffer(L.READ_FRAMEBUFFER, null), fe.bindFramebuffer(L.DRAW_FRAMEBUFFER, null); } else kt ? M.isDataTexture || M.isData3DTexture ? L.texSubImage3D(At, ee, Ye, ot, pt, pe, me, ge, lt, ye, ht.data) : O.isCompressedArrayTexture ? L.compressedTexSubImage3D(At, ee, Ye, ot, pt, pe, me, ge, lt, ht.data) : L.texSubImage3D(At, ee, Ye, ot, pt, pe, me, ge, lt, ye, ht) : M.isDataTexture ? L.texSubImage2D(L.TEXTURE_2D, ee, Ye, ot, pe, me, lt, ye, ht.data) : M.isCompressedTexture ? L.compressedTexSubImage2D(L.TEXTURE_2D, ee, Ye, ot, ht.width, ht.height, lt, ht.data) : L.texSubImage2D(L.TEXTURE_2D, ee, Ye, ot, pe, me, lt, ye, ht); L.pixelStorei(L.UNPACK_ROW_LENGTH, Ai), L.pixelStorei(L.UNPACK_IMAGE_HEIGHT, ti), L.pixelStorei(L.UNPACK_SKIP_PIXELS, vr), L.pixelStorei(L.UNPACK_SKIP_ROWS, Wt), L.pixelStorei(L.UNPACK_SKIP_IMAGES, ss), ee === 0 && O.generateMipmaps && L.generateMipmap(At), fe.unbindTexture(); }, this.initRenderTarget = function(M) { Me.get(M).__webglFramebuffer === void 0 && De.setupRenderTarget(M); }, this.initTexture = function(M) { M.isCubeTexture ? De.setTextureCube(M, 0) : M.isData3DTexture ? De.setTexture3D(M, 0) : M.isDataArrayTexture || M.isCompressedArrayTexture ? De.setTexture2DArray(M, 0) : De.setTexture2D(M, 0), fe.unbindTexture(); }, this.resetState = function() { I = 0, b = 0, S = null, fe.reset(), P.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 bi; } /** * Defines the output color space of the renderer. * * @type {SRGBColorSpace|LinearSRGBColorSpace} * @default SRGBColorSpace */ get outputColorSpace() { return this._outputColorSpace; } set outputColorSpace(e) { this._outputColorSpace = e; const t = this.getContext(); t.drawingBufferColorSpace = Xe._getDrawingBufferColorSpace(e), t.unpackColorSpace = Xe._getUnpackColorSpace(); } } class $v extends Xd { /** * Constructs a new RGBE/HDR loader. * * @param {LoadingManager} [manager] - The loading manager. */ constructor(e) { super(e), this.type = ft; } /** * Parses the given RGBE texture data. * * @param {ArrayBuffer} buffer - The raw texture data. * @return {DataTextureLoader~TexData} An object representing the parsed texture data. */ parse(e) { const t = function(m, p) { switch (m) { case 1: throw new Error("THREE.HDRLoader: Read Error: " + (p || "")); case 2: throw new Error("THREE.HDRLoader: Write Error: " + (p || "")); case 3: throw new Error("THREE.HDRLoader: Bad File Format: " + (p || "")); default: case 4: throw new Error("THREE.HDRLoader: Memory Error: " + (p || "")); } }, i = function(m, p, y) { p = p || 1024; let _ = m.pos, E = -1, A = 0, T = "", R = String.fromCharCode.apply(null, new Uint16Array(m.subarray(_, _ + 128))); for (; 0 > (E = R.indexOf(` `)) && A < p && _ < m.byteLength; ) T += R, A += R.length, _ += 128, R += String.fromCharCode.apply(null, new Uint16Array(m.subarray(_, _ + 128))); return -1 < E ? (m.pos += A + E + 1, T + R.slice(0, E)) : !1; }, s = function(m) { const p = /^#\?(\S+)/, y = /^\s*GAMMA\s*=\s*(\d+(\.\d+)?)\s*$/, _ = /^\s*EXPOSURE\s*=\s*(\d+(\.\d+)?)\s*$/, E = /^\s*FORMAT=(\S+)\s*$/, A = /^\s*\-Y\s+(\d+)\s+\+X\s+(\d+)\s*$/, T = { valid: 0, /* indicate which fields are valid */ string: "", /* the actual header string */ comments: "", /* comments found in header */ programtype: "RGBE", /* listed at beginning of file to identify it after "#?". defaults to "RGBE" */ format: "", /* RGBE format, default 32-bit_rle_rgbe */ gamma: 1, /* image has already been gamma corrected with given gamma. defaults to 1.0 (no correction) */ exposure: 1, /* a value of 1.0 in an image corresponds to watts/steradian/m^2. defaults to 1.0 */ width: 0, height: 0 /* image dimensions, width/height */ }; let R, I; for ((m.pos >= m.byteLength || !(R = i(m))) && t(1, "no header found"), (I = R.match(p)) || t(3, "bad initial token"), T.valid |= 1, T.programtype = I[1], T.string += R + ` `; R = i(m), R !== !1; ) { if (T.string += R + ` `, R.charAt(0) === "#") { T.comments += R + ` `; continue; } if ((I = R.match(y)) && (T.gamma = parseFloat(I[1])), (I = R.match(_)) && (T.exposure = parseFloat(I[1])), (I = R.match(E)) && (T.valid |= 2, T.format = I[1]), (I = R.match(A)) && (T.valid |= 4, T.height = parseInt(I[1], 10), T.width = parseInt(I[2], 10)), T.valid & 2 && T.valid & 4) break; } return T.valid & 2 || t(3, "missing format specifier"), T.valid & 4 || t(3, "missing image size specifier"), T; }, n = function(m, p, y) { const _ = p; if ( // run length encoding is not allowed so read flat _ < 8 || _ > 32767 || // this file is not run length encoded m[0] !== 2 || m[1] !== 2 || m[2] & 128 ) return new Uint8Array(m); _ !== (m[2] << 8 | m[3]) && t(3, "wrong scanline width"); const E = new Uint8Array(4 * p * y); E.length || t(4, "unable to allocate buffer space"); let A = 0, T = 0; const R = 4 * _, I = new Uint8Array(4), b = new Uint8Array(R); let S = y; for (; S > 0 && T < m.byteLength; ) { T + 4 > m.byteLength && t(1), I[0] = m[T++], I[1] = m[T++], I[2] = m[T++], I[3] = m[T++], (I[0] != 2 || I[1] != 2 || (I[2] << 8 | I[3]) != _) && t(3, "bad rgbe scanline format"); let D = 0, N; for (; D < R && T < m.byteLength; ) { N = m[T++]; const H = N > 128; if (H && (N -= 128), (N === 0 || D + N > R) && t(3, "bad scanline data"), H) { const j = m[T++]; for (let q = 0; q < N; q++) b[D++] = j; } else b.set(m.subarray(T, T + N), D), D += N, T += N; } const k = _; for (let H = 0; H < k; H++) { let j = 0; E[A] = b[H + j], j += _, E[A + 1] = b[H + j], j += _, E[A + 2] = b[H + j], j += _, E[A + 3] = b[H + j], A += 4; } S--; } return E; }, a = function(m, p, y, _) { const E = m[p + 3], A = Math.pow(2, E - 128) / 255; y[_ + 0] = m[p + 0] * A, y[_ + 1] = m[p + 1] * A, y[_ + 2] = m[p + 2] * A, y[_ + 3] = 1; }, o = function(m, p, y, _) { const E = m[p + 3], A = Math.pow(2, E - 128) / 255; y[_ + 0] = Vs.toHalfFloat(Math.min(m[p + 0] * A, 65504)), y[_ + 1] = Vs.toHalfFloat(Math.min(m[p + 1] * A, 65504)), y[_ + 2] = Vs.toHalfFloat(Math.min(m[p + 2] * A, 65504)), y[_ + 3] = Vs.toHalfFloat(1); }, l = new Uint8Array(e); l.pos = 0; const c = s(l), h = c.width, u = c.height, d = n(l.subarray(l.pos), h, u); let f, g, v; switch (this.type) { case Gt: v = d.length / 4; const m = new Float32Array(v * 4); for (let y = 0; y < v; y++) a(d, y * 4, m, y * 4); f = m, g = Gt; break; case ft: v = d.length / 4; const p = new Uint16Array(v * 4); for (let y = 0; y < v; y++) o(d, y * 4, p, y * 4); f = p, g = ft; break; default: throw new Error("THREE.HDRLoader: Unsupported type: " + this.type); } return { width: h, height: u, data: f, header: c.string, gamma: c.gamma, exposure: c.exposure, type: g }; } /** * Sets the texture type. * * @param {(HalfFloatType|FloatType)} value - The texture type to set. * @return {HDRLoader} A reference to this loader. */ setDataType(e) { return this.type = e, this; } load(e, t, i, s) { function n(a, o) { switch (a.type) { case Gt: case ft: a.colorSpace = Ut, a.minFilter = xt, a.magFilter = xt, a.generateMipmaps = !1, a.flipY = !0; break; } t && t(a, o); } return super.load(e, n, i, s); } } class Qv extends $v { constructor(e) { console.warn("RGBELoader has been deprecated. Please use HDRLoader instead."), super(e); } } const Qi = { name: "CopyShader", uniforms: { tDiffuse: { value: null }, opacity: { value: 1 } }, vertexShader: ( /* glsl */ ` varying vec2 vUv; void main() { vUv = uv; gl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 ); }` ), fragmentShader: ( /* glsl */ ` uniform float opacity; uniform sampler2D tDiffuse; varying vec2 vUv; void main() { vec4 texel = texture2D( tDiffuse, vUv ); gl_FragColor = opacity * texel; }` ) }; class tr { /** * Constructs a new pass. */ constructor() { this.isPass = !0, this.enabled = !0, this.needsSwap = !0, this.clear = !1, this.renderToScreen = !1; } /** * Sets the size of the pass. * * @abstract * @param {number} width - The width to set. * @param {number} height - The height to set. */ setSize() { } /** * This method holds the render logic of a pass. It must be implemented in all derived classes. * * @abstract * @param {WebGLRenderer} renderer - The renderer. * @param {WebGLRenderTarget} writeBuffer - The write buffer. This buffer is intended as the rendering * destination for the pass. * @param {WebGLRenderTarget} readBuffer - The read buffer. The pass can access the result from the * previous pass from this buffer. * @param {number} deltaTime - The delta time in seconds. * @param {boolean} maskActive - Whether masking is active or not. */ render() { console.error("THREE.Pass: .render() must be implemented in derived pass."); } /** * Frees the GPU-related resources allocated by this instance. Call this * method whenever the pass is no longer used in your app. * * @abstract */ dispose() { } } const e0 = new mr(-1, 1, 1, -1, 0, 1); class t0 extends Qt { constructor() { super(), this.setAttribute("position", new pi([-1, 3, 0, -1, -1, 0, 3, -1, 0], 3)), this.setAttribute("uv", new pi([0, 2, 0, 0, 2, 0], 2)); } } const i0 = new t0(); class Ds { /** * Constructs a new full screen quad. * * @param {?Material} material - The material to render te full screen quad with. */ constructor(e) { this._mesh = new nt(i0, e); } /** * Frees the GPU-related resources allocated by this instance. Call this * method whenever the instance is no longer used in your app. */ dispose() { this._mesh.geometry.dispose(); } /** * Renders the full screen quad. * * @param {WebGLRenderer} renderer - The renderer. */ render(e) { e.render(this._mesh, e0); } /** * The quad's material. * * @type {?Material} */ get material() { return this._mesh.material; } set material(e) { this._mesh.material = e; } } class _o extends tr { /** * Constructs a new shader pass. * * @param {Object|ShaderMaterial} [shader] - A shader object holding vertex and fragment shader as well as * defines and uniforms. It's also valid to pass a custom shader material. * @param {string} [textureID='tDiffuse'] - The name of the texture uniform that should sample * the read buffer. */ constructor(e, t = "tDiffuse") { super(), this.textureID = t, this.uniforms = null, this.material = null, e instanceof ct ? (this.uniforms = e.uniforms, this.material = e) : e && (this.uniforms = ui.clone(e.uniforms), this.material = new ct({ name: e.name !== void 0 ? e.name : "unspecified", defines: Object.assign({}, e.defines), uniforms: this.uniforms, vertexShader: e.vertexShader, fragmentShader: e.fragmentShader })), this._fsQuad = new Ds(this.material); } /** * Performs the shader pass. * * @param {WebGLRenderer} renderer - The renderer. * @param {WebGLRenderTarget} writeBuffer - The write buffer. This buffer is intended as the rendering * destination for the pass. * @param {WebGLRenderTarget} readBuffer - The read buffer. The pass can access the result from the * previous pass from this buffer. * @param {number} deltaTime - The delta time in seconds. * @param {boolean} maskActive - Whether masking is active or not. */ render(e, t, i) { this.uniforms[this.textureID] && (this.uniforms[this.textureID].value = i.texture), this._fsQuad.material = this.material, this.renderToScreen ? (e.setRenderTarget(null), this._fsQuad.render(e)) : (e.setRenderTarget(t), this.clear && e.clear(e.autoClearColor, e.autoClearDepth, e.autoClearStencil), this._fsQuad.render(e)); } /** * Frees the GPU-related resources allocated by this instance. Call this * method whenever the pass is no longer used in your app. */ dispose() { this.material.dispose(), this._fsQuad.dispose(); } } class bc extends tr { /** * Constructs a new mask pass. * * @param {Scene} scene - The 3D objects in this scene will define the mask. * @param {Camera} camera - The camera. */ constructor(e, t) { super(), this.scene = e, this.camera = t, this.clear = !0, this.needsSwap = !1, this.inverse = !1; } /** * Performs a mask pass with the configured scene and camera. * * @param {WebGLRenderer} renderer - The renderer. * @param {WebGLRenderTarget} writeBuffer - The write buffer. This buffer is intended as the rendering * destination for the pass. * @param {WebGLRenderTarget} readBuffer - The read buffer. The pass can access the result from the * previous pass from this buffer. * @param {number} deltaTime - The delta time in seconds. * @param {boolean} maskActive - Whether masking is active or not. */ render(e, t, i) { const s = e.getContext(), n = e.state; n.buffers.color.setMask(!1), n.buffers.depth.setMask(!1), n.buffers.color.setLocked(!0), n.buffers.depth.setLocked(!0); let a, o; this.inverse ? (a = 0, o = 1) : (a = 1, o = 0), n.buffers.stencil.setTest(!0), n.buffers.stencil.setOp(s.REPLACE, s.REPLACE, s.REPLACE), n.buffers.stencil.setFunc(s.ALWAYS, a, 4294967295), n.buffers.stencil.setClear(o), n.buffers.stencil.setLocked(!0), e.setRenderTarget(i), this.clear && e.clear(), e.render(this.scene, this.camera), e.setRenderTarget(t), this.clear && e.clear(), e.render(this.scene, this.camera), n.buffers.color.setLocked(!1), n.buffers.depth.setLocked(!1), n.buffers.color.setMask(!0), n.buffers.depth.setMask(!0), n.buffers.stencil.setLocked(!1), n.buffers.stencil.setFunc(s.EQUAL, 1, 4294967295), n.buffers.stencil.setOp(s.KEEP, s.KEEP, s.KEEP), n.buffers.stencil.setLocked(!0); } } class r0 extends tr { /** * Constructs a new clear mask pass. */ constructor() { super(), this.needsSwap = !1; } /** * Performs the clear of the currently defined mask. * * @param {WebGLRenderer} renderer - The renderer. * @param {WebGLRenderTarget} writeBuffer - The write buffer. This buffer is intended as the rendering * destination for the pass. * @param {WebGLRenderTarget} readBuffer - The read buffer. The pass can access the result from the * previous pass from this buffer. * @param {number} deltaTime - The delta time in seconds. * @param {boolean} maskActive - Whether masking is active or not. */ render(e) { e.state.buffers.stencil.setLocked(!1), e.state.buffers.stencil.setTest(!1); } } class s0 { /** * Constructs a new effect composer. * * @param {WebGLRenderer} renderer - The renderer. * @param {WebGLRenderTarget} [renderTarget] - This render target and a clone will * be used as the internal read and write buffers. If not given, the composer creates * the buffers automatically. */ constructor(e, t) { if (this.renderer = e, this._pixelRatio = e.getPixelRatio(), t === void 0) { const i = e.getSize(new oe()); this._width = i.width, this._height = i.height, t = new _t(this._width * this._pixelRatio, this._height * this._pixelRatio, { type: ft }), t.texture.name = "EffectComposer.rt1"; } else this._width = t.width, this._height = t.height; this.renderTarget1 = t, this.renderTarget2 = t.clone(), this.renderTarget2.texture.name = "EffectComposer.rt2", this.writeBuffer = this.renderTarget1, this.readBuffer = this.renderTarget2, this.renderToScreen = !0, this.passes = [], this.copyPass = new _o(Qi), this.copyPass.material.blending = vt, this.clock = new ep(); } /** * Swaps the internal read/write buffers. */ swapBuffers() { const e = this.readBuffer; this.readBuffer = this.writeBuffer, this.writeBuffer = e; } /** * Adds the given pass to the pass chain. * * @param {Pass} pass - The pass to add. */ addPass(e) { this.passes.push(e), e.setSize(this._width * this._pixelRatio, this._height * this._pixelRatio); } /** * Inserts the given pass at a given index. * * @param {Pass} pass - The pass to insert. * @param {number} index - The index into the pass chain. */ insertPass(e, t) { this.passes.splice(t, 0, e), e.setSize(this._width * this._pixelRatio, this._height * this._pixelRatio); } /** * Removes the given pass from the pass chain. * * @param {Pass} pass - The pass to remove. */ removePass(e) { const t = this.passes.indexOf(e); t !== -1 && this.passes.splice(t, 1); } /** * Returns `true` if the pass for the given index is the last enabled pass in the pass chain. * * @param {number} passIndex - The pass index. * @return {boolean} Whether the pass for the given index is the last pass in the pass chain. */ isLastEnabledPass(e) { for (let t = e + 1; t < this.passes.length; t++) if (this.passes[t].enabled) return !1; return !0; } /** * Executes all enabled post-processing passes in order to produce the final frame. * * @param {number} deltaTime - The delta time in seconds. If not given, the composer computes * its own time delta value. */ render(e) { e === void 0 && (e = this.clock.getDelta()); const t = this.renderer.getRenderTarget(); let i = !1; for (let s = 0, n = this.passes.length; s < n; s++) { const a = this.passes[s]; if (a.enabled !== !1) { if (a.renderToScreen = this.renderToScreen && this.isLastEnabledPass(s), a.render(this.renderer, this.writeBuffer, this.readBuffer, e, i), a.needsSwap) { if (i) { const o = this.renderer.getContext(), l = this.renderer.state.buffers.stencil; l.setFunc(o.NOTEQUAL, 1, 4294967295), this.copyPass.render(this.renderer, this.writeBuffer, this.readBuffer, e), l.setFunc(o.EQUAL, 1, 4294967295); } this.swapBuffers(); } bc !== void 0 && (a instanceof bc ? i = !0 : a instanceof r0 && (i = !1)); } } this.renderer.setRenderTarget(t); } /** * Resets the internal state of the EffectComposer. * * @param {WebGLRenderTarget} [renderTarget] - This render target has the same purpose like * the one from the constructor. If set, it is used to setup the read and write buffers. */ reset(e) { if (e === void 0) { const t = this.renderer.getSize(new oe()); this._pixelRatio = this.renderer.getPixelRatio(), this._width = t.width, this._height = t.height, e = this.renderTarget1.clone(), e.setSize(this._width * this._pixelRatio, this._height * this._pixelRatio); } this.renderTarget1.dispose(), this.renderTarget2.dispose(), this.renderTarget1 = e, this.renderTarget2 = e.clone(), this.writeBuffer = this.renderTarget1, this.readBuffer = this.renderTarget2; } /** * Resizes the internal read and write buffers as well as all passes. Similar to {@link WebGLRenderer#setSize}, * this method honors the current pixel ration. * * @param {number} width - The width in logical pixels. * @param {number} height - The height in logical pixels. */ setSize(e, t) { this._width = e, this._height = t; const i = this._width * this._pixelRatio, s = this._height * this._pixelRatio; this.renderTarget1.setSize(i, s), this.renderTarget2.setSize(i, s); for (let n = 0; n < this.passes.length; n++) this.passes[n].setSize(i, s); } /** * Sets device pixel ratio. This is usually used for HiDPI device to prevent blurring output. * Setting the pixel ratio will automatically resize the composer. * * @param {number} pixelRatio - The pixel ratio to set. */ setPixelRatio(e) { this._pixelRatio = e, this.setSize(this._width, this._height); } /** * Frees the GPU-related resources allocated by this instance. Call this * method whenever the composer is no longer used in your app. */ dispose() { this.renderTarget1.dispose(), this.renderTarget2.dispose(), this.copyPass.dispose(); } } class n0 extends tr { /** * Constructs a new render pass. * * @param {Scene} scene - The scene to render. * @param {Camera} camera - The camera. * @param {?Material} [overrideMaterial=null] - The override material. If set, this material is used * for all objects in the scene. * @param {?(number|Color|string)} [clearColor=null] - The clear color of the render pass. * @param {?number} [clearAlpha=null] - The clear alpha of the render pass. */ constructor(e, t, i = null, s = null, n = null) { super(), this.scene = e, this.camera = t, this.overrideMaterial = i, this.clearColor = s, this.clearAlpha = n, this.clear = !0, this.clearDepth = !1, this.needsSwap = !1, this._oldClearColor = new _e(); } /** * Performs a beauty pass with the configured scene and camera. * * @param {WebGLRenderer} renderer - The renderer. * @param {WebGLRenderTarget} writeBuffer - The write buffer. This buffer is intended as the rendering * destination for the pass. * @param {WebGLRenderTarget} readBuffer - The read buffer. The pass can access the result from the * previous pass from this buffer. * @param {number} deltaTime - The delta time in seconds. * @param {boolean} maskActive - Whether masking is active or not. */ render(e, t, i) { const s = e.autoClear; e.autoClear = !1; let n, a; this.overrideMaterial !== null && (a = this.scene.overrideMaterial, this.scene.overrideMaterial = this.overrideMaterial), this.clearColor !== null && (e.getClearColor(this._oldClearColor), e.setClearColor(this.clearColor, e.getClearAlpha())), this.clearAlpha !== null && (n = e.getClearAlpha(), e.setClearAlpha(this.clearAlpha)), this.clearDepth == !0 && e.clearDepth(), e.setRenderTarget(this.renderToScreen ? null : i), this.clear === !0 && e.clear(e.autoClearColor, e.autoClearDepth, e.autoClearStencil), e.render(this.scene, this.camera), this.clearColor !== null && e.setClearColor(this._oldClearColor), this.clearAlpha !== null && e.setClearAlpha(n), this.overrideMaterial !== null && (this.scene.overrideMaterial = a), e.autoClear = s; } } const ln = { defines: { PERSPECTIVE_CAMERA: 1, SAMPLES: 16, NORMAL_VECTOR_TYPE: 1, DEPTH_SWIZZLING: "x", SCREEN_SPACE_RADIUS: 0, SCREEN_SPACE_RADIUS_SCALE: 100, SCENE_CLIP_BOX: 0 }, uniforms: { tNormal: { value: null }, tDepth: { value: null }, tNoise: { value: null }, resolution: { value: new oe() }, cameraNear: { value: null }, cameraFar: { value: null }, cameraProjectionMatrix: { value: new Ue() }, cameraProjectionMatrixInverse: { value: new Ue() }, cameraWorldMatrix: { value: new Ue() }, radius: { value: 0.25 }, distanceExponent: { value: 1 }, thickness: { value: 1 }, distanceFallOff: { value: 1 }, scale: { value: 1 }, sceneBoxMin: { value: new w(-1, -1, -1) }, sceneBoxMax: { value: new w(1, 1, 1) } }, vertexShader: ( /* glsl */ ` varying vec2 vUv; void main() { vUv = uv; gl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 ); }` ), fragmentShader: ( /* glsl */ ` varying vec2 vUv; uniform highp sampler2D tNormal; uniform highp sampler2D tDepth; uniform sampler2D tNoise; uniform vec2 resolution; uniform float cameraNear; uniform float cameraFar; uniform mat4 cameraProjectionMatrix; uniform mat4 cameraProjectionMatrixInverse; uniform mat4 cameraWorldMatrix; uniform float radius; uniform float distanceExponent; uniform float thickness; uniform float distanceFallOff; uniform float scale; #if SCENE_CLIP_BOX == 1 uniform vec3 sceneBoxMin; uniform vec3 sceneBoxMax; #endif #include #include #ifndef FRAGMENT_OUTPUT #define FRAGMENT_OUTPUT vec4(vec3(ao), 1.) #endif vec3 getViewPosition(const in vec2 screenPosition, const in float depth) { vec4 clipSpacePosition = vec4(vec3(screenPosition, depth) * 2.0 - 1.0, 1.0); vec4 viewSpacePosition = cameraProjectionMatrixInverse * clipSpacePosition; return viewSpacePosition.xyz / viewSpacePosition.w; } float getDepth(const vec2 uv) { return textureLod(tDepth, uv.xy, 0.0).DEPTH_SWIZZLING; } float fetchDepth(const ivec2 uv) { return texelFetch(tDepth, uv.xy, 0).DEPTH_SWIZZLING; } float getViewZ(const in float depth) { #if PERSPECTIVE_CAMERA == 1 return perspectiveDepthToViewZ(depth, cameraNear, cameraFar); #else return orthographicDepthToViewZ(depth, cameraNear, cameraFar); #endif } vec3 computeNormalFromDepth(const vec2 uv) { vec2 size = vec2(textureSize(tDepth, 0)); ivec2 p = ivec2(uv * size); float c0 = fetchDepth(p); float l2 = fetchDepth(p - ivec2(2, 0)); float l1 = fetchDepth(p - ivec2(1, 0)); float r1 = fetchDepth(p + ivec2(1, 0)); float r2 = fetchDepth(p + ivec2(2, 0)); float b2 = fetchDepth(p - ivec2(0, 2)); float b1 = fetchDepth(p - ivec2(0, 1)); float t1 = fetchDepth(p + ivec2(0, 1)); float t2 = fetchDepth(p + ivec2(0, 2)); float dl = abs((2.0 * l1 - l2) - c0); float dr = abs((2.0 * r1 - r2) - c0); float db = abs((2.0 * b1 - b2) - c0); float dt = abs((2.0 * t1 - t2) - c0); vec3 ce = getViewPosition(uv, c0).xyz; vec3 dpdx = (dl < dr) ? ce - getViewPosition((uv - vec2(1.0 / size.x, 0.0)), l1).xyz : -ce + getViewPosition((uv + vec2(1.0 / size.x, 0.0)), r1).xyz; vec3 dpdy = (db < dt) ? ce - getViewPosition((uv - vec2(0.0, 1.0 / size.y)), b1).xyz : -ce + getViewPosition((uv + vec2(0.0, 1.0 / size.y)), t1).xyz; return normalize(cross(dpdx, dpdy)); } vec3 getViewNormal(const vec2 uv) { #if NORMAL_VECTOR_TYPE == 2 return normalize(textureLod(tNormal, uv, 0.).rgb); #elif NORMAL_VECTOR_TYPE == 1 return unpackRGBToNormal(textureLod(tNormal, uv, 0.).rgb); #else return computeNormalFromDepth(uv); #endif } vec3 getSceneUvAndDepth(vec3 sampleViewPos) { vec4 sampleClipPos = cameraProjectionMatrix * vec4(sampleViewPos, 1.); vec2 sampleUv = sampleClipPos.xy / sampleClipPos.w * 0.5 + 0.5; float sampleSceneDepth = getDepth(sampleUv); return vec3(sampleUv, sampleSceneDepth); } void main() { float depth = getDepth(vUv.xy); if (depth >= 1.0) { discard; return; } vec3 viewPos = getViewPosition(vUv, depth); vec3 viewNormal = getViewNormal(vUv); float radiusToUse = radius; float distanceFalloffToUse = thickness; #if SCREEN_SPACE_RADIUS == 1 float radiusScale = getViewPosition(vec2(0.5 + float(SCREEN_SPACE_RADIUS_SCALE) / resolution.x, 0.0), depth).x; radiusToUse *= radiusScale; distanceFalloffToUse *= radiusScale; #endif #if SCENE_CLIP_BOX == 1 vec3 worldPos = (cameraWorldMatrix * vec4(viewPos, 1.0)).xyz; float boxDistance = length(max(vec3(0.0), max(sceneBoxMin - worldPos, worldPos - sceneBoxMax))); if (boxDistance > radiusToUse) { discard; return; } #endif vec2 noiseResolution = vec2(textureSize(tNoise, 0)); vec2 noiseUv = vUv * resolution / noiseResolution; vec4 noiseTexel = textureLod(tNoise, noiseUv, 0.0); vec3 randomVec = noiseTexel.xyz * 2.0 - 1.0; vec3 tangent = normalize(vec3(randomVec.xy, 0.)); vec3 bitangent = vec3(-tangent.y, tangent.x, 0.); mat3 kernelMatrix = mat3(tangent, bitangent, vec3(0., 0., 1.)); const int DIRECTIONS = SAMPLES < 30 ? 3 : 5; const int STEPS = (SAMPLES + DIRECTIONS - 1) / DIRECTIONS; float ao = 0.0; for (int i = 0; i < DIRECTIONS; ++i) { float angle = float(i) / float(DIRECTIONS) * PI; vec4 sampleDir = vec4(cos(angle), sin(angle), 0., 0.5 + 0.5 * noiseTexel.w); sampleDir.xyz = normalize(kernelMatrix * sampleDir.xyz); vec3 viewDir = normalize(-viewPos.xyz); vec3 sliceBitangent = normalize(cross(sampleDir.xyz, viewDir)); vec3 sliceTangent = cross(sliceBitangent, viewDir); vec3 normalInSlice = normalize(viewNormal - sliceBitangent * dot(viewNormal, sliceBitangent)); vec3 tangentToNormalInSlice = cross(normalInSlice, sliceBitangent); vec2 cosHorizons = vec2(dot(viewDir, tangentToNormalInSlice), dot(viewDir, -tangentToNormalInSlice)); for (int j = 0; j < STEPS; ++j) { vec3 sampleViewOffset = sampleDir.xyz * radiusToUse * sampleDir.w * pow(float(j + 1) / float(STEPS), distanceExponent); vec3 sampleSceneUvDepth = getSceneUvAndDepth(viewPos + sampleViewOffset); vec3 sampleSceneViewPos = getViewPosition(sampleSceneUvDepth.xy, sampleSceneUvDepth.z); vec3 viewDelta = sampleSceneViewPos - viewPos; if (abs(viewDelta.z) < thickness) { float sampleCosHorizon = dot(viewDir, normalize(viewDelta)); cosHorizons.x += max(0., (sampleCosHorizon - cosHorizons.x) * mix(1., 2. / float(j + 2), distanceFallOff)); } sampleSceneUvDepth = getSceneUvAndDepth(viewPos - sampleViewOffset); sampleSceneViewPos = getViewPosition(sampleSceneUvDepth.xy, sampleSceneUvDepth.z); viewDelta = sampleSceneViewPos - viewPos; if (abs(viewDelta.z) < thickness) { float sampleCosHorizon = dot(viewDir, normalize(viewDelta)); cosHorizons.y += max(0., (sampleCosHorizon - cosHorizons.y) * mix(1., 2. / float(j + 2), distanceFallOff)); } } vec2 sinHorizons = sqrt(1. - cosHorizons * cosHorizons); float nx = dot(normalInSlice, sliceTangent); float ny = dot(normalInSlice, viewDir); float nxb = 1. / 2. * (acos(cosHorizons.y) - acos(cosHorizons.x) + sinHorizons.x * cosHorizons.x - sinHorizons.y * cosHorizons.y); float nyb = 1. / 2. * (2. - cosHorizons.x * cosHorizons.x - cosHorizons.y * cosHorizons.y); float occlusion = nx * nxb + ny * nyb; ao += occlusion; } ao = clamp(ao / float(DIRECTIONS), 0., 1.); #if SCENE_CLIP_BOX == 1 ao = mix(ao, 1., smoothstep(0., radiusToUse, boxDistance)); #endif ao = pow(ao, scale); gl_FragColor = FRAGMENT_OUTPUT; }` ) }, cn = { defines: { PERSPECTIVE_CAMERA: 1 }, uniforms: { tDepth: { value: null }, cameraNear: { value: null }, cameraFar: { value: null } }, vertexShader: ( /* glsl */ ` varying vec2 vUv; void main() { vUv = uv; gl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 ); }` ), fragmentShader: ( /* glsl */ ` uniform sampler2D tDepth; uniform float cameraNear; uniform float cameraFar; varying vec2 vUv; #include float getLinearDepth( const in vec2 screenPosition ) { #if PERSPECTIVE_CAMERA == 1 float fragCoordZ = texture2D( tDepth, screenPosition ).x; float viewZ = perspectiveDepthToViewZ( fragCoordZ, cameraNear, cameraFar ); return viewZToOrthographicDepth( viewZ, cameraNear, cameraFar ); #else return texture2D( tDepth, screenPosition ).x; #endif } void main() { float depth = getLinearDepth( vUv ); gl_FragColor = vec4( vec3( 1.0 - depth ), 1.0 ); }` ) }, _a = { uniforms: { tDiffuse: { value: null }, intensity: { value: 1 } }, vertexShader: ( /* glsl */ ` varying vec2 vUv; void main() { vUv = uv; gl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 ); }` ), fragmentShader: ( /* glsl */ ` uniform float intensity; uniform sampler2D tDiffuse; varying vec2 vUv; void main() { vec4 texel = texture2D( tDiffuse, vUv ); gl_FragColor = vec4(mix(vec3(1.), texel.rgb, intensity), texel.a); }` ) }; function a0(r = 5) { const e = Math.floor(r) % 2 === 0 ? Math.floor(r) + 1 : Math.floor(r), t = o0(e), i = t.length, s = new Uint8Array(i * 4); for (let a = 0; a < i; ++a) { const o = t[a], l = 2 * Math.PI * o / i, c = new w( Math.cos(l), Math.sin(l), 0 ).normalize(); s[a * 4] = (c.x * 0.5 + 0.5) * 255, s[a * 4 + 1] = (c.y * 0.5 + 0.5) * 255, s[a * 4 + 2] = 127, s[a * 4 + 3] = 255; } const n = new es(s, e, e); return n.wrapS = Ei, n.wrapT = Ei, n.needsUpdate = !0, n; } function o0(r) { const e = Math.floor(r) % 2 === 0 ? Math.floor(r) + 1 : Math.floor(r), t = e * e, i = Array(t).fill(0); let s = Math.floor(e / 2), n = e - 1; for (let a = 1; a <= t; ) { if (s === -1 && n === e ? (n = e - 2, s = 0) : (n === e && (n = 0), s < 0 && (s = e - 1)), i[s * e + n] !== 0) { n -= 2, s++; continue; } else i[s * e + n] = a++; n++, s--; } return i; } const hn = { defines: { SAMPLES: 16, SAMPLE_VECTORS: Ch(16, 2, 1), NORMAL_VECTOR_TYPE: 1, DEPTH_VALUE_SOURCE: 0 }, uniforms: { tDiffuse: { value: null }, tNormal: { value: null }, tDepth: { value: null }, tNoise: { value: null }, resolution: { value: new oe() }, cameraProjectionMatrixInverse: { value: new Ue() }, lumaPhi: { value: 5 }, depthPhi: { value: 5 }, normalPhi: { value: 5 }, radius: { value: 4 }, index: { value: 0 } }, vertexShader: ( /* glsl */ ` varying vec2 vUv; void main() { vUv = uv; gl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 ); }` ), fragmentShader: ( /* glsl */ ` varying vec2 vUv; uniform sampler2D tDiffuse; uniform sampler2D tNormal; uniform sampler2D tDepth; uniform sampler2D tNoise; uniform vec2 resolution; uniform mat4 cameraProjectionMatrixInverse; uniform float lumaPhi; uniform float depthPhi; uniform float normalPhi; uniform float radius; uniform int index; #include #include #ifndef SAMPLE_LUMINANCE #define SAMPLE_LUMINANCE dot(vec3(0.2125, 0.7154, 0.0721), a) #endif #ifndef FRAGMENT_OUTPUT #define FRAGMENT_OUTPUT vec4(denoised, 1.) #endif float getLuminance(const in vec3 a) { return SAMPLE_LUMINANCE; } const vec3 poissonDisk[SAMPLES] = SAMPLE_VECTORS; vec3 getViewPosition(const in vec2 screenPosition, const in float depth) { vec4 clipSpacePosition = vec4(vec3(screenPosition, depth) * 2.0 - 1.0, 1.0); vec4 viewSpacePosition = cameraProjectionMatrixInverse * clipSpacePosition; return viewSpacePosition.xyz / viewSpacePosition.w; } float getDepth(const vec2 uv) { #if DEPTH_VALUE_SOURCE == 1 return textureLod(tDepth, uv.xy, 0.0).a; #else return textureLod(tDepth, uv.xy, 0.0).r; #endif } float fetchDepth(const ivec2 uv) { #if DEPTH_VALUE_SOURCE == 1 return texelFetch(tDepth, uv.xy, 0).a; #else return texelFetch(tDepth, uv.xy, 0).r; #endif } vec3 computeNormalFromDepth(const vec2 uv) { vec2 size = vec2(textureSize(tDepth, 0)); ivec2 p = ivec2(uv * size); float c0 = fetchDepth(p); float l2 = fetchDepth(p - ivec2(2, 0)); float l1 = fetchDepth(p - ivec2(1, 0)); float r1 = fetchDepth(p + ivec2(1, 0)); float r2 = fetchDepth(p + ivec2(2, 0)); float b2 = fetchDepth(p - ivec2(0, 2)); float b1 = fetchDepth(p - ivec2(0, 1)); float t1 = fetchDepth(p + ivec2(0, 1)); float t2 = fetchDepth(p + ivec2(0, 2)); float dl = abs((2.0 * l1 - l2) - c0); float dr = abs((2.0 * r1 - r2) - c0); float db = abs((2.0 * b1 - b2) - c0); float dt = abs((2.0 * t1 - t2) - c0); vec3 ce = getViewPosition(uv, c0).xyz; vec3 dpdx = (dl < dr) ? ce - getViewPosition((uv - vec2(1.0 / size.x, 0.0)), l1).xyz : -ce + getViewPosition((uv + vec2(1.0 / size.x, 0.0)), r1).xyz; vec3 dpdy = (db < dt) ? ce - getViewPosition((uv - vec2(0.0, 1.0 / size.y)), b1).xyz : -ce + getViewPosition((uv + vec2(0.0, 1.0 / size.y)), t1).xyz; return normalize(cross(dpdx, dpdy)); } vec3 getViewNormal(const vec2 uv) { #if NORMAL_VECTOR_TYPE == 2 return normalize(textureLod(tNormal, uv, 0.).rgb); #elif NORMAL_VECTOR_TYPE == 1 return unpackRGBToNormal(textureLod(tNormal, uv, 0.).rgb); #else return computeNormalFromDepth(uv); #endif } void denoiseSample(in vec3 center, in vec3 viewNormal, in vec3 viewPos, in vec2 sampleUv, inout vec3 denoised, inout float totalWeight) { vec4 sampleTexel = textureLod(tDiffuse, sampleUv, 0.0); float sampleDepth = getDepth(sampleUv); vec3 sampleNormal = getViewNormal(sampleUv); vec3 neighborColor = sampleTexel.rgb; vec3 viewPosSample = getViewPosition(sampleUv, sampleDepth); float normalDiff = dot(viewNormal, sampleNormal); float normalSimilarity = pow(max(normalDiff, 0.), normalPhi); float lumaDiff = abs(getLuminance(neighborColor) - getLuminance(center)); float lumaSimilarity = max(1.0 - lumaDiff / lumaPhi, 0.0); float depthDiff = abs(dot(viewPos - viewPosSample, viewNormal)); float depthSimilarity = max(1. - depthDiff / depthPhi, 0.); float w = lumaSimilarity * depthSimilarity * normalSimilarity; denoised += w * neighborColor; totalWeight += w; } void main() { float depth = getDepth(vUv.xy); vec3 viewNormal = getViewNormal(vUv); if (depth == 1. || dot(viewNormal, viewNormal) == 0.) { discard; return; } vec4 texel = textureLod(tDiffuse, vUv, 0.0); vec3 center = texel.rgb; vec3 viewPos = getViewPosition(vUv, depth); vec2 noiseResolution = vec2(textureSize(tNoise, 0)); vec2 noiseUv = vUv * resolution / noiseResolution; vec4 noiseTexel = textureLod(tNoise, noiseUv, 0.0); vec2 noiseVec = vec2(sin(noiseTexel[index % 4] * 2. * PI), cos(noiseTexel[index % 4] * 2. * PI)); mat2 rotationMatrix = mat2(noiseVec.x, -noiseVec.y, noiseVec.x, noiseVec.y); float totalWeight = 1.0; vec3 denoised = texel.rgb; for (int i = 0; i < SAMPLES; i++) { vec3 sampleDir = poissonDisk[i]; vec2 offset = rotationMatrix * (sampleDir.xy * (1. + sampleDir.z * (radius - 1.)) / resolution); vec2 sampleUv = vUv + offset; denoiseSample(center, viewNormal, viewPos, sampleUv, denoised, totalWeight); } if (totalWeight > 0.) { denoised /= totalWeight; } gl_FragColor = FRAGMENT_OUTPUT; }` ) }; function Ch(r, e, t) { const i = l0( r, e, t ); let s = "vec3[SAMPLES]("; for (let n = 0; n < r; n++) { const a = i[n]; s += `vec3(${a.x}, ${a.y}, ${a.z})${n < r - 1 ? "," : ")"}`; } return s; } function l0(r, e, t) { const i = []; for (let s = 0; s < r; s++) { const n = 2 * Math.PI * e * s / r, a = Math.pow(s / (r - 1), t); i.push(new w(Math.cos(n), Math.sin(n), a)); } return i; } class c0 { /** * Constructs a new simplex noise object. * * @param {Object} [r=Math] - A math utility class that holds a `random()` method. This makes it * possible to pass in custom random number generator. */ constructor(e = Math) { this.grad3 = [ [1, 1, 0], [-1, 1, 0], [1, -1, 0], [-1, -1, 0], [1, 0, 1], [-1, 0, 1], [1, 0, -1], [-1, 0, -1], [0, 1, 1], [0, -1, 1], [0, 1, -1], [0, -1, -1] ], this.grad4 = [ [0, 1, 1, 1], [0, 1, 1, -1], [0, 1, -1, 1], [0, 1, -1, -1], [0, -1, 1, 1], [0, -1, 1, -1], [0, -1, -1, 1], [0, -1, -1, -1], [1, 0, 1, 1], [1, 0, 1, -1], [1, 0, -1, 1], [1, 0, -1, -1], [-1, 0, 1, 1], [-1, 0, 1, -1], [-1, 0, -1, 1], [-1, 0, -1, -1], [1, 1, 0, 1], [1, 1, 0, -1], [1, -1, 0, 1], [1, -1, 0, -1], [-1, 1, 0, 1], [-1, 1, 0, -1], [-1, -1, 0, 1], [-1, -1, 0, -1], [1, 1, 1, 0], [1, 1, -1, 0], [1, -1, 1, 0], [1, -1, -1, 0], [-1, 1, 1, 0], [-1, 1, -1, 0], [-1, -1, 1, 0], [-1, -1, -1, 0] ], this.p = []; for (let t = 0; t < 256; t++) this.p[t] = Math.floor(e.random() * 256); this.perm = []; for (let t = 0; t < 512; t++) this.perm[t] = this.p[t & 255]; this.simplex = [ [0, 1, 2, 3], [0, 1, 3, 2], [0, 0, 0, 0], [0, 2, 3, 1], [0, 0, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0], [1, 2, 3, 0], [0, 2, 1, 3], [0, 0, 0, 0], [0, 3, 1, 2], [0, 3, 2, 1], [0, 0, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0], [1, 3, 2, 0], [0, 0, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0], [1, 2, 0, 3], [0, 0, 0, 0], [1, 3, 0, 2], [0, 0, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0], [2, 3, 0, 1], [2, 3, 1, 0], [1, 0, 2, 3], [1, 0, 3, 2], [0, 0, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0], [2, 0, 3, 1], [0, 0, 0, 0], [2, 1, 3, 0], [0, 0, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0], [2, 0, 1, 3], [0, 0, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0], [3, 0, 1, 2], [3, 0, 2, 1], [0, 0, 0, 0], [3, 1, 2, 0], [2, 1, 0, 3], [0, 0, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0], [3, 1, 0, 2], [0, 0, 0, 0], [3, 2, 0, 1], [3, 2, 1, 0] ]; } /** * A 2D simplex noise method. * * @param {number} xin - The x coordinate. * @param {number} yin - The y coordinate. * @return {number} The noise value. */ noise(e, t) { let i, s, n; const a = 0.5 * (Math.sqrt(3) - 1), o = (e + t) * a, l = Math.floor(e + o), c = Math.floor(t + o), h = (3 - Math.sqrt(3)) / 6, u = (l + c) * h, d = l - u, f = c - u, g = e - d, v = t - f; let m, p; g > v ? (m = 1, p = 0) : (m = 0, p = 1); const y = g - m + h, _ = v - p + h, E = g - 1 + 2 * h, A = v - 1 + 2 * h, T = l & 255, R = c & 255, I = this.perm[T + this.perm[R]] % 12, b = this.perm[T + m + this.perm[R + p]] % 12, S = this.perm[T + 1 + this.perm[R + 1]] % 12; let D = 0.5 - g * g - v * v; D < 0 ? i = 0 : (D *= D, i = D * D * this._dot(this.grad3[I], g, v)); let N = 0.5 - y * y - _ * _; N < 0 ? s = 0 : (N *= N, s = N * N * this._dot(this.grad3[b], y, _)); let k = 0.5 - E * E - A * A; return k < 0 ? n = 0 : (k *= k, n = k * k * this._dot(this.grad3[S], E, A)), 70 * (i + s + n); } /** * A 3D simplex noise method. * * @param {number} xin - The x coordinate. * @param {number} yin - The y coordinate. * @param {number} zin - The z coordinate. * @return {number} The noise value. */ noise3d(e, t, i) { let s, n, a, o; const l = (e + t + i) * 0.3333333333333333, c = Math.floor(e + l), h = Math.floor(t + l), u = Math.floor(i + l), d = 1 / 6, f = (c + h + u) * d, g = c - f, v = h - f, m = u - f, p = e - g, y = t - v, _ = i - m; let E, A, T, R, I, b; p >= y ? y >= _ ? (E = 1, A = 0, T = 0, R = 1, I = 1, b = 0) : p >= _ ? (E = 1, A = 0, T = 0, R = 1, I = 0, b = 1) : (E = 0, A = 0, T = 1, R = 1, I = 0, b = 1) : y < _ ? (E = 0, A = 0, T = 1, R = 0, I = 1, b = 1) : p < _ ? (E = 0, A = 1, T = 0, R = 0, I = 1, b = 1) : (E = 0, A = 1, T = 0, R = 1, I = 1, b = 0); const S = p - E + d, D = y - A + d, N = _ - T + d, k = p - R + 2 * d, H = y - I + 2 * d, j = _ - b + 2 * d, q = p - 1 + 3 * d, te = y - 1 + 3 * d, G = _ - 1 + 3 * d, Z = c & 255, se = h & 255, Pe = u & 255, ke = this.perm[Z + this.perm[se + this.perm[Pe]]] % 12, qe = this.perm[Z + E + this.perm[se + A + this.perm[Pe + T]]] % 12, Ke = this.perm[Z + R + this.perm[se + I + this.perm[Pe + b]]] % 12, Ze = this.perm[Z + 1 + this.perm[se + 1 + this.perm[Pe + 1]]] % 12; let W = 0.6 - p * p - y * y - _ * _; W < 0 ? s = 0 : (W *= W, s = W * W * this._dot3(this.grad3[ke], p, y, _)); let Y = 0.6 - S * S - D * D - N * N; Y < 0 ? n = 0 : (Y *= Y, n = Y * Y * this._dot3(this.grad3[qe], S, D, N)); let ue = 0.6 - k * k - H * H - j * j; ue < 0 ? a = 0 : (ue *= ue, a = ue * ue * this._dot3(this.grad3[Ke], k, H, j)); let Ce = 0.6 - q * q - te * te - G * G; return Ce < 0 ? o = 0 : (Ce *= Ce, o = Ce * Ce * this._dot3(this.grad3[Ze], q, te, G)), 32 * (s + n + a + o); } /** * A 4D simplex noise method. * * @param {number} x - The x coordinate. * @param {number} y - The y coordinate. * @param {number} z - The z coordinate. * @param {number} w - The w coordinate. * @return {number} The noise value. */ noise4d(e, t, i, s) { const n = this.grad4, a = this.simplex, o = this.perm, l = (Math.sqrt(5) - 1) / 4, c = (5 - Math.sqrt(5)) / 20; let h, u, d, f, g; const v = (e + t + i + s) * l, m = Math.floor(e + v), p = Math.floor(t + v), y = Math.floor(i + v), _ = Math.floor(s + v), E = (m + p + y + _) * c, A = m - E, T = p - E, R = y - E, I = _ - E, b = e - A, S = t - T, D = i - R, N = s - I, k = b > S ? 32 : 0, H = b > D ? 16 : 0, j = S > D ? 8 : 0, q = b > N ? 4 : 0, te = S > N ? 2 : 0, G = D > N ? 1 : 0, Z = k + H + j + q + te + G, se = a[Z][0] >= 3 ? 1 : 0, Pe = a[Z][1] >= 3 ? 1 : 0, ke = a[Z][2] >= 3 ? 1 : 0, qe = a[Z][3] >= 3 ? 1 : 0, Ke = a[Z][0] >= 2 ? 1 : 0, Ze = a[Z][1] >= 2 ? 1 : 0, W = a[Z][2] >= 2 ? 1 : 0, Y = a[Z][3] >= 2 ? 1 : 0, ue = a[Z][0] >= 1 ? 1 : 0, Ce = a[Z][1] >= 1 ? 1 : 0, be = a[Z][2] >= 1 ? 1 : 0, Ee = a[Z][3] >= 1 ? 1 : 0, $e = b - se + c, je = S - Pe + c, Ve = D - ke + c, L = N - qe + c, mt = b - Ke + 2 * c, We = S - Ze + 2 * c, Qe = D - W + 2 * c, fe = N - Y + 2 * c, at = b - ue + 3 * c, Me = S - Ce + 3 * c, De = D - be + 3 * c, C = N - Ee + 3 * c, x = b - 1 + 4 * c, B = S - 1 + 4 * c, X = D - 1 + 4 * c, K = N - 1 + 4 * c, V = m & 255, xe = p & 255, ne = y & 255, Te = _ & 255, de = o[V + o[xe + o[ne + o[Te]]]] % 32, $ = o[V + se + o[xe + Pe + o[ne + ke + o[Te + qe]]]] % 32, re = o[V + Ke + o[xe + Ze + o[ne + W + o[Te + Y]]]] % 32, Oe = o[V + ue + o[xe + Ce + o[ne + be + o[Te + Ee]]]] % 32, we = o[V + 1 + o[xe + 1 + o[ne + 1 + o[Te + 1]]]] % 32; let he = 0.6 - b * b - S * S - D * D - N * N; he < 0 ? h = 0 : (he *= he, h = he * he * this._dot4(n[de], b, S, D, N)); let Re = 0.6 - $e * $e - je * je - Ve * Ve - L * L; Re < 0 ? u = 0 : (Re *= Re, u = Re * Re * this._dot4(n[$], $e, je, Ve, L)); let P = 0.6 - mt * mt - We * We - Qe * Qe - fe * fe; P < 0 ? d = 0 : (P *= P, d = P * P * this._dot4(n[re], mt, We, Qe, fe)); let ae = 0.6 - at * at - Me * Me - De * De - C * C; ae < 0 ? f = 0 : (ae *= ae, f = ae * ae * this._dot4(n[Oe], at, Me, De, C)); let ie = 0.6 - x * x - B * B - X * X - K * K; return ie < 0 ? g = 0 : (ie *= ie, g = ie * ie * this._dot4(n[we], x, B, X, K)), 27 * (h + u + d + f + g); } // private _dot(e, t, i) { return e[0] * t + e[1] * i; } _dot3(e, t, i, s) { return e[0] * t + e[1] * i + e[2] * s; } _dot4(e, t, i, s, n) { return e[0] * t + e[1] * i + e[2] * s + e[3] * n; } } class ai extends tr { /** * Constructs a new GTAO pass. * * @param {Scene} scene - The scene to compute the AO for. * @param {Camera} camera - The camera. * @param {number} [width=512] - The width of the effect. * @param {number} [height=512] - The height of the effect. * @param {Object} [parameters] - The pass parameters. * @param {Object} [aoParameters] - The AO parameters. * @param {Object} [pdParameters] - The denoise parameters. */ constructor(e, t, i = 512, s = 512, n, a, o) { super(), this.width = i, this.height = s, this.clear = !0, this.camera = t, this.scene = e, this.output = 0, this._renderGBuffer = !0, this._visibilityCache = [], this.blendIntensity = 1, this.pdRings = 2, this.pdRadiusExponent = 2, this.pdSamples = 16, this.gtaoNoiseTexture = a0(), this.pdNoiseTexture = this._generateNoise(), this.gtaoRenderTarget = new _t(this.width, this.height, { type: ft }), this.pdRenderTarget = this.gtaoRenderTarget.clone(), this.gtaoMaterial = new ct({ defines: Object.assign({}, ln.defines), uniforms: ui.clone(ln.uniforms), vertexShader: ln.vertexShader, fragmentShader: ln.fragmentShader, blending: vt, depthTest: !1, depthWrite: !1 }), this.gtaoMaterial.defines.PERSPECTIVE_CAMERA = this.camera.isPerspectiveCamera ? 1 : 0, this.gtaoMaterial.uniforms.tNoise.value = this.gtaoNoiseTexture, this.gtaoMaterial.uniforms.resolution.value.set(this.width, this.height), this.gtaoMaterial.uniforms.cameraNear.value = this.camera.near, this.gtaoMaterial.uniforms.cameraFar.value = this.camera.far, this.normalMaterial = new Dd(), this.normalMaterial.blending = vt, this.pdMaterial = new ct({ defines: Object.assign({}, hn.defines), uniforms: ui.clone(hn.uniforms), vertexShader: hn.vertexShader, fragmentShader: hn.fragmentShader, depthTest: !1, depthWrite: !1 }), this.pdMaterial.uniforms.tDiffuse.value = this.gtaoRenderTarget.texture, this.pdMaterial.uniforms.tNoise.value = this.pdNoiseTexture, this.pdMaterial.uniforms.resolution.value.set(this.width, this.height), this.pdMaterial.uniforms.lumaPhi.value = 10, this.pdMaterial.uniforms.depthPhi.value = 2, this.pdMaterial.uniforms.normalPhi.value = 3, this.pdMaterial.uniforms.radius.value = 8, this.depthRenderMaterial = new ct({ defines: Object.assign({}, cn.defines), uniforms: ui.clone(cn.uniforms), vertexShader: cn.vertexShader, fragmentShader: cn.fragmentShader, blending: vt }), this.depthRenderMaterial.uniforms.cameraNear.value = this.camera.near, this.depthRenderMaterial.uniforms.cameraFar.value = this.camera.far, this.copyMaterial = new ct({ uniforms: ui.clone(Qi.uniforms), vertexShader: Qi.vertexShader, fragmentShader: Qi.fragmentShader, transparent: !0, depthTest: !1, depthWrite: !1, blendSrc: Ca, blendDst: ms, blendEquation: li, blendSrcAlpha: wa, blendDstAlpha: ms, blendEquationAlpha: li }), this.blendMaterial = new ct({ uniforms: ui.clone(_a.uniforms), vertexShader: _a.vertexShader, fragmentShader: _a.fragmentShader, transparent: !0, depthTest: !1, depthWrite: !1, blending: zc, blendSrc: Ca, blendDst: ms, blendEquation: li, blendSrcAlpha: wa, blendDstAlpha: ms, blendEquationAlpha: li }), this._fsQuad = new Ds(null), this._originalClearColor = new _e(), this.setGBuffer(n ? n.depthTexture : void 0, n ? n.normalTexture : void 0), a !== void 0 && this.updateGtaoMaterial(a), o !== void 0 && this.updatePdMaterial(o); } /** * Sets the size of the pass. * * @param {number} width - The width to set. * @param {number} height - The height to set. */ setSize(e, t) { this.width = e, this.height = t, this.gtaoRenderTarget.setSize(e, t), this.normalRenderTarget.setSize(e, t), this.pdRenderTarget.setSize(e, t), this.gtaoMaterial.uniforms.resolution.value.set(e, t), this.gtaoMaterial.uniforms.cameraProjectionMatrix.value.copy(this.camera.projectionMatrix), this.gtaoMaterial.uniforms.cameraProjectionMatrixInverse.value.copy(this.camera.projectionMatrixInverse), this.pdMaterial.uniforms.resolution.value.set(e, t), this.pdMaterial.uniforms.cameraProjectionMatrixInverse.value.copy(this.camera.projectionMatrixInverse); } /** * Frees the GPU-related resources allocated by this instance. Call this * method whenever the pass is no longer used in your app. */ dispose() { this.gtaoNoiseTexture.dispose(), this.pdNoiseTexture.dispose(), this.normalRenderTarget.dispose(), this.gtaoRenderTarget.dispose(), this.pdRenderTarget.dispose(), this.normalMaterial.dispose(), this.pdMaterial.dispose(), this.copyMaterial.dispose(), this.depthRenderMaterial.dispose(), this._fsQuad.dispose(); } /** * A texture holding the computed AO. * * @type {Texture} * @readonly */ get gtaoMap() { return this.pdRenderTarget.texture; } /** * Configures the GBuffer of this pass. If no arguments are passed, * the pass creates an internal render target for holding depth * and normal data. * * @param {DepthTexture} [depthTexture] - The depth texture. * @param {DepthTexture} [normalTexture] - The normal texture. */ setGBuffer(e, t) { e !== void 0 ? (this.depthTexture = e, this.normalTexture = t, this._renderGBuffer = !1) : (this.depthTexture = new Wo(), this.depthTexture.format = Xr, this.depthTexture.type = jr, this.normalRenderTarget = new _t(this.width, this.height, { minFilter: Dt, magFilter: Dt, type: ft, depthTexture: this.depthTexture }), this.normalTexture = this.normalRenderTarget.texture, this._renderGBuffer = !0); const i = this.normalTexture ? 1 : 0, s = this.depthTexture === this.normalTexture ? "w" : "x"; this.gtaoMaterial.defines.NORMAL_VECTOR_TYPE = i, this.gtaoMaterial.defines.DEPTH_SWIZZLING = s, this.gtaoMaterial.uniforms.tNormal.value = this.normalTexture, this.gtaoMaterial.uniforms.tDepth.value = this.depthTexture, this.pdMaterial.defines.NORMAL_VECTOR_TYPE = i, this.pdMaterial.defines.DEPTH_SWIZZLING = s, this.pdMaterial.uniforms.tNormal.value = this.normalTexture, this.pdMaterial.uniforms.tDepth.value = this.depthTexture, this.depthRenderMaterial.uniforms.tDepth.value = this.normalRenderTarget.depthTexture; } /** * Configures the clip box of the GTAO shader with the given AABB. * * @param {?Box3} box - The AABB enclosing the scene that should receive AO. When passing * `null`, to clip box is used. */ setSceneClipBox(e) { e ? (this.gtaoMaterial.needsUpdate = this.gtaoMaterial.defines.SCENE_CLIP_BOX !== 1, this.gtaoMaterial.defines.SCENE_CLIP_BOX = 1, this.gtaoMaterial.uniforms.sceneBoxMin.value.copy(e.min), this.gtaoMaterial.uniforms.sceneBoxMax.value.copy(e.max)) : (this.gtaoMaterial.needsUpdate = this.gtaoMaterial.defines.SCENE_CLIP_BOX === 0, this.gtaoMaterial.defines.SCENE_CLIP_BOX = 0); } /** * Updates the GTAO material from the given parameter object. * * @param {Object} parameters - The GTAO material parameters. */ updateGtaoMaterial(e) { e.radius !== void 0 && (this.gtaoMaterial.uniforms.radius.value = e.radius), e.distanceExponent !== void 0 && (this.gtaoMaterial.uniforms.distanceExponent.value = e.distanceExponent), e.thickness !== void 0 && (this.gtaoMaterial.uniforms.thickness.value = e.thickness), e.distanceFallOff !== void 0 && (this.gtaoMaterial.uniforms.distanceFallOff.value = e.distanceFallOff, this.gtaoMaterial.needsUpdate = !0), e.scale !== void 0 && (this.gtaoMaterial.uniforms.scale.value = e.scale), e.samples !== void 0 && e.samples !== this.gtaoMaterial.defines.SAMPLES && (this.gtaoMaterial.defines.SAMPLES = e.samples, this.gtaoMaterial.needsUpdate = !0), e.screenSpaceRadius !== void 0 && (e.screenSpaceRadius ? 1 : 0) !== this.gtaoMaterial.defines.SCREEN_SPACE_RADIUS && (this.gtaoMaterial.defines.SCREEN_SPACE_RADIUS = e.screenSpaceRadius ? 1 : 0, this.gtaoMaterial.needsUpdate = !0); } /** * Updates the Denoise material from the given parameter object. * * @param {Object} parameters - The denoise parameters. */ updatePdMaterial(e) { let t = !1; e.lumaPhi !== void 0 && (this.pdMaterial.uniforms.lumaPhi.value = e.lumaPhi), e.depthPhi !== void 0 && (this.pdMaterial.uniforms.depthPhi.value = e.depthPhi), e.normalPhi !== void 0 && (this.pdMaterial.uniforms.normalPhi.value = e.normalPhi), e.radius !== void 0 && e.radius !== this.radius && (this.pdMaterial.uniforms.radius.value = e.radius), e.radiusExponent !== void 0 && e.radiusExponent !== this.pdRadiusExponent && (this.pdRadiusExponent = e.radiusExponent, t = !0), e.rings !== void 0 && e.rings !== this.pdRings && (this.pdRings = e.rings, t = !0), e.samples !== void 0 && e.samples !== this.pdSamples && (this.pdSamples = e.samples, t = !0), t && (this.pdMaterial.defines.SAMPLES = this.pdSamples, this.pdMaterial.defines.SAMPLE_VECTORS = Ch(this.pdSamples, this.pdRings, this.pdRadiusExponent), this.pdMaterial.needsUpdate = !0); } /** * Performs the GTAO pass. * * @param {WebGLRenderer} renderer - The renderer. * @param {WebGLRenderTarget} writeBuffer - The write buffer. This buffer is intended as the rendering * destination for the pass. * @param {WebGLRenderTarget} readBuffer - The read buffer. The pass can access the result from the * previous pass from this buffer. * @param {number} deltaTime - The delta time in seconds. * @param {boolean} maskActive - Whether masking is active or not. */ render(e, t, i) { switch (this._renderGBuffer && (this._overrideVisibility(), this._renderOverride(e, this.normalMaterial, this.normalRenderTarget, 7829503, 1), this._restoreVisibility()), this.gtaoMaterial.uniforms.cameraNear.value = this.camera.near, this.gtaoMaterial.uniforms.cameraFar.value = this.camera.far, this.gtaoMaterial.uniforms.cameraProjectionMatrix.value.copy(this.camera.projectionMatrix), this.gtaoMaterial.uniforms.cameraProjectionMatrixInverse.value.copy(this.camera.projectionMatrixInverse), this.gtaoMaterial.uniforms.cameraWorldMatrix.value.copy(this.camera.matrixWorld), this._renderPass(e, this.gtaoMaterial, this.gtaoRenderTarget, 16777215, 1), this.pdMaterial.uniforms.cameraProjectionMatrixInverse.value.copy(this.camera.projectionMatrixInverse), this._renderPass(e, this.pdMaterial, this.pdRenderTarget, 16777215, 1), this.output) { case ai.OUTPUT.Off: break; case ai.OUTPUT.Diffuse: this.copyMaterial.uniforms.tDiffuse.value = i.texture, this.copyMaterial.blending = vt, this._renderPass(e, this.copyMaterial, this.renderToScreen ? null : t); break; case ai.OUTPUT.AO: this.copyMaterial.uniforms.tDiffuse.value = this.gtaoRenderTarget.texture, this.copyMaterial.blending = vt, this._renderPass(e, this.copyMaterial, this.renderToScreen ? null : t); break; case ai.OUTPUT.Denoise: this.copyMaterial.uniforms.tDiffuse.value = this.pdRenderTarget.texture, this.copyMaterial.blending = vt, this._renderPass(e, this.copyMaterial, this.renderToScreen ? null : t); break; case ai.OUTPUT.Depth: this.depthRenderMaterial.uniforms.cameraNear.value = this.camera.near, this.depthRenderMaterial.uniforms.cameraFar.value = this.camera.far, this._renderPass(e, this.depthRenderMaterial, this.renderToScreen ? null : t); break; case ai.OUTPUT.Normal: this.copyMaterial.uniforms.tDiffuse.value = this.normalRenderTarget.texture, this.copyMaterial.blending = vt, this._renderPass(e, this.copyMaterial, this.renderToScreen ? null : t); break; case ai.OUTPUT.Default: this.copyMaterial.uniforms.tDiffuse.value = i.texture, this.copyMaterial.blending = vt, this._renderPass(e, this.copyMaterial, this.renderToScreen ? null : t), this.blendMaterial.uniforms.intensity.value = this.blendIntensity, this.blendMaterial.uniforms.tDiffuse.value = this.pdRenderTarget.texture, this._renderPass(e, this.blendMaterial, this.renderToScreen ? null : t); break; default: console.warn("THREE.GTAOPass: Unknown output type."); } } // internals _renderPass(e, t, i, s, n) { e.getClearColor(this._originalClearColor); const a = e.getClearAlpha(), o = e.autoClear; e.setRenderTarget(i), e.autoClear = !1, s != null && (e.setClearColor(s), e.setClearAlpha(n || 0), e.clear()), this._fsQuad.material = t, this._fsQuad.render(e), e.autoClear = o, e.setClearColor(this._originalClearColor), e.setClearAlpha(a); } _renderOverride(e, t, i, s, n) { e.getClearColor(this._originalClearColor); const a = e.getClearAlpha(), o = e.autoClear; e.setRenderTarget(i), e.autoClear = !1, s = t.clearColor || s, n = t.clearAlpha || n, s != null && (e.setClearColor(s), e.setClearAlpha(n || 0), e.clear()), this.scene.overrideMaterial = t, e.render(this.scene, this.camera), this.scene.overrideMaterial = null, e.autoClear = o, e.setClearColor(this._originalClearColor), e.setClearAlpha(a); } _overrideVisibility() { const e = this.scene, t = this._visibilityCache; e.traverse(function(i) { (i.isPoints || i.isLine || i.isLine2) && i.visible && (i.visible = !1, t.push(i)); }); } _restoreVisibility() { const e = this._visibilityCache; for (let t = 0; t < e.length; t++) e[t].visible = !0; e.length = 0; } _generateNoise(e = 64) { const t = new c0(), i = e * e * 4, s = new Uint8Array(i); for (let a = 0; a < e; a++) for (let o = 0; o < e; o++) { const l = a, c = o; s[(a * e + o) * 4] = (t.noise(l, c) * 0.5 + 0.5) * 255, s[(a * e + o) * 4 + 1] = (t.noise(l + e, c) * 0.5 + 0.5) * 255, s[(a * e + o) * 4 + 2] = (t.noise(l, c + e) * 0.5 + 0.5) * 255, s[(a * e + o) * 4 + 3] = (t.noise(l + e, c + e) * 0.5 + 0.5) * 255; } const n = new es(s, e, e, qt, fi); return n.wrapS = Ei, n.wrapT = Ei, n.needsUpdate = !0, n; } } ai.OUTPUT = { Off: -1, Default: 0, Diffuse: 1, Depth: 2, Normal: 3, AO: 4, Denoise: 5 }; const h0 = { uniforms: { tDiffuse: { value: null }, luminosityThreshold: { value: 1 }, smoothWidth: { value: 1 }, defaultColor: { value: new _e(0) }, defaultOpacity: { value: 0 } }, vertexShader: ( /* glsl */ ` varying vec2 vUv; void main() { vUv = uv; gl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 ); }` ), fragmentShader: ( /* glsl */ ` uniform sampler2D tDiffuse; uniform vec3 defaultColor; uniform float defaultOpacity; uniform float luminosityThreshold; uniform float smoothWidth; varying vec2 vUv; void main() { vec4 texel = texture2D( tDiffuse, vUv ); float v = luminance( texel.xyz ); vec4 outputColor = vec4( defaultColor.rgb, defaultOpacity ); float alpha = smoothstep( luminosityThreshold, luminosityThreshold + smoothWidth, v ); gl_FragColor = mix( outputColor, texel, alpha ); }` ) }; class $r extends tr { /** * Constructs a new Unreal Bloom pass. * * @param {Vector2} [resolution] - The effect's resolution. * @param {number} [strength=1] - The Bloom strength. * @param {number} radius - The Bloom radius. * @param {number} threshold - The luminance threshold limits which bright areas contribute to the Bloom effect. */ constructor(e, t = 1, i, s) { super(), this.strength = t, this.radius = i, this.threshold = s, this.resolution = e !== void 0 ? new oe(e.x, e.y) : new oe(256, 256), this.clearColor = new _e(0, 0, 0), this.needsSwap = !1, this.renderTargetsHorizontal = [], this.renderTargetsVertical = [], this.nMips = 5; let n = Math.round(this.resolution.x / 2), a = Math.round(this.resolution.y / 2); this.renderTargetBright = new _t(n, a, { type: ft }), this.renderTargetBright.texture.name = "UnrealBloomPass.bright", this.renderTargetBright.texture.generateMipmaps = !1; for (let h = 0; h < this.nMips; h++) { const u = new _t(n, a, { type: ft }); u.texture.name = "UnrealBloomPass.h" + h, u.texture.generateMipmaps = !1, this.renderTargetsHorizontal.push(u); const d = new _t(n, a, { type: ft }); d.texture.name = "UnrealBloomPass.v" + h, d.texture.generateMipmaps = !1, this.renderTargetsVertical.push(d), n = Math.round(n / 2), a = Math.round(a / 2); } const o = h0; this.highPassUniforms = ui.clone(o.uniforms), this.highPassUniforms.luminosityThreshold.value = s, this.highPassUniforms.smoothWidth.value = 0.01, this.materialHighPassFilter = new ct({ uniforms: this.highPassUniforms, vertexShader: o.vertexShader, fragmentShader: o.fragmentShader }), this.separableBlurMaterials = []; const l = [6, 10, 14, 18, 22]; n = Math.round(this.resolution.x / 2), a = Math.round(this.resolution.y / 2); for (let h = 0; h < this.nMips; h++) this.separableBlurMaterials.push(this._getSeparableBlurMaterial(l[h])), this.separableBlurMaterials[h].uniforms.invSize.value = new oe(1 / n, 1 / a), n = Math.round(n / 2), a = Math.round(a / 2); this.compositeMaterial = this._getCompositeMaterial(this.nMips), this.compositeMaterial.uniforms.blurTexture1.value = this.renderTargetsVertical[0].texture, this.compositeMaterial.uniforms.blurTexture2.value = this.renderTargetsVertical[1].texture, this.compositeMaterial.uniforms.blurTexture3.value = this.renderTargetsVertical[2].texture, this.compositeMaterial.uniforms.blurTexture4.value = this.renderTargetsVertical[3].texture, this.compositeMaterial.uniforms.blurTexture5.value = this.renderTargetsVertical[4].texture, this.compositeMaterial.uniforms.bloomStrength.value = t, this.compositeMaterial.uniforms.bloomRadius.value = 0.1; const c = [1, 0.8, 0.6, 0.4, 0.2]; this.compositeMaterial.uniforms.bloomFactors.value = c, this.bloomTintColors = [new w(1, 1, 1), new w(1, 1, 1), new w(1, 1, 1), new w(1, 1, 1), new w(1, 1, 1)], this.compositeMaterial.uniforms.bloomTintColors.value = this.bloomTintColors, this.copyUniforms = ui.clone(Qi.uniforms), this.blendMaterial = new ct({ uniforms: this.copyUniforms, vertexShader: Qi.vertexShader, fragmentShader: Qi.fragmentShader, blending: yn, depthTest: !1, depthWrite: !1, transparent: !0 }), this._oldClearColor = new _e(), this._oldClearAlpha = 1, this._basic = new Bt(), this._fsQuad = new Ds(null); } /** * Frees the GPU-related resources allocated by this instance. Call this * method whenever the pass is no longer used in your app. */ dispose() { for (let e = 0; e < this.renderTargetsHorizontal.length; e++) this.renderTargetsHorizontal[e].dispose(); for (let e = 0; e < this.renderTargetsVertical.length; e++) this.renderTargetsVertical[e].dispose(); this.renderTargetBright.dispose(); for (let e = 0; e < this.separableBlurMaterials.length; e++) this.separableBlurMaterials[e].dispose(); this.compositeMaterial.dispose(), this.blendMaterial.dispose(), this._basic.dispose(), this._fsQuad.dispose(); } /** * Sets the size of the pass. * * @param {number} width - The width to set. * @param {number} height - The height to set. */ setSize(e, t) { let i = Math.round(e / 2), s = Math.round(t / 2); this.renderTargetBright.setSize(i, s); for (let n = 0; n < this.nMips; n++) this.renderTargetsHorizontal[n].setSize(i, s), this.renderTargetsVertical[n].setSize(i, s), this.separableBlurMaterials[n].uniforms.invSize.value = new oe(1 / i, 1 / s), i = Math.round(i / 2), s = Math.round(s / 2); } /** * Performs the Bloom pass. * * @param {WebGLRenderer} renderer - The renderer. * @param {WebGLRenderTarget} writeBuffer - The write buffer. This buffer is intended as the rendering * destination for the pass. * @param {WebGLRenderTarget} readBuffer - The read buffer. The pass can access the result from the * previous pass from this buffer. * @param {number} deltaTime - The delta time in seconds. * @param {boolean} maskActive - Whether masking is active or not. */ render(e, t, i, s, n) { e.getClearColor(this._oldClearColor), this._oldClearAlpha = e.getClearAlpha(); const a = e.autoClear; e.autoClear = !1, e.setClearColor(this.clearColor, 0), n && e.state.buffers.stencil.setTest(!1), this.renderToScreen && (this._fsQuad.material = this._basic, this._basic.map = i.texture, e.setRenderTarget(null), e.clear(), this._fsQuad.render(e)), this.highPassUniforms.tDiffuse.value = i.texture, this.highPassUniforms.luminosityThreshold.value = this.threshold, this._fsQuad.material = this.materialHighPassFilter, e.setRenderTarget(this.renderTargetBright), e.clear(), this._fsQuad.render(e); let o = this.renderTargetBright; for (let l = 0; l < this.nMips; l++) this._fsQuad.material = this.separableBlurMaterials[l], this.separableBlurMaterials[l].uniforms.colorTexture.value = o.texture, this.separableBlurMaterials[l].uniforms.direction.value = $r.BlurDirectionX, e.setRenderTarget(this.renderTargetsHorizontal[l]), e.clear(), this._fsQuad.render(e), this.separableBlurMaterials[l].uniforms.colorTexture.value = this.renderTargetsHorizontal[l].texture, this.separableBlurMaterials[l].uniforms.direction.value = $r.BlurDirectionY, e.setRenderTarget(this.renderTargetsVertical[l]), e.clear(), this._fsQuad.render(e), o = this.renderTargetsVertical[l]; this._fsQuad.material = this.compositeMaterial, this.compositeMaterial.uniforms.bloomStrength.value = this.strength, this.compositeMaterial.uniforms.bloomRadius.value = this.radius, this.compositeMaterial.uniforms.bloomTintColors.value = this.bloomTintColors, e.setRenderTarget(this.renderTargetsHorizontal[0]), e.clear(), this._fsQuad.render(e), this._fsQuad.material = this.blendMaterial, this.copyUniforms.tDiffuse.value = this.renderTargetsHorizontal[0].texture, n && e.state.buffers.stencil.setTest(!0), this.renderToScreen ? (e.setRenderTarget(null), this._fsQuad.render(e)) : (e.setRenderTarget(i), this._fsQuad.render(e)), e.setClearColor(this._oldClearColor, this._oldClearAlpha), e.autoClear = a; } // internals _getSeparableBlurMaterial(e) { const t = [], i = e / 3; for (let s = 0; s < e; s++) t.push(0.39894 * Math.exp(-0.5 * s * s / (i * i)) / i); return new ct({ defines: { KERNEL_RADIUS: e }, uniforms: { colorTexture: { value: null }, invSize: { value: new oe(0.5, 0.5) }, // inverse texture size direction: { value: new oe(0.5, 0.5) }, gaussianCoefficients: { value: t } // precomputed Gaussian coefficients }, vertexShader: `varying vec2 vUv; void main() { vUv = uv; gl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 ); }`, fragmentShader: `#include varying vec2 vUv; uniform sampler2D colorTexture; uniform vec2 invSize; uniform vec2 direction; uniform float gaussianCoefficients[KERNEL_RADIUS]; void main() { float weightSum = gaussianCoefficients[0]; vec3 diffuseSum = texture2D( colorTexture, vUv ).rgb * weightSum; for( int i = 1; i < KERNEL_RADIUS; i ++ ) { float x = float(i); float w = gaussianCoefficients[i]; vec2 uvOffset = direction * invSize * x; vec3 sample1 = texture2D( colorTexture, vUv + uvOffset ).rgb; vec3 sample2 = texture2D( colorTexture, vUv - uvOffset ).rgb; diffuseSum += ( sample1 + sample2 ) * w; } gl_FragColor = vec4( diffuseSum, 1.0 ); }` }); } _getCompositeMaterial(e) { return new ct({ defines: { NUM_MIPS: e }, uniforms: { blurTexture1: { value: null }, blurTexture2: { value: null }, blurTexture3: { value: null }, blurTexture4: { value: null }, blurTexture5: { value: null }, bloomStrength: { value: 1 }, bloomFactors: { value: null }, bloomTintColors: { value: null }, bloomRadius: { value: 0 } }, vertexShader: `varying vec2 vUv; void main() { vUv = uv; gl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 ); }`, fragmentShader: `varying vec2 vUv; uniform sampler2D blurTexture1; uniform sampler2D blurTexture2; uniform sampler2D blurTexture3; uniform sampler2D blurTexture4; uniform sampler2D blurTexture5; uniform float bloomStrength; uniform float bloomRadius; uniform float bloomFactors[NUM_MIPS]; uniform vec3 bloomTintColors[NUM_MIPS]; float lerpBloomFactor(const in float factor) { float mirrorFactor = 1.2 - factor; return mix(factor, mirrorFactor, bloomRadius); } void main() { gl_FragColor = bloomStrength * ( lerpBloomFactor(bloomFactors[0]) * vec4(bloomTintColors[0], 1.0) * texture2D(blurTexture1, vUv) + lerpBloomFactor(bloomFactors[1]) * vec4(bloomTintColors[1], 1.0) * texture2D(blurTexture2, vUv) + lerpBloomFactor(bloomFactors[2]) * vec4(bloomTintColors[2], 1.0) * texture2D(blurTexture3, vUv) + lerpBloomFactor(bloomFactors[3]) * vec4(bloomTintColors[3], 1.0) * texture2D(blurTexture4, vUv) + lerpBloomFactor(bloomFactors[4]) * vec4(bloomTintColors[4], 1.0) * texture2D(blurTexture5, vUv) ); }` }); } } $r.BlurDirectionX = new oe(1, 0); $r.BlurDirectionY = new oe(0, 1); const un = { name: "OutputShader", uniforms: { tDiffuse: { value: null }, toneMappingExposure: { value: 1 } }, vertexShader: ( /* glsl */ ` precision highp float; uniform mat4 modelViewMatrix; uniform mat4 projectionMatrix; attribute vec3 position; attribute vec2 uv; varying vec2 vUv; void main() { vUv = uv; gl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 ); }` ), fragmentShader: ( /* glsl */ ` precision highp float; uniform sampler2D tDiffuse; #include #include varying vec2 vUv; void main() { gl_FragColor = texture2D( tDiffuse, vUv ); // tone mapping #ifdef LINEAR_TONE_MAPPING gl_FragColor.rgb = LinearToneMapping( gl_FragColor.rgb ); #elif defined( REINHARD_TONE_MAPPING ) gl_FragColor.rgb = ReinhardToneMapping( gl_FragColor.rgb ); #elif defined( CINEON_TONE_MAPPING ) gl_FragColor.rgb = CineonToneMapping( gl_FragColor.rgb ); #elif defined( ACES_FILMIC_TONE_MAPPING ) gl_FragColor.rgb = ACESFilmicToneMapping( gl_FragColor.rgb ); #elif defined( AGX_TONE_MAPPING ) gl_FragColor.rgb = AgXToneMapping( gl_FragColor.rgb ); #elif defined( NEUTRAL_TONE_MAPPING ) gl_FragColor.rgb = NeutralToneMapping( gl_FragColor.rgb ); #elif defined( CUSTOM_TONE_MAPPING ) gl_FragColor.rgb = CustomToneMapping( gl_FragColor.rgb ); #endif // color space #ifdef SRGB_TRANSFER gl_FragColor = sRGBTransferOETF( gl_FragColor ); #endif }` ) }; class u0 extends tr { /** * Constructs a new output pass. */ constructor() { super(), this.uniforms = ui.clone(un.uniforms), this.material = new Pd({ name: un.name, uniforms: this.uniforms, vertexShader: un.vertexShader, fragmentShader: un.fragmentShader }), this._fsQuad = new Ds(this.material), this._outputColorSpace = null, this._toneMapping = null; } /** * Performs the output pass. * * @param {WebGLRenderer} renderer - The renderer. * @param {WebGLRenderTarget} writeBuffer - The write buffer. This buffer is intended as the rendering * destination for the pass. * @param {WebGLRenderTarget} readBuffer - The read buffer. The pass can access the result from the * previous pass from this buffer. * @param {number} deltaTime - The delta time in seconds. * @param {boolean} maskActive - Whether masking is active or not. */ render(e, t, i) { this.uniforms.tDiffuse.value = i.texture, this.uniforms.toneMappingExposure.value = e.toneMappingExposure, (this._outputColorSpace !== e.outputColorSpace || this._toneMapping !== e.toneMapping) && (this._outputColorSpace = e.outputColorSpace, this._toneMapping = e.toneMapping, this.material.defines = {}, Xe.getTransfer(this._outputColorSpace) === et && (this.material.defines.SRGB_TRANSFER = ""), this._toneMapping === kc ? this.material.defines.LINEAR_TONE_MAPPING = "" : this._toneMapping === Hc ? this.material.defines.REINHARD_TONE_MAPPING = "" : this._toneMapping === Vc ? this.material.defines.CINEON_TONE_MAPPING = "" : this._toneMapping === Eo ? this.material.defines.ACES_FILMIC_TONE_MAPPING = "" : this._toneMapping === Wc ? this.material.defines.AGX_TONE_MAPPING = "" : this._toneMapping === jc ? this.material.defines.NEUTRAL_TONE_MAPPING = "" : this._toneMapping === Gc && (this.material.defines.CUSTOM_TONE_MAPPING = ""), this.material.needsUpdate = !0), this.renderToScreen === !0 ? (e.setRenderTarget(null), this._fsQuad.render(e)) : (e.setRenderTarget(t), this.clear && e.clear(e.autoClearColor, e.autoClearDepth, e.autoClearStencil), this._fsQuad.render(e)); } /** * Frees the GPU-related resources allocated by this instance. Call this * method whenever the pass is no longer used in your app. */ dispose() { this.material.dispose(), this._fsQuad.dispose(); } } const d0 = { name: "FXAAShader", uniforms: { tDiffuse: { value: null }, resolution: { value: new oe(1 / 1024, 1 / 512) } }, vertexShader: ( /* glsl */ ` varying vec2 vUv; void main() { vUv = uv; gl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 ); }` ), fragmentShader: ( /* glsl */ ` uniform sampler2D tDiffuse; uniform vec2 resolution; varying vec2 vUv; #define EDGE_STEP_COUNT 6 #define EDGE_GUESS 8.0 #define EDGE_STEPS 1.0, 1.5, 2.0, 2.0, 2.0, 4.0 const float edgeSteps[EDGE_STEP_COUNT] = float[EDGE_STEP_COUNT]( EDGE_STEPS ); float _ContrastThreshold = 0.0312; float _RelativeThreshold = 0.063; float _SubpixelBlending = 1.0; vec4 Sample( sampler2D tex2D, vec2 uv ) { return texture( tex2D, uv ); } float SampleLuminance( sampler2D tex2D, vec2 uv ) { return dot( Sample( tex2D, uv ).rgb, vec3( 0.3, 0.59, 0.11 ) ); } float SampleLuminance( sampler2D tex2D, vec2 texSize, vec2 uv, float uOffset, float vOffset ) { uv += texSize * vec2(uOffset, vOffset); return SampleLuminance(tex2D, uv); } struct LuminanceData { float m, n, e, s, w; float ne, nw, se, sw; float highest, lowest, contrast; }; LuminanceData SampleLuminanceNeighborhood( sampler2D tex2D, vec2 texSize, vec2 uv ) { LuminanceData l; l.m = SampleLuminance( tex2D, uv ); l.n = SampleLuminance( tex2D, texSize, uv, 0.0, 1.0 ); l.e = SampleLuminance( tex2D, texSize, uv, 1.0, 0.0 ); l.s = SampleLuminance( tex2D, texSize, uv, 0.0, -1.0 ); l.w = SampleLuminance( tex2D, texSize, uv, -1.0, 0.0 ); l.ne = SampleLuminance( tex2D, texSize, uv, 1.0, 1.0 ); l.nw = SampleLuminance( tex2D, texSize, uv, -1.0, 1.0 ); l.se = SampleLuminance( tex2D, texSize, uv, 1.0, -1.0 ); l.sw = SampleLuminance( tex2D, texSize, uv, -1.0, -1.0 ); l.highest = max( max( max( max( l.n, l.e ), l.s ), l.w ), l.m ); l.lowest = min( min( min( min( l.n, l.e ), l.s ), l.w ), l.m ); l.contrast = l.highest - l.lowest; return l; } bool ShouldSkipPixel( LuminanceData l ) { float threshold = max( _ContrastThreshold, _RelativeThreshold * l.highest ); return l.contrast < threshold; } float DeterminePixelBlendFactor( LuminanceData l ) { float f = 2.0 * ( l.n + l.e + l.s + l.w ); f += l.ne + l.nw + l.se + l.sw; f *= 1.0 / 12.0; f = abs( f - l.m ); f = clamp( f / l.contrast, 0.0, 1.0 ); float blendFactor = smoothstep( 0.0, 1.0, f ); return blendFactor * blendFactor * _SubpixelBlending; } struct EdgeData { bool isHorizontal; float pixelStep; float oppositeLuminance, gradient; }; EdgeData DetermineEdge( vec2 texSize, LuminanceData l ) { EdgeData e; float horizontal = abs( l.n + l.s - 2.0 * l.m ) * 2.0 + abs( l.ne + l.se - 2.0 * l.e ) + abs( l.nw + l.sw - 2.0 * l.w ); float vertical = abs( l.e + l.w - 2.0 * l.m ) * 2.0 + abs( l.ne + l.nw - 2.0 * l.n ) + abs( l.se + l.sw - 2.0 * l.s ); e.isHorizontal = horizontal >= vertical; float pLuminance = e.isHorizontal ? l.n : l.e; float nLuminance = e.isHorizontal ? l.s : l.w; float pGradient = abs( pLuminance - l.m ); float nGradient = abs( nLuminance - l.m ); e.pixelStep = e.isHorizontal ? texSize.y : texSize.x; if (pGradient < nGradient) { e.pixelStep = -e.pixelStep; e.oppositeLuminance = nLuminance; e.gradient = nGradient; } else { e.oppositeLuminance = pLuminance; e.gradient = pGradient; } return e; } float DetermineEdgeBlendFactor( sampler2D tex2D, vec2 texSize, LuminanceData l, EdgeData e, vec2 uv ) { vec2 uvEdge = uv; vec2 edgeStep; if (e.isHorizontal) { uvEdge.y += e.pixelStep * 0.5; edgeStep = vec2( texSize.x, 0.0 ); } else { uvEdge.x += e.pixelStep * 0.5; edgeStep = vec2( 0.0, texSize.y ); } float edgeLuminance = ( l.m + e.oppositeLuminance ) * 0.5; float gradientThreshold = e.gradient * 0.25; vec2 puv = uvEdge + edgeStep * edgeSteps[0]; float pLuminanceDelta = SampleLuminance( tex2D, puv ) - edgeLuminance; bool pAtEnd = abs( pLuminanceDelta ) >= gradientThreshold; for ( int i = 1; i < EDGE_STEP_COUNT && !pAtEnd; i++ ) { puv += edgeStep * edgeSteps[i]; pLuminanceDelta = SampleLuminance( tex2D, puv ) - edgeLuminance; pAtEnd = abs( pLuminanceDelta ) >= gradientThreshold; } if ( !pAtEnd ) { puv += edgeStep * EDGE_GUESS; } vec2 nuv = uvEdge - edgeStep * edgeSteps[0]; float nLuminanceDelta = SampleLuminance( tex2D, nuv ) - edgeLuminance; bool nAtEnd = abs( nLuminanceDelta ) >= gradientThreshold; for ( int i = 1; i < EDGE_STEP_COUNT && !nAtEnd; i++ ) { nuv -= edgeStep * edgeSteps[i]; nLuminanceDelta = SampleLuminance( tex2D, nuv ) - edgeLuminance; nAtEnd = abs( nLuminanceDelta ) >= gradientThreshold; } if ( !nAtEnd ) { nuv -= edgeStep * EDGE_GUESS; } float pDistance, nDistance; if ( e.isHorizontal ) { pDistance = puv.x - uv.x; nDistance = uv.x - nuv.x; } else { pDistance = puv.y - uv.y; nDistance = uv.y - nuv.y; } float shortestDistance; bool deltaSign; if ( pDistance <= nDistance ) { shortestDistance = pDistance; deltaSign = pLuminanceDelta >= 0.0; } else { shortestDistance = nDistance; deltaSign = nLuminanceDelta >= 0.0; } if ( deltaSign == ( l.m - edgeLuminance >= 0.0 ) ) { return 0.0; } return 0.5 - shortestDistance / ( pDistance + nDistance ); } vec4 ApplyFXAA( sampler2D tex2D, vec2 texSize, vec2 uv ) { LuminanceData luminance = SampleLuminanceNeighborhood( tex2D, texSize, uv ); if ( ShouldSkipPixel( luminance ) ) { return Sample( tex2D, uv ); } float pixelBlend = DeterminePixelBlendFactor( luminance ); EdgeData edge = DetermineEdge( texSize, luminance ); float edgeBlend = DetermineEdgeBlendFactor( tex2D, texSize, luminance, edge, uv ); float finalBlend = max( pixelBlend, edgeBlend ); if (edge.isHorizontal) { uv.y += edge.pixelStep * finalBlend; } else { uv.x += edge.pixelStep * finalBlend; } return Sample( tex2D, uv ); } void main() { gl_FragColor = ApplyFXAA( tDiffuse, resolution.xy, vUv ); }` ) }; function p0(r) { return r && r.__esModule && Object.prototype.hasOwnProperty.call(r, "default") ? r.default : r; } var xo = { exports: {} }, f0 = xo.exports, Tc; function m0() { return Tc || (Tc = 1, (function(r, e) { (function(t, i) { r.exports = i(); })(f0, function() { var t = function() { function i(f) { return a.appendChild(f.dom), f; } function s(f) { for (var g = 0; g < a.children.length; g++) a.children[g].style.display = g === f ? "block" : "none"; n = f; } var n = 0, a = document.createElement("div"); a.style.cssText = "position:fixed;top:0;left:0;cursor:pointer;opacity:0.9;z-index:10000", a.addEventListener("click", function(f) { f.preventDefault(), s(++n % a.children.length); }, !1); var o = (performance || Date).now(), l = o, c = 0, h = i(new t.Panel("FPS", "#0ff", "#002")), u = i(new t.Panel("MS", "#0f0", "#020")); if (self.performance && self.performance.memory) var d = i(new t.Panel("MB", "#f08", "#201")); return s(0), { REVISION: 16, dom: a, addPanel: i, showPanel: s, begin: function() { o = (performance || Date).now(); }, end: function() { c++; var f = (performance || Date).now(); if (u.update(f - o, 200), f > l + 1e3 && (h.update(1e3 * c / (f - l), 100), l = f, c = 0, d)) { var g = performance.memory; d.update(g.usedJSHeapSize / 1048576, g.jsHeapSizeLimit / 1048576); } return f; }, update: function() { o = this.end(); }, domElement: a, setMode: s }; }; return t.Panel = function(i, s, n) { var a = 1 / 0, o = 0, l = Math.round, c = l(window.devicePixelRatio || 1), h = 80 * c, u = 48 * c, d = 3 * c, f = 2 * c, g = 3 * c, v = 15 * c, m = 74 * c, p = 30 * c, y = document.createElement("canvas"); y.width = h, y.height = u, y.style.cssText = "width:80px;height:48px"; var _ = y.getContext("2d"); return _.font = "bold " + 9 * c + "px Helvetica,Arial,sans-serif", _.textBaseline = "top", _.fillStyle = n, _.fillRect(0, 0, h, u), _.fillStyle = s, _.fillText(i, d, f), _.fillRect(g, v, m, p), _.fillStyle = n, _.globalAlpha = 0.9, _.fillRect(g, v, m, p), { dom: y, update: function(E, A) { a = Math.min(a, E), o = Math.max(o, E), _.fillStyle = n, _.globalAlpha = 1, _.fillRect(0, 0, h, v), _.fillStyle = s, _.fillText(l(E) + " " + i + " (" + l(a) + "-" + l(o) + ")", d, f), _.drawImage(y, g + c, v, m - c, p, g, v, m - c, p), _.fillRect(g + m - c, v, c, p), _.fillStyle = n, _.globalAlpha = 0.9, _.fillRect(g + m - c, v, c, l((1 - E / A) * p)); } }; }, t; }); })(xo)), xo.exports; } var g0 = m0(); const v0 = /* @__PURE__ */ p0(g0); class _0 { scene; constructor(e) { this.scene = new zo(), this.setupEnvironment(e.backgroundColor), this.setupLights(); } setupEnvironment(e = 15790320) { this.scene.background = new _e(e); } setupLights() { } setBackground(e) { this.scene.background = new _e(e); } getBoundingBox() { const e = new Rt(); return this.scene.traverse((t) => { if (t instanceof nt || t instanceof zi) { const i = new Rt().setFromObject(t); e.union(i); } }), e.isEmpty() && e.setFromCenterAndSize( new w(0, 0, 0), new w(10, 10, 10) ), e; } } const Ec = { type: "change" }, Zo = { type: "start" }, Rh = { type: "end" }, dn = new Qr(), wc = new yi(), x0 = Math.cos(70 * No.DEG2RAD), yt = new w(), Ht = 2 * Math.PI, st = { NONE: -1, ROTATE: 0, DOLLY: 1, PAN: 2, TOUCH_ROTATE: 3, TOUCH_PAN: 4, TOUCH_DOLLY_PAN: 5, TOUCH_DOLLY_ROTATE: 6 }, xa = 1e-6; class Ah extends hp { /** * Constructs a new controls instance. * * @param {Object3D} object - The object that is managed by the controls. * @param {?HTMLElement} domElement - The HTML element used for event listeners. */ constructor(e, t = null) { super(e, t), this.state = st.NONE, this.target = new w(), this.cursor = new w(), 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: Or.ROTATE, MIDDLE: Or.DOLLY, RIGHT: Or.PAN }, this.touches = { ONE: Ur.ROTATE, TWO: Ur.DOLLY_PAN }, this.target0 = this.target.clone(), this.position0 = this.object.position.clone(), this.zoom0 = this.object.zoom, this._domElementKeyEvents = null, this._lastPosition = new w(), this._lastQuaternion = new mi(), this._lastTargetPosition = new w(), this._quat = new mi().setFromUnitVectors(e.up, new w(0, 1, 0)), this._quatInverse = this._quat.clone().invert(), this._spherical = new $l(), this._sphericalDelta = new $l(), this._scale = 1, this._panOffset = new w(), this._rotateStart = new oe(), this._rotateEnd = new oe(), this._rotateDelta = new oe(), this._panStart = new oe(), this._panEnd = new oe(), this._panDelta = new oe(), this._dollyStart = new oe(), this._dollyEnd = new oe(), this._dollyDelta = new oe(), this._dollyDirection = new w(), this._mouse = new oe(), this._performCursorZoom = !1, this._pointers = [], this._pointerPositions = {}, this._controlActive = !1, this._onPointerMove = M0.bind(this), this._onPointerDown = y0.bind(this), this._onPointerUp = S0.bind(this), this._onContextMenu = A0.bind(this), this._onMouseWheel = E0.bind(this), this._onKeyDown = w0.bind(this), this._onTouchStart = C0.bind(this), this._onTouchMove = R0.bind(this), this._onMouseDown = b0.bind(this), this._onMouseMove = T0.bind(this), this._interceptControlDown = P0.bind(this), this._interceptControlUp = D0.bind(this), this.domElement !== null && this.connect(this.domElement), this.update(); } connect(e) { super.connect(e), this.domElement.addEventListener("pointerdown", this._onPointerDown), this.domElement.addEventListener("pointercancel", this._onPointerUp), this.domElement.addEventListener("contextmenu", this._onContextMenu), this.domElement.addEventListener("wheel", this._onMouseWheel, { passive: !1 }), this.domElement.getRootNode().addEventListener("keydown", this._interceptControlDown, { passive: !0, capture: !0 }), this.domElement.style.touchAction = "none"; } disconnect() { this.domElement.removeEventListener("pointerdown", this._onPointerDown), this.domElement.removeEventListener("pointermove", this._onPointerMove), this.domElement.removeEventListener("pointerup", this._onPointerUp), this.domElement.removeEventListener("pointercancel", this._onPointerUp), this.domElement.removeEventListener("wheel", this._onMouseWheel), this.domElement.removeEventListener("contextmenu", this._onContextMenu), this.stopListenToKeyEvents(), this.domElement.getRootNode().removeEventListener("keydown", this._interceptControlDown, { capture: !0 }), this.domElement.style.touchAction = "auto"; } dispose() { this.disconnect(); } /** * Get the current vertical rotation, in radians. * * @return {number} The current vertical rotation, in radians. */ getPolarAngle() { return this._spherical.phi; } /** * Get the current horizontal rotation, in radians. * * @return {number} The current horizontal rotation, in radians. */ getAzimuthalAngle() { return this._spherical.theta; } /** * Returns the distance from the camera to the target. * * @return {number} The distance from the camera to the target. */ getDistance() { return this.object.position.distanceTo(this.target); } /** * Adds key event listeners to the given DOM element. * `window` is a recommended argument for using this method. * * @param {HTMLElement} domElement - The DOM element */ listenToKeyEvents(e) { e.addEventListener("keydown", this._onKeyDown), this._domElementKeyEvents = e; } /** * Removes the key event listener previously defined with `listenToKeyEvents()`. */ stopListenToKeyEvents() { this._domElementKeyEvents !== null && (this._domElementKeyEvents.removeEventListener("keydown", this._onKeyDown), this._domElementKeyEvents = null); } /** * Save the current state of the controls. This can later be recovered with `reset()`. */ saveState() { this.target0.copy(this.target), this.position0.copy(this.object.position), this.zoom0 = this.object.zoom; } /** * Reset the controls to their state from either the last time the `saveState()` * was called, or the initial state. */ reset() { this.target.copy(this.target0), this.object.position.copy(this.position0), this.object.zoom = this.zoom0, this.object.updateProjectionMatrix(), this.dispatchEvent(Ec), this.update(), this.state = st.NONE; } update(e = null) { const t = this.object.position; yt.copy(t).sub(this.target), yt.applyQuaternion(this._quat), this._spherical.setFromVector3(yt), this.autoRotate && this.state === st.NONE && this._rotateLeft(this._getAutoRotationAngle(e)), this.enableDamping ? (this._spherical.theta += this._sphericalDelta.theta * this.dampingFactor, this._spherical.phi += this._sphericalDelta.phi * this.dampingFactor) : (this._spherical.theta += this._sphericalDelta.theta, this._spherical.phi += this._sphericalDelta.phi); let i = this.minAzimuthAngle, s = this.maxAzimuthAngle; isFinite(i) && isFinite(s) && (i < -Math.PI ? i += Ht : i > Math.PI && (i -= Ht), s < -Math.PI ? s += Ht : s > Math.PI && (s -= Ht), i <= s ? this._spherical.theta = Math.max(i, Math.min(s, this._spherical.theta)) : this._spherical.theta = this._spherical.theta > (i + s) / 2 ? Math.max(i, 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 n = !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), n = a != this._spherical.radius; } if (yt.setFromSpherical(this._spherical), yt.applyQuaternion(this._quatInverse), t.copy(this.target).add(yt), 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 = yt.length(); a = this._clampDistance(o * this._scale); const l = o - a; this.object.position.addScaledVector(this._dollyDirection, l), this.object.updateMatrixWorld(), n = !!l; } else if (this.object.isOrthographicCamera) { const o = new w(this._mouse.x, this._mouse.y, 0); o.unproject(this.object); const l = this.object.zoom; this.object.zoom = Math.max(this.minZoom, Math.min(this.maxZoom, this.object.zoom / this._scale)), this.object.updateProjectionMatrix(), n = l !== this.object.zoom; const c = new w(this._mouse.x, this._mouse.y, 0); c.unproject(this.object), this.object.position.sub(c).add(o), this.object.updateMatrixWorld(), a = yt.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) : (dn.origin.copy(this.object.position), dn.direction.set(0, 0, -1).transformDirection(this.object.matrix), Math.abs(this.object.up.dot(dn.direction)) < x0 ? this.object.lookAt(this.target) : (wc.setFromNormalAndCoplanarPoint(this.object.up, this.target), dn.intersectPlane(wc, 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(), n = !0); } return this._scale = 1, this._performCursorZoom = !1, n || this._lastPosition.distanceToSquared(this.object.position) > xa || 8 * (1 - this._lastQuaternion.dot(this.object.quaternion)) > xa || this._lastTargetPosition.distanceToSquared(this.target) > xa ? (this.dispatchEvent(Ec), this._lastPosition.copy(this.object.position), this._lastQuaternion.copy(this.object.quaternion), this._lastTargetPosition.copy(this.target), !0) : !1; } _getAutoRotationAngle(e) { return e !== null ? Ht / 60 * this.autoRotateSpeed * e : Ht / 60 / 60 * this.autoRotateSpeed; } _getZoomScale(e) { const t = Math.abs(e * 0.01); return Math.pow(0.95, this.zoomSpeed * t); } _rotateLeft(e) { this._sphericalDelta.theta -= e; } _rotateUp(e) { this._sphericalDelta.phi -= e; } _panLeft(e, t) { yt.setFromMatrixColumn(t, 0), yt.multiplyScalar(-e), this._panOffset.add(yt); } _panUp(e, t) { this.screenSpacePanning === !0 ? yt.setFromMatrixColumn(t, 1) : (yt.setFromMatrixColumn(t, 0), yt.crossVectors(this.object.up, yt)), yt.multiplyScalar(e), this._panOffset.add(yt); } // deltaX and deltaY are in pixels; right and down are positive _pan(e, t) { const i = this.domElement; if (this.object.isPerspectiveCamera) { const s = this.object.position; yt.copy(s).sub(this.target); let n = yt.length(); n *= Math.tan(this.object.fov / 2 * Math.PI / 180), this._panLeft(2 * e * n / i.clientHeight, this.object.matrix), this._panUp(2 * t * n / i.clientHeight, this.object.matrix); } else this.object.isOrthographicCamera ? (this._panLeft(e * (this.object.right - this.object.left) / this.object.zoom / i.clientWidth, this.object.matrix), this._panUp(t * (this.object.top - this.object.bottom) / this.object.zoom / i.clientHeight, this.object.matrix)) : (console.warn("WARNING: OrbitControls.js encountered an unknown camera type - pan disabled."), this.enablePan = !1); } _dollyOut(e) { this.object.isPerspectiveCamera || this.object.isOrthographicCamera ? this._scale /= e : (console.warn("WARNING: OrbitControls.js encountered an unknown camera type - dolly/zoom disabled."), this.enableZoom = !1); } _dollyIn(e) { this.object.isPerspectiveCamera || this.object.isOrthographicCamera ? this._scale *= e : (console.warn("WARNING: OrbitControls.js encountered an unknown camera type - dolly/zoom disabled."), this.enableZoom = !1); } _updateZoomParameters(e, t) { if (!this.zoomToCursor) return; this._performCursorZoom = !0; const i = this.domElement.getBoundingClientRect(), s = e - i.left, n = t - i.top, a = i.width, o = i.height; this._mouse.x = s / a * 2 - 1, this._mouse.y = -(n / o) * 2 + 1, this._dollyDirection.set(this._mouse.x, this._mouse.y, 1).unproject(this.object).sub(this.object.position).normalize(); } _clampDistance(e) { return Math.max(this.minDistance, Math.min(this.maxDistance, e)); } // // event callbacks - update the object state // _handleMouseDownRotate(e) { this._rotateStart.set(e.clientX, e.clientY); } _handleMouseDownDolly(e) { this._updateZoomParameters(e.clientX, e.clientX), this._dollyStart.set(e.clientX, e.clientY); } _handleMouseDownPan(e) { this._panStart.set(e.clientX, e.clientY); } _handleMouseMoveRotate(e) { this._rotateEnd.set(e.clientX, e.clientY), this._rotateDelta.subVectors(this._rotateEnd, this._rotateStart).multiplyScalar(this.rotateSpeed); const t = this.domElement; this._rotateLeft(Ht * this._rotateDelta.x / t.clientHeight), this._rotateUp(Ht * this._rotateDelta.y / t.clientHeight), this._rotateStart.copy(this._rotateEnd), this.update(); } _handleMouseMoveDolly(e) { this._dollyEnd.set(e.clientX, e.clientY), this._dollyDelta.subVectors(this._dollyEnd, this._dollyStart), this._dollyDelta.y > 0 ? this._dollyOut(this._getZoomScale(this._dollyDelta.y)) : this._dollyDelta.y < 0 && this._dollyIn(this._getZoomScale(this._dollyDelta.y)), this._dollyStart.copy(this._dollyEnd), this.update(); } _handleMouseMovePan(e) { this._panEnd.set(e.clientX, e.clientY), this._panDelta.subVectors(this._panEnd, this._panStart).multiplyScalar(this.panSpeed), this._pan(this._panDelta.x, this._panDelta.y), this._panStart.copy(this._panEnd), this.update(); } _handleMouseWheel(e) { this._updateZoomParameters(e.clientX, e.clientY), e.deltaY < 0 ? this._dollyIn(this._getZoomScale(e.deltaY)) : e.deltaY > 0 && this._dollyOut(this._getZoomScale(e.deltaY)), this.update(); } _handleKeyDown(e) { let t = !1; switch (e.code) { case this.keys.UP: e.ctrlKey || e.metaKey || e.shiftKey ? this.enableRotate && this._rotateUp(Ht * this.keyRotateSpeed / this.domElement.clientHeight) : this.enablePan && this._pan(0, this.keyPanSpeed), t = !0; break; case this.keys.BOTTOM: e.ctrlKey || e.metaKey || e.shiftKey ? this.enableRotate && this._rotateUp(-Ht * this.keyRotateSpeed / this.domElement.clientHeight) : this.enablePan && this._pan(0, -this.keyPanSpeed), t = !0; break; case this.keys.LEFT: e.ctrlKey || e.metaKey || e.shiftKey ? this.enableRotate && this._rotateLeft(Ht * this.keyRotateSpeed / this.domElement.clientHeight) : this.enablePan && this._pan(this.keyPanSpeed, 0), t = !0; break; case this.keys.RIGHT: e.ctrlKey || e.metaKey || e.shiftKey ? this.enableRotate && this._rotateLeft(-Ht * this.keyRotateSpeed / this.domElement.clientHeight) : this.enablePan && this._pan(-this.keyPanSpeed, 0), t = !0; break; } t && (e.preventDefault(), this.update()); } _handleTouchStartRotate(e) { if (this._pointers.length === 1) this._rotateStart.set(e.pageX, e.pageY); else { const t = this._getSecondPointerPosition(e), i = 0.5 * (e.pageX + t.x), s = 0.5 * (e.pageY + t.y); this._rotateStart.set(i, s); } } _handleTouchStartPan(e) { if (this._pointers.length === 1) this._panStart.set(e.pageX, e.pageY); else { const t = this._getSecondPointerPosition(e), i = 0.5 * (e.pageX + t.x), s = 0.5 * (e.pageY + t.y); this._panStart.set(i, s); } } _handleTouchStartDolly(e) { const t = this._getSecondPointerPosition(e), i = e.pageX - t.x, s = e.pageY - t.y, n = Math.sqrt(i * i + s * s); this._dollyStart.set(0, n); } _handleTouchStartDollyPan(e) { this.enableZoom && this._handleTouchStartDolly(e), this.enablePan && this._handleTouchStartPan(e); } _handleTouchStartDollyRotate(e) { this.enableZoom && this._handleTouchStartDolly(e), this.enableRotate && this._handleTouchStartRotate(e); } _handleTouchMoveRotate(e) { if (this._pointers.length == 1) this._rotateEnd.set(e.pageX, e.pageY); else { const i = this._getSecondPointerPosition(e), s = 0.5 * (e.pageX + i.x), n = 0.5 * (e.pageY + i.y); this._rotateEnd.set(s, n); } this._rotateDelta.subVectors(this._rotateEnd, this._rotateStart).multiplyScalar(this.rotateSpeed); const t = this.domElement; this._rotateLeft(Ht * this._rotateDelta.x / t.clientHeight), this._rotateUp(Ht * this._rotateDelta.y / t.clientHeight), this._rotateStart.copy(this._rotateEnd); } _handleTouchMovePan(e) { if (this._pointers.length === 1) this._panEnd.set(e.pageX, e.pageY); else { const t = this._getSecondPointerPosition(e), i = 0.5 * (e.pageX + t.x), s = 0.5 * (e.pageY + t.y); this._panEnd.set(i, 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(e) { const t = this._getSecondPointerPosition(e), i = e.pageX - t.x, s = e.pageY - t.y, n = Math.sqrt(i * i + s * s); this._dollyEnd.set(0, n), this._dollyDelta.set(0, Math.pow(this._dollyEnd.y / this._dollyStart.y, this.zoomSpeed)), this._dollyOut(this._dollyDelta.y), this._dollyStart.copy(this._dollyEnd); const a = (e.pageX + t.x) * 0.5, o = (e.pageY + t.y) * 0.5; this._updateZoomParameters(a, o); } _handleTouchMoveDollyPan(e) { this.enableZoom && this._handleTouchMoveDolly(e), this.enablePan && this._handleTouchMovePan(e); } _handleTouchMoveDollyRotate(e) { this.enableZoom && this._handleTouchMoveDolly(e), this.enableRotate && this._handleTouchMoveRotate(e); } // pointers _addPointer(e) { this._pointers.push(e.pointerId); } _removePointer(e) { delete this._pointerPositions[e.pointerId]; for (let t = 0; t < this._pointers.length; t++) if (this._pointers[t] == e.pointerId) { this._pointers.splice(t, 1); return; } } _isTrackingPointer(e) { for (let t = 0; t < this._pointers.length; t++) if (this._pointers[t] == e.pointerId) return !0; return !1; } _trackPointer(e) { let t = this._pointerPositions[e.pointerId]; t === void 0 && (t = new oe(), this._pointerPositions[e.pointerId] = t), t.set(e.pageX, e.pageY); } _getSecondPointerPosition(e) { const t = e.pointerId === this._pointers[0] ? this._pointers[1] : this._pointers[0]; return this._pointerPositions[t]; } // _customWheelEvent(e) { const t = e.deltaMode, i = { clientX: e.clientX, clientY: e.clientY, deltaY: e.deltaY }; switch (t) { case 1: i.deltaY *= 16; break; case 2: i.deltaY *= 100; break; } return e.ctrlKey && !this._controlActive && (i.deltaY *= 10), i; } } function y0(r) { this.enabled !== !1 && (this._pointers.length === 0 && (this.domElement.setPointerCapture(r.pointerId), this.domElement.addEventListener("pointermove", this._onPointerMove), this.domElement.addEventListener("pointerup", this._onPointerUp)), !this._isTrackingPointer(r) && (this._addPointer(r), r.pointerType === "touch" ? this._onTouchStart(r) : this._onMouseDown(r))); } function M0(r) { this.enabled !== !1 && (r.pointerType === "touch" ? this._onTouchMove(r) : this._onMouseMove(r)); } function S0(r) { switch (this._removePointer(r), this._pointers.length) { case 0: this.domElement.releasePointerCapture(r.pointerId), this.domElement.removeEventListener("pointermove", this._onPointerMove), this.domElement.removeEventListener("pointerup", this._onPointerUp), this.dispatchEvent(Rh), this.state = st.NONE; break; case 1: const e = this._pointers[0], t = this._pointerPositions[e]; this._onTouchStart({ pointerId: e, pageX: t.x, pageY: t.y }); break; } } function b0(r) { let e; switch (r.button) { case 0: e = this.mouseButtons.LEFT; break; case 1: e = this.mouseButtons.MIDDLE; break; case 2: e = this.mouseButtons.RIGHT; break; default: e = -1; } switch (e) { case Or.DOLLY: if (this.enableZoom === !1) return; this._handleMouseDownDolly(r), this.state = st.DOLLY; break; case Or.ROTATE: if (r.ctrlKey || r.metaKey || r.shiftKey) { if (this.enablePan === !1) return; this._handleMouseDownPan(r), this.state = st.PAN; } else { if (this.enableRotate === !1) return; this._handleMouseDownRotate(r), this.state = st.ROTATE; } break; case Or.PAN: if (r.ctrlKey || r.metaKey || r.shiftKey) { if (this.enableRotate === !1) return; this._handleMouseDownRotate(r), this.state = st.ROTATE; } else { if (this.enablePan === !1) return; this._handleMouseDownPan(r), this.state = st.PAN; } break; default: this.state = st.NONE; } this.state !== st.NONE && this.dispatchEvent(Zo); } function T0(r) { switch (this.state) { case st.ROTATE: if (this.enableRotate === !1) return; this._handleMouseMoveRotate(r); break; case st.DOLLY: if (this.enableZoom === !1) return; this._handleMouseMoveDolly(r); break; case st.PAN: if (this.enablePan === !1) return; this._handleMouseMovePan(r); break; } } function E0(r) { this.enabled === !1 || this.enableZoom === !1 || this.state !== st.NONE || (r.preventDefault(), this.dispatchEvent(Zo), this._handleMouseWheel(this._customWheelEvent(r)), this.dispatchEvent(Rh)); } function w0(r) { this.enabled !== !1 && this._handleKeyDown(r); } function C0(r) { switch (this._trackPointer(r), this._pointers.length) { case 1: switch (this.touches.ONE) { case Ur.ROTATE: if (this.enableRotate === !1) return; this._handleTouchStartRotate(r), this.state = st.TOUCH_ROTATE; break; case Ur.PAN: if (this.enablePan === !1) return; this._handleTouchStartPan(r), this.state = st.TOUCH_PAN; break; default: this.state = st.NONE; } break; case 2: switch (this.touches.TWO) { case Ur.DOLLY_PAN: if (this.enableZoom === !1 && this.enablePan === !1) return; this._handleTouchStartDollyPan(r), this.state = st.TOUCH_DOLLY_PAN; break; case Ur.DOLLY_ROTATE: if (this.enableZoom === !1 && this.enableRotate === !1) return; this._handleTouchStartDollyRotate(r), this.state = st.TOUCH_DOLLY_ROTATE; break; default: this.state = st.NONE; } break; default: this.state = st.NONE; } this.state !== st.NONE && this.dispatchEvent(Zo); } function R0(r) { switch (this._trackPointer(r), this.state) { case st.TOUCH_ROTATE: if (this.enableRotate === !1) return; this._handleTouchMoveRotate(r), this.update(); break; case st.TOUCH_PAN: if (this.enablePan === !1) return; this._handleTouchMovePan(r), this.update(); break; case st.TOUCH_DOLLY_PAN: if (this.enableZoom === !1 && this.enablePan === !1) return; this._handleTouchMoveDollyPan(r), this.update(); break; case st.TOUCH_DOLLY_ROTATE: if (this.enableZoom === !1 && this.enableRotate === !1) return; this._handleTouchMoveDollyRotate(r), this.update(); break; default: this.state = st.NONE; } } function A0(r) { this.enabled !== !1 && r.preventDefault(); } function P0(r) { r.key === "Control" && (this._controlActive = !0, this.domElement.getRootNode().addEventListener("keyup", this._interceptControlUp, { passive: !0, capture: !0 })); } function D0(r) { r.key === "Control" && (this._controlActive = !1, this.domElement.getRootNode().removeEventListener("keyup", this._interceptControlUp, { passive: !0, capture: !0 })); } var zr = /* @__PURE__ */ ((r) => (r.Top = "top", r.Bottom = "bottom", r.Left = "left", r.Right = "right", r.Front = "front", r.Back = "back", r.Iso = "iso", r))(zr || {}), Nr = /* @__PURE__ */ ((r) => (r.Perspective = "perspective", r.Orthographic = "orthographic", r))(Nr || {}), An = /* @__PURE__ */ ((r) => (r.Orbit = "orbit", r.FirstPerson = "walk", r.PanOnly = "pan_only", r))(An || {}); class L0 { camera; controls; engineState; constructor(e, t, i, s) { this.engineState = s, this.camera = new Mt(45, t / i, 0.1, 1e4), this.camera.position.set(20, 20, 20), this.controls = new Ah(this.camera, e, this.engineState), this.controls.enableDamping = !0, this.controls.dampingFactor = 0.05; } updateAspect(e, t) { this.camera.aspect = e / t, this.camera.updateProjectionMatrix(); } tick() { this.controls.update(); } setView(e) { const t = this.camera.position.length(); switch (e) { case zr.Top: case "top": this.camera.position.set(0, t, 0); break; case zr.Front: case "front": this.camera.position.set(0, 0, t); break; case zr.Iso: case "iso": this.camera.position.set(t / Math.sqrt(3), t / Math.sqrt(3), t / Math.sqrt(3)); break; } this.camera.lookAt(0, 0, 0), this.controls.update(); } } function Cc(r, e) { if (e === vu) return console.warn("THREE.BufferGeometryUtils.toTrianglesDrawMode(): Geometry already defined as triangles."), r; if (e === ho || e === eh) { let t = r.getIndex(); if (t === null) { const a = [], o = r.getAttribute("position"); if (o !== void 0) { for (let l = 0; l < o.count; l++) a.push(l); r.setIndex(a), t = r.getIndex(); } else return console.error("THREE.BufferGeometryUtils.toTrianglesDrawMode(): Undefined position attribute. Processing not possible."), r; } const i = t.count - 2, s = []; if (e === ho) for (let a = 1; a <= i; a++) s.push(t.getX(0)), s.push(t.getX(a)), s.push(t.getX(a + 1)); else for (let a = 0; a < i; a++) a % 2 === 0 ? (s.push(t.getX(a)), s.push(t.getX(a + 1)), s.push(t.getX(a + 2))) : (s.push(t.getX(a + 2)), s.push(t.getX(a + 1)), s.push(t.getX(a))); s.length / 3 !== i && console.error("THREE.BufferGeometryUtils.toTrianglesDrawMode(): Unable to generate correct amount of triangles."); const n = r.clone(); return n.setIndex(s), n.clearGroups(), n; } else return console.error("THREE.BufferGeometryUtils.toTrianglesDrawMode(): Unknown draw mode:", e), r; } class Ph extends er { /** * Constructs a new glTF loader. * * @param {LoadingManager} [manager] - The loading manager. */ constructor(e) { super(e), this.dracoLoader = null, this.ktx2Loader = null, this.meshoptDecoder = null, this.pluginCallbacks = [], this.register(function(t) { return new B0(t); }), this.register(function(t) { return new F0(t); }), this.register(function(t) { return new q0(t); }), this.register(function(t) { return new Y0(t); }), this.register(function(t) { return new K0(t); }), this.register(function(t) { return new k0(t); }), this.register(function(t) { return new H0(t); }), this.register(function(t) { return new V0(t); }), this.register(function(t) { return new G0(t); }), this.register(function(t) { return new O0(t); }), this.register(function(t) { return new W0(t); }), this.register(function(t) { return new z0(t); }), this.register(function(t) { return new X0(t); }), this.register(function(t) { return new j0(t); }), this.register(function(t) { return new U0(t); }), this.register(function(t) { return new Z0(t); }), this.register(function(t) { return new J0(t); }); } /** * Starts loading from the given URL and passes the loaded glTF asset * to the `onLoad()` callback. * * @param {string} url - The path/URL of the file to be loaded. This can also be a data URI. * @param {function(GLTFLoader~LoadObject)} onLoad - Executed when the loading process has been finished. * @param {onProgressCallback} onProgress - Executed while the loading is in progress. * @param {onErrorCallback} onError - Executed when errors occur. */ load(e, t, i, s) { const n = this; let a; if (this.resourcePath !== "") a = this.resourcePath; else if (this.path !== "") { const c = Ms.extractUrlBase(e); a = Ms.resolveURL(c, this.path); } else a = Ms.extractUrlBase(e); this.manager.itemStart(e); const o = function(c) { s ? s(c) : console.error(c), n.manager.itemError(e), n.manager.itemEnd(e); }, l = new Xo(this.manager); l.setPath(this.path), l.setResponseType("arraybuffer"), l.setRequestHeader(this.requestHeader), l.setWithCredentials(this.withCredentials), l.load(e, function(c) { try { n.parse(c, a, function(h) { t(h), n.manager.itemEnd(e); }, o); } catch (h) { o(h); } }, i, o); } /** * Sets the given Draco loader to this loader. Required for decoding assets * compressed with the `KHR_draco_mesh_compression` extension. * * @param {DRACOLoader} dracoLoader - The Draco loader to set. * @return {GLTFLoader} A reference to this loader. */ setDRACOLoader(e) { return this.dracoLoader = e, this; } /** * Sets the given KTX2 loader to this loader. Required for loading KTX2 * compressed textures. * * @param {KTX2Loader} ktx2Loader - The KTX2 loader to set. * @return {GLTFLoader} A reference to this loader. */ setKTX2Loader(e) { return this.ktx2Loader = e, this; } /** * Sets the given meshopt decoder. Required for decoding assets * compressed with the `EXT_meshopt_compression` extension. * * @param {Object} meshoptDecoder - The meshopt decoder to set. * @return {GLTFLoader} A reference to this loader. */ setMeshoptDecoder(e) { return this.meshoptDecoder = e, this; } /** * Registers a plugin callback. This API is internally used to implement the various * glTF extensions but can also used by third-party code to add additional logic * to the loader. * * @param {function(parser:GLTFParser)} callback - The callback function to register. * @return {GLTFLoader} A reference to this loader. */ register(e) { return this.pluginCallbacks.indexOf(e) === -1 && this.pluginCallbacks.push(e), this; } /** * Unregisters a plugin callback. * * @param {Function} callback - The callback function to unregister. * @return {GLTFLoader} A reference to this loader. */ unregister(e) { return this.pluginCallbacks.indexOf(e) !== -1 && this.pluginCallbacks.splice(this.pluginCallbacks.indexOf(e), 1), this; } /** * Parses the given FBX data and returns the resulting group. * * @param {string|ArrayBuffer} data - The raw glTF data. * @param {string} path - The URL base path. * @param {function(GLTFLoader~LoadObject)} onLoad - Executed when the loading process has been finished. * @param {onErrorCallback} onError - Executed when errors occur. */ parse(e, t, i, s) { let n; const a = {}, o = {}, l = new TextDecoder(); if (typeof e == "string") n = JSON.parse(e); else if (e instanceof ArrayBuffer) if (l.decode(new Uint8Array(e, 0, 4)) === Dh) { try { a[Ge.KHR_BINARY_GLTF] = new $0(e); } catch (h) { s && s(h); return; } n = JSON.parse(a[Ge.KHR_BINARY_GLTF].content); } else n = JSON.parse(l.decode(e)); else n = e; if (n.asset === void 0 || n.asset.version[0] < 2) { s && s(new Error("THREE.GLTFLoader: Unsupported asset. glTF versions >=2.0 are supported.")); return; } const c = new u_(n, { path: t || this.resourcePath || "", crossOrigin: this.crossOrigin, requestHeader: this.requestHeader, manager: this.manager, ktx2Loader: this.ktx2Loader, meshoptDecoder: this.meshoptDecoder }); c.fileLoader.setRequestHeader(this.requestHeader); for (let h = 0; h < this.pluginCallbacks.length; h++) { const u = this.pluginCallbacks[h](c); u.name || console.error("THREE.GLTFLoader: Invalid plugin found: missing name"), o[u.name] = u, a[u.name] = !0; } if (n.extensionsUsed) for (let h = 0; h < n.extensionsUsed.length; ++h) { const u = n.extensionsUsed[h], d = n.extensionsRequired || []; switch (u) { case Ge.KHR_MATERIALS_UNLIT: a[u] = new N0(); break; case Ge.KHR_DRACO_MESH_COMPRESSION: a[u] = new Q0(n, this.dracoLoader); break; case Ge.KHR_TEXTURE_TRANSFORM: a[u] = new e_(); break; case Ge.KHR_MESH_QUANTIZATION: a[u] = new t_(); break; default: d.indexOf(u) >= 0 && o[u] === void 0 && console.warn('THREE.GLTFLoader: Unknown extension "' + u + '".'); } } c.setExtensions(a), c.setPlugins(o), c.parse(i, s); } /** * Async version of {@link GLTFLoader#parse}. * * @async * @param {string|ArrayBuffer} data - The raw glTF data. * @param {string} path - The URL base path. * @return {Promise} A Promise that resolves with the loaded glTF when the parsing has been finished. */ parseAsync(e, t) { const i = this; return new Promise(function(s, n) { i.parse(e, t, s, n); }); } } function I0() { let r = {}; return { get: function(e) { return r[e]; }, add: function(e, t) { r[e] = t; }, remove: function(e) { delete r[e]; }, removeAll: function() { r = {}; } }; } const Ge = { KHR_BINARY_GLTF: "KHR_binary_glTF", KHR_DRACO_MESH_COMPRESSION: "KHR_draco_mesh_compression", KHR_LIGHTS_PUNCTUAL: "KHR_lights_punctual", KHR_MATERIALS_CLEARCOAT: "KHR_materials_clearcoat", KHR_MATERIALS_DISPERSION: "KHR_materials_dispersion", KHR_MATERIALS_IOR: "KHR_materials_ior", KHR_MATERIALS_SHEEN: "KHR_materials_sheen", KHR_MATERIALS_SPECULAR: "KHR_materials_specular", KHR_MATERIALS_TRANSMISSION: "KHR_materials_transmission", KHR_MATERIALS_IRIDESCENCE: "KHR_materials_iridescence", KHR_MATERIALS_ANISOTROPY: "KHR_materials_anisotropy", KHR_MATERIALS_UNLIT: "KHR_materials_unlit", KHR_MATERIALS_VOLUME: "KHR_materials_volume", KHR_TEXTURE_BASISU: "KHR_texture_basisu", KHR_TEXTURE_TRANSFORM: "KHR_texture_transform", KHR_MESH_QUANTIZATION: "KHR_mesh_quantization", KHR_MATERIALS_EMISSIVE_STRENGTH: "KHR_materials_emissive_strength", EXT_MATERIALS_BUMP: "EXT_materials_bump", EXT_TEXTURE_WEBP: "EXT_texture_webp", EXT_TEXTURE_AVIF: "EXT_texture_avif", EXT_MESHOPT_COMPRESSION: "EXT_meshopt_compression", EXT_MESH_GPU_INSTANCING: "EXT_mesh_gpu_instancing" }; class U0 { constructor(e) { this.parser = e, this.name = Ge.KHR_LIGHTS_PUNCTUAL, this.cache = { refs: {}, uses: {} }; } _markDefs() { const e = this.parser, t = this.parser.json.nodes || []; for (let i = 0, s = t.length; i < s; i++) { const n = t[i]; n.extensions && n.extensions[this.name] && n.extensions[this.name].light !== void 0 && e._addNodeRef(this.cache, n.extensions[this.name].light); } } _loadLight(e) { const t = this.parser, i = "light:" + e; let s = t.cache.get(i); if (s) return s; const n = t.json, a = ((n.extensions && n.extensions[this.name] || {}).lights || [])[e]; let o; const l = new _e(16777215); a.color !== void 0 && l.setRGB(a.color[0], a.color[1], a.color[2], Ut); const c = a.range !== void 0 ? a.range : 0; switch (a.type) { case "directional": o = new yh(l), o.target.position.set(0, 0, -1), o.add(o.target); break; case "point": o = new Zd(l), o.distance = c; break; case "spot": o = new Yd(l), o.distance = c, a.spot = a.spot || {}, a.spot.innerConeAngle = a.spot.innerConeAngle !== void 0 ? a.spot.innerConeAngle : 0, a.spot.outerConeAngle = a.spot.outerConeAngle !== void 0 ? a.spot.outerConeAngle : Math.PI / 4, o.angle = a.spot.outerConeAngle, o.penumbra = 1 - a.spot.innerConeAngle / a.spot.outerConeAngle, o.target.position.set(0, 0, -1), o.add(o.target); break; default: throw new Error("THREE.GLTFLoader: Unexpected light type: " + a.type); } return o.position.set(0, 0, 0), xi(o, a), a.intensity !== void 0 && (o.intensity = a.intensity), o.name = t.createUniqueName(a.name || "light_" + e), s = Promise.resolve(o), t.cache.add(i, s), s; } getDependency(e, t) { if (e === "light") return this._loadLight(t); } createNodeAttachment(e) { const t = this, i = this.parser, s = i.json.nodes[e], n = (s.extensions && s.extensions[this.name] || {}).light; return n === void 0 ? null : this._loadLight(n).then(function(a) { return i._getNodeRef(t.cache, n, a); }); } } class N0 { constructor() { this.name = Ge.KHR_MATERIALS_UNLIT; } getMaterialType() { return Bt; } extendParams(e, t, i) { const s = []; e.color = new _e(1, 1, 1), e.opacity = 1; const n = t.pbrMetallicRoughness; if (n) { if (Array.isArray(n.baseColorFactor)) { const a = n.baseColorFactor; e.color.setRGB(a[0], a[1], a[2], Ut), e.opacity = a[3]; } n.baseColorTexture !== void 0 && s.push(i.assignTexture(e, "map", n.baseColorTexture, wt)); } return Promise.all(s); } } class O0 { constructor(e) { this.parser = e, this.name = Ge.KHR_MATERIALS_EMISSIVE_STRENGTH; } extendMaterialParams(e, t) { const i = this.parser.json.materials[e]; if (!i.extensions || !i.extensions[this.name]) return Promise.resolve(); const s = i.extensions[this.name].emissiveStrength; return s !== void 0 && (t.emissiveIntensity = s), Promise.resolve(); } } class B0 { constructor(e) { this.parser = e, this.name = Ge.KHR_MATERIALS_CLEARCOAT; } getMaterialType(e) { const t = this.parser.json.materials[e]; return !t.extensions || !t.extensions[this.name] ? null : Ri; } extendMaterialParams(e, t) { const i = this.parser, s = i.json.materials[e]; if (!s.extensions || !s.extensions[this.name]) return Promise.resolve(); const n = [], a = s.extensions[this.name]; if (a.clearcoatFactor !== void 0 && (t.clearcoat = a.clearcoatFactor), a.clearcoatTexture !== void 0 && n.push(i.assignTexture(t, "clearcoatMap", a.clearcoatTexture)), a.clearcoatRoughnessFactor !== void 0 && (t.clearcoatRoughness = a.clearcoatRoughnessFactor), a.clearcoatRoughnessTexture !== void 0 && n.push(i.assignTexture(t, "clearcoatRoughnessMap", a.clearcoatRoughnessTexture)), a.clearcoatNormalTexture !== void 0 && (n.push(i.assignTexture(t, "clearcoatNormalMap", a.clearcoatNormalTexture)), a.clearcoatNormalTexture.scale !== void 0)) { const o = a.clearcoatNormalTexture.scale; t.clearcoatNormalScale = new oe(o, o); } return Promise.all(n); } } class F0 { constructor(e) { this.parser = e, this.name = Ge.KHR_MATERIALS_DISPERSION; } getMaterialType(e) { const t = this.parser.json.materials[e]; return !t.extensions || !t.extensions[this.name] ? null : Ri; } extendMaterialParams(e, t) { const i = this.parser.json.materials[e]; if (!i.extensions || !i.extensions[this.name]) return Promise.resolve(); const s = i.extensions[this.name]; return t.dispersion = s.dispersion !== void 0 ? s.dispersion : 0, Promise.resolve(); } } class z0 { constructor(e) { this.parser = e, this.name = Ge.KHR_MATERIALS_IRIDESCENCE; } getMaterialType(e) { const t = this.parser.json.materials[e]; return !t.extensions || !t.extensions[this.name] ? null : Ri; } extendMaterialParams(e, t) { const i = this.parser, s = i.json.materials[e]; if (!s.extensions || !s.extensions[this.name]) return Promise.resolve(); const n = [], a = s.extensions[this.name]; return a.iridescenceFactor !== void 0 && (t.iridescence = a.iridescenceFactor), a.iridescenceTexture !== void 0 && n.push(i.assignTexture(t, "iridescenceMap", a.iridescenceTexture)), a.iridescenceIor !== void 0 && (t.iridescenceIOR = a.iridescenceIor), t.iridescenceThicknessRange === void 0 && (t.iridescenceThicknessRange = [100, 400]), a.iridescenceThicknessMinimum !== void 0 && (t.iridescenceThicknessRange[0] = a.iridescenceThicknessMinimum), a.iridescenceThicknessMaximum !== void 0 && (t.iridescenceThicknessRange[1] = a.iridescenceThicknessMaximum), a.iridescenceThicknessTexture !== void 0 && n.push(i.assignTexture(t, "iridescenceThicknessMap", a.iridescenceThicknessTexture)), Promise.all(n); } } class k0 { constructor(e) { this.parser = e, this.name = Ge.KHR_MATERIALS_SHEEN; } getMaterialType(e) { const t = this.parser.json.materials[e]; return !t.extensions || !t.extensions[this.name] ? null : Ri; } extendMaterialParams(e, t) { const i = this.parser, s = i.json.materials[e]; if (!s.extensions || !s.extensions[this.name]) return Promise.resolve(); const n = []; t.sheenColor = new _e(0, 0, 0), t.sheenRoughness = 0, t.sheen = 1; const a = s.extensions[this.name]; if (a.sheenColorFactor !== void 0) { const o = a.sheenColorFactor; t.sheenColor.setRGB(o[0], o[1], o[2], Ut); } return a.sheenRoughnessFactor !== void 0 && (t.sheenRoughness = a.sheenRoughnessFactor), a.sheenColorTexture !== void 0 && n.push(i.assignTexture(t, "sheenColorMap", a.sheenColorTexture, wt)), a.sheenRoughnessTexture !== void 0 && n.push(i.assignTexture(t, "sheenRoughnessMap", a.sheenRoughnessTexture)), Promise.all(n); } } class H0 { constructor(e) { this.parser = e, this.name = Ge.KHR_MATERIALS_TRANSMISSION; } getMaterialType(e) { const t = this.parser.json.materials[e]; return !t.extensions || !t.extensions[this.name] ? null : Ri; } extendMaterialParams(e, t) { const i = this.parser, s = i.json.materials[e]; if (!s.extensions || !s.extensions[this.name]) return Promise.resolve(); const n = [], a = s.extensions[this.name]; return a.transmissionFactor !== void 0 && (t.transmission = a.transmissionFactor), a.transmissionTexture !== void 0 && n.push(i.assignTexture(t, "transmissionMap", a.transmissionTexture)), Promise.all(n); } } class V0 { constructor(e) { this.parser = e, this.name = Ge.KHR_MATERIALS_VOLUME; } getMaterialType(e) { const t = this.parser.json.materials[e]; return !t.extensions || !t.extensions[this.name] ? null : Ri; } extendMaterialParams(e, t) { const i = this.parser, s = i.json.materials[e]; if (!s.extensions || !s.extensions[this.name]) return Promise.resolve(); const n = [], a = s.extensions[this.name]; t.thickness = a.thicknessFactor !== void 0 ? a.thicknessFactor : 0, a.thicknessTexture !== void 0 && n.push(i.assignTexture(t, "thicknessMap", a.thicknessTexture)), t.attenuationDistance = a.attenuationDistance || 1 / 0; const o = a.attenuationColor || [1, 1, 1]; return t.attenuationColor = new _e().setRGB(o[0], o[1], o[2], Ut), Promise.all(n); } } class G0 { constructor(e) { this.parser = e, this.name = Ge.KHR_MATERIALS_IOR; } getMaterialType(e) { const t = this.parser.json.materials[e]; return !t.extensions || !t.extensions[this.name] ? null : Ri; } extendMaterialParams(e, t) { const i = this.parser.json.materials[e]; if (!i.extensions || !i.extensions[this.name]) return Promise.resolve(); const s = i.extensions[this.name]; return t.ior = s.ior !== void 0 ? s.ior : 1.5, Promise.resolve(); } } class W0 { constructor(e) { this.parser = e, this.name = Ge.KHR_MATERIALS_SPECULAR; } getMaterialType(e) { const t = this.parser.json.materials[e]; return !t.extensions || !t.extensions[this.name] ? null : Ri; } extendMaterialParams(e, t) { const i = this.parser, s = i.json.materials[e]; if (!s.extensions || !s.extensions[this.name]) return Promise.resolve(); const n = [], a = s.extensions[this.name]; t.specularIntensity = a.specularFactor !== void 0 ? a.specularFactor : 1, a.specularTexture !== void 0 && n.push(i.assignTexture(t, "specularIntensityMap", a.specularTexture)); const o = a.specularColorFactor || [1, 1, 1]; return t.specularColor = new _e().setRGB(o[0], o[1], o[2], Ut), a.specularColorTexture !== void 0 && n.push(i.assignTexture(t, "specularColorMap", a.specularColorTexture, wt)), Promise.all(n); } } class j0 { constructor(e) { this.parser = e, this.name = Ge.EXT_MATERIALS_BUMP; } getMaterialType(e) { const t = this.parser.json.materials[e]; return !t.extensions || !t.extensions[this.name] ? null : Ri; } extendMaterialParams(e, t) { const i = this.parser, s = i.json.materials[e]; if (!s.extensions || !s.extensions[this.name]) return Promise.resolve(); const n = [], a = s.extensions[this.name]; return t.bumpScale = a.bumpFactor !== void 0 ? a.bumpFactor : 1, a.bumpTexture !== void 0 && n.push(i.assignTexture(t, "bumpMap", a.bumpTexture)), Promise.all(n); } } class X0 { constructor(e) { this.parser = e, this.name = Ge.KHR_MATERIALS_ANISOTROPY; } getMaterialType(e) { const t = this.parser.json.materials[e]; return !t.extensions || !t.extensions[this.name] ? null : Ri; } extendMaterialParams(e, t) { const i = this.parser, s = i.json.materials[e]; if (!s.extensions || !s.extensions[this.name]) return Promise.resolve(); const n = [], a = s.extensions[this.name]; return a.anisotropyStrength !== void 0 && (t.anisotropy = a.anisotropyStrength), a.anisotropyRotation !== void 0 && (t.anisotropyRotation = a.anisotropyRotation), a.anisotropyTexture !== void 0 && n.push(i.assignTexture(t, "anisotropyMap", a.anisotropyTexture)), Promise.all(n); } } class q0 { constructor(e) { this.parser = e, this.name = Ge.KHR_TEXTURE_BASISU; } loadTexture(e) { const t = this.parser, i = t.json, s = i.textures[e]; if (!s.extensions || !s.extensions[this.name]) return null; const n = s.extensions[this.name], a = t.options.ktx2Loader; if (!a) { if (i.extensionsRequired && i.extensionsRequired.indexOf(this.name) >= 0) throw new Error("THREE.GLTFLoader: setKTX2Loader must be called before loading KTX2 textures"); return null; } return t.loadTextureImage(e, n.source, a); } } class Y0 { constructor(e) { this.parser = e, this.name = Ge.EXT_TEXTURE_WEBP; } loadTexture(e) { const t = this.name, i = this.parser, s = i.json, n = s.textures[e]; if (!n.extensions || !n.extensions[t]) return null; const a = n.extensions[t], o = s.images[a.source]; let l = i.textureLoader; if (o.uri) { const c = i.options.manager.getHandler(o.uri); c !== null && (l = c); } return i.loadTextureImage(e, a.source, l); } } class K0 { constructor(e) { this.parser = e, this.name = Ge.EXT_TEXTURE_AVIF; } loadTexture(e) { const t = this.name, i = this.parser, s = i.json, n = s.textures[e]; if (!n.extensions || !n.extensions[t]) return null; const a = n.extensions[t], o = s.images[a.source]; let l = i.textureLoader; if (o.uri) { const c = i.options.manager.getHandler(o.uri); c !== null && (l = c); } return i.loadTextureImage(e, a.source, l); } } class Z0 { constructor(e) { this.name = Ge.EXT_MESHOPT_COMPRESSION, this.parser = e; } loadBufferView(e) { const t = this.parser.json, i = t.bufferViews[e]; if (i.extensions && i.extensions[this.name]) { const s = i.extensions[this.name], n = this.parser.getDependency("buffer", s.buffer), a = this.parser.options.meshoptDecoder; if (!a || !a.supported) { if (t.extensionsRequired && t.extensionsRequired.indexOf(this.name) >= 0) throw new Error("THREE.GLTFLoader: setMeshoptDecoder must be called before loading compressed files"); return null; } return n.then(function(o) { const l = s.byteOffset || 0, c = s.byteLength || 0, h = s.count, u = s.byteStride, d = new Uint8Array(o, l, c); return a.decodeGltfBufferAsync ? a.decodeGltfBufferAsync(h, u, d, s.mode, s.filter).then(function(f) { return f.buffer; }) : a.ready.then(function() { const f = new ArrayBuffer(h * u); return a.decodeGltfBuffer(new Uint8Array(f), h, u, d, s.mode, s.filter), f; }); }); } else return null; } } class J0 { constructor(e) { this.name = Ge.EXT_MESH_GPU_INSTANCING, this.parser = e; } createNodeMesh(e) { const t = this.parser.json, i = t.nodes[e]; if (!i.extensions || !i.extensions[this.name] || i.mesh === void 0) return null; const s = t.meshes[i.mesh]; for (const l of s.primitives) if (l.mode !== Zt.TRIANGLES && l.mode !== Zt.TRIANGLE_STRIP && l.mode !== Zt.TRIANGLE_FAN && l.mode !== void 0) return null; const n = i.extensions[this.name].attributes, a = [], o = {}; for (const l in n) a.push(this.parser.getDependency("accessor", n[l]).then((c) => (o[l] = c, o[l]))); return a.length < 1 ? null : (a.push(this.parser.createNodeMesh(e)), Promise.all(a).then((l) => { const c = l.pop(), h = c.isGroup ? c.children : [c], u = l[0].count, d = []; for (const f of h) { const g = new Ue(), v = new w(), m = new mi(), p = new w(1, 1, 1), y = new bd(f.geometry, f.material, u); for (let _ = 0; _ < u; _++) o.TRANSLATION && v.fromBufferAttribute(o.TRANSLATION, _), o.ROTATION && m.fromBufferAttribute(o.ROTATION, _), o.SCALE && p.fromBufferAttribute(o.SCALE, _), y.setMatrixAt(_, g.compose(v, m, p)); for (const _ in o) if (_ === "_COLOR_0") { const E = o[_]; y.instanceColor = new fo(E.array, E.itemSize, E.normalized); } else _ !== "TRANSLATION" && _ !== "ROTATION" && _ !== "SCALE" && f.geometry.setAttribute(_, o[_]); dt.prototype.copy.call(y, f), this.parser.assignFinalMaterial(y), d.push(y); } return c.isGroup ? (c.clear(), c.add(...d), c) : d[0]; })); } } const Dh = "glTF", fs = 12, Rc = { JSON: 1313821514, BIN: 5130562 }; class $0 { constructor(e) { this.name = Ge.KHR_BINARY_GLTF, this.content = null, this.body = null; const t = new DataView(e, 0, fs), i = new TextDecoder(); if (this.header = { magic: i.decode(new Uint8Array(e.slice(0, 4))), version: t.getUint32(4, !0), length: t.getUint32(8, !0) }, this.header.magic !== Dh) throw new Error("THREE.GLTFLoader: Unsupported glTF-Binary header."); if (this.header.version < 2) throw new Error("THREE.GLTFLoader: Legacy binary file detected."); const s = this.header.length - fs, n = new DataView(e, fs); let a = 0; for (; a < s; ) { const o = n.getUint32(a, !0); a += 4; const l = n.getUint32(a, !0); if (a += 4, l === Rc.JSON) { const c = new Uint8Array(e, fs + a, o); this.content = i.decode(c); } else if (l === Rc.BIN) { const c = fs + a; this.body = e.slice(c, c + o); } a += o; } if (this.content === null) throw new Error("THREE.GLTFLoader: JSON content not found."); } } class Q0 { constructor(e, t) { if (!t) throw new Error("THREE.GLTFLoader: No DRACOLoader instance provided."); this.name = Ge.KHR_DRACO_MESH_COMPRESSION, this.json = e, this.dracoLoader = t, this.dracoLoader.preload(); } decodePrimitive(e, t) { const i = this.json, s = this.dracoLoader, n = e.extensions[this.name].bufferView, a = e.extensions[this.name].attributes, o = {}, l = {}, c = {}; for (const h in a) { const u = yo[h] || h.toLowerCase(); o[u] = a[h]; } for (const h in e.attributes) { const u = yo[h] || h.toLowerCase(); if (a[h] !== void 0) { const d = i.accessors[e.attributes[h]], f = kr[d.componentType]; c[u] = f.name, l[u] = d.normalized === !0; } } return t.getDependency("bufferView", n).then(function(h) { return new Promise(function(u, d) { s.decodeDracoFile(h, function(f) { for (const g in f.attributes) { const v = f.attributes[g], m = l[g]; m !== void 0 && (v.normalized = m); } u(f); }, o, c, Ut, d); }); }); } } class e_ { constructor() { this.name = Ge.KHR_TEXTURE_TRANSFORM; } extendTexture(e, t) { return (t.texCoord === void 0 || t.texCoord === e.channel) && t.offset === void 0 && t.rotation === void 0 && t.scale === void 0 || (e = e.clone(), t.texCoord !== void 0 && (e.channel = t.texCoord), t.offset !== void 0 && e.offset.fromArray(t.offset), t.rotation !== void 0 && (e.rotation = t.rotation), t.scale !== void 0 && e.repeat.fromArray(t.scale), e.needsUpdate = !0), e; } } class t_ { constructor() { this.name = Ge.KHR_MESH_QUANTIZATION; } } class Lh extends As { constructor(e, t, i, s) { super(e, t, i, s); } copySampleValue_(e) { const t = this.resultBuffer, i = this.sampleValues, s = this.valueSize, n = e * s * 3 + s; for (let a = 0; a !== s; a++) t[a] = i[n + a]; return t; } interpolate_(e, t, i, s) { const n = this.resultBuffer, a = this.sampleValues, o = this.valueSize, l = o * 2, c = o * 3, h = s - t, u = (i - t) / h, d = u * u, f = d * u, g = e * c, v = g - c, m = -2 * f + 3 * d, p = f - d, y = 1 - m, _ = p - d + u; for (let E = 0; E !== o; E++) { const A = a[v + E + o], T = a[v + E + l] * h, R = a[g + E + o], I = a[g + E] * h; n[E] = y * A + _ * T + m * R + p * I; } return n; } } const i_ = new mi(); class r_ extends Lh { interpolate_(e, t, i, s) { const n = super.interpolate_(e, t, i, s); return i_.fromArray(n).normalize().toArray(n), n; } } const Zt = { POINTS: 0, LINES: 1, LINE_LOOP: 2, LINE_STRIP: 3, TRIANGLES: 4, TRIANGLE_STRIP: 5, TRIANGLE_FAN: 6 }, kr = { 5120: Int8Array, 5121: Uint8Array, 5122: Int16Array, 5123: Uint16Array, 5125: Uint32Array, 5126: Float32Array }, Ac = { 9728: Dt, 9729: xt, 9984: qc, 9985: pn, 9986: gs, 9987: Si }, Pc = { 33071: Jt, 33648: Sn, 10497: Ei }, ya = { SCALAR: 1, VEC2: 2, VEC3: 3, VEC4: 4, MAT2: 4, MAT3: 9, MAT4: 16 }, yo = { POSITION: "position", NORMAL: "normal", TANGENT: "tangent", TEXCOORD_0: "uv", TEXCOORD_1: "uv1", TEXCOORD_2: "uv2", TEXCOORD_3: "uv3", COLOR_0: "color", WEIGHTS_0: "skinWeight", JOINTS_0: "skinIndex" }, Yi = { scale: "scale", translation: "position", rotation: "quaternion", weights: "morphTargetInfluences" }, s_ = { CUBICSPLINE: void 0, // We use a custom interpolant (GLTFCubicSplineInterpolation) for CUBICSPLINE tracks. Each // keyframe track will be initialized with a default interpolation type, then modified. LINEAR: Es, STEP: Ts }, Ma = { OPAQUE: "OPAQUE", MASK: "MASK", BLEND: "BLEND" }; function n_(r) { return r.DefaultMaterial === void 0 && (r.DefaultMaterial = new jo({ color: 16777215, emissive: 0, metalness: 1, roughness: 1, transparent: !1, depthTest: !0, side: Ti })), r.DefaultMaterial; } function hr(r, e, t) { for (const i in t.extensions) r[i] === void 0 && (e.userData.gltfExtensions = e.userData.gltfExtensions || {}, e.userData.gltfExtensions[i] = t.extensions[i]); } function xi(r, e) { e.extras !== void 0 && (typeof e.extras == "object" ? Object.assign(r.userData, e.extras) : console.warn("THREE.GLTFLoader: Ignoring primitive type .extras, " + e.extras)); } function a_(r, e, t) { let i = !1, s = !1, n = !1; for (let c = 0, h = e.length; c < h; c++) { const u = e[c]; if (u.POSITION !== void 0 && (i = !0), u.NORMAL !== void 0 && (s = !0), u.COLOR_0 !== void 0 && (n = !0), i && s && n) break; } if (!i && !s && !n) return Promise.resolve(r); const a = [], o = [], l = []; for (let c = 0, h = e.length; c < h; c++) { const u = e[c]; if (i) { const d = u.POSITION !== void 0 ? t.getDependency("accessor", u.POSITION) : r.attributes.position; a.push(d); } if (s) { const d = u.NORMAL !== void 0 ? t.getDependency("accessor", u.NORMAL) : r.attributes.normal; o.push(d); } if (n) { const d = u.COLOR_0 !== void 0 ? t.getDependency("accessor", u.COLOR_0) : r.attributes.color; l.push(d); } } return Promise.all([ Promise.all(a), Promise.all(o), Promise.all(l) ]).then(function(c) { const h = c[0], u = c[1], d = c[2]; return i && (r.morphAttributes.position = h), s && (r.morphAttributes.normal = u), n && (r.morphAttributes.color = d), r.morphTargetsRelative = !0, r; }); } function o_(r, e) { if (r.updateMorphTargets(), e.weights !== void 0) for (let t = 0, i = e.weights.length; t < i; t++) r.morphTargetInfluences[t] = e.weights[t]; if (e.extras && Array.isArray(e.extras.targetNames)) { const t = e.extras.targetNames; if (r.morphTargetInfluences.length === t.length) { r.morphTargetDictionary = {}; for (let i = 0, s = t.length; i < s; i++) r.morphTargetDictionary[t[i]] = i; } else console.warn("THREE.GLTFLoader: Invalid extras.targetNames length. Ignoring names."); } } function l_(r) { let e; const t = r.extensions && r.extensions[Ge.KHR_DRACO_MESH_COMPRESSION]; if (t ? e = "draco:" + t.bufferView + ":" + t.indices + ":" + Sa(t.attributes) : e = r.indices + ":" + Sa(r.attributes) + ":" + r.mode, r.targets !== void 0) for (let i = 0, s = r.targets.length; i < s; i++) e += ":" + Sa(r.targets[i]); return e; } function Sa(r) { let e = ""; const t = Object.keys(r).sort(); for (let i = 0, s = t.length; i < s; i++) e += t[i] + ":" + r[t[i]] + ";"; return e; } function Mo(r) { switch (r) { case Int8Array: return 1 / 127; case Uint8Array: return 1 / 255; case Int16Array: return 1 / 32767; case Uint16Array: return 1 / 65535; default: throw new Error("THREE.GLTFLoader: Unsupported normalized accessor component type."); } } function c_(r) { return r.search(/\.jpe?g($|\?)/i) > 0 || r.search(/^data\:image\/jpeg/) === 0 ? "image/jpeg" : r.search(/\.webp($|\?)/i) > 0 || r.search(/^data\:image\/webp/) === 0 ? "image/webp" : r.search(/\.ktx2($|\?)/i) > 0 || r.search(/^data\:image\/ktx2/) === 0 ? "image/ktx2" : "image/png"; } const h_ = new Ue(); class u_ { constructor(e = {}, t = {}) { this.json = e, this.extensions = {}, this.plugins = {}, this.options = t, this.cache = new I0(), this.associations = /* @__PURE__ */ new Map(), this.primitiveCache = {}, this.nodeCache = {}, this.meshCache = { refs: {}, uses: {} }, this.cameraCache = { refs: {}, uses: {} }, this.lightCache = { refs: {}, uses: {} }, this.sourceCache = {}, this.textureCache = {}, this.nodeNamesUsed = {}; let i = !1, s = -1, n = !1, a = -1; if (typeof navigator < "u") { const o = navigator.userAgent; i = /^((?!chrome|android).)*safari/i.test(o) === !0; const l = o.match(/Version\/(\d+)/); s = i && l ? parseInt(l[1], 10) : -1, n = o.indexOf("Firefox") > -1, a = n ? o.match(/Firefox\/([0-9]+)\./)[1] : -1; } typeof createImageBitmap > "u" || i && s < 17 || n && a < 98 ? this.textureLoader = new xh(this.options.manager) : this.textureLoader = new $d(this.options.manager), this.textureLoader.setCrossOrigin(this.options.crossOrigin), this.textureLoader.setRequestHeader(this.options.requestHeader), this.fileLoader = new Xo(this.options.manager), this.fileLoader.setResponseType("arraybuffer"), this.options.crossOrigin === "use-credentials" && this.fileLoader.setWithCredentials(!0); } setExtensions(e) { this.extensions = e; } setPlugins(e) { this.plugins = e; } parse(e, t) { const i = this, s = this.json, n = this.extensions; this.cache.removeAll(), this.nodeCache = {}, this._invokeAll(function(a) { return a._markDefs && a._markDefs(); }), Promise.all(this._invokeAll(function(a) { return a.beforeRoot && a.beforeRoot(); })).then(function() { return Promise.all([ i.getDependencies("scene"), i.getDependencies("animation"), i.getDependencies("camera") ]); }).then(function(a) { const o = { scene: a[0][s.scene || 0], scenes: a[0], animations: a[1], cameras: a[2], asset: s.asset, parser: i, userData: {} }; return hr(n, o, s), xi(o, s), Promise.all(i._invokeAll(function(l) { return l.afterRoot && l.afterRoot(o); })).then(function() { for (const l of o.scenes) l.updateMatrixWorld(); e(o); }); }).catch(t); } /** * Marks the special nodes/meshes in json for efficient parse. * * @private */ _markDefs() { const e = this.json.nodes || [], t = this.json.skins || [], i = this.json.meshes || []; for (let s = 0, n = t.length; s < n; s++) { const a = t[s].joints; for (let o = 0, l = a.length; o < l; o++) e[a[o]].isBone = !0; } for (let s = 0, n = e.length; s < n; s++) { const a = e[s]; a.mesh !== void 0 && (this._addNodeRef(this.meshCache, a.mesh), a.skin !== void 0 && (i[a.mesh].isSkinnedMesh = !0)), a.camera !== void 0 && this._addNodeRef(this.cameraCache, a.camera); } } /** * Counts references to shared node / Object3D resources. These resources * can be reused, or "instantiated", at multiple nodes in the scene * hierarchy. Mesh, Camera, and Light instances are instantiated and must * be marked. Non-scenegraph resources (like Materials, Geometries, and * Textures) can be reused directly and are not marked here. * * Example: CesiumMilkTruck sample model reuses "Wheel" meshes. * * @private * @param {Object} cache * @param {Object3D} index */ _addNodeRef(e, t) { t !== void 0 && (e.refs[t] === void 0 && (e.refs[t] = e.uses[t] = 0), e.refs[t]++); } /** * Returns a reference to a shared resource, cloning it if necessary. * * @private * @param {Object} cache * @param {number} index * @param {Object} object * @return {Object} */ _getNodeRef(e, t, i) { if (e.refs[t] <= 1) return i; const s = i.clone(), n = (a, o) => { const l = this.associations.get(a); l != null && this.associations.set(o, l); for (const [c, h] of a.children.entries()) n(h, o.children[c]); }; return n(i, s), s.name += "_instance_" + e.uses[t]++, s; } _invokeOne(e) { const t = Object.values(this.plugins); t.push(this); for (let i = 0; i < t.length; i++) { const s = e(t[i]); if (s) return s; } return null; } _invokeAll(e) { const t = Object.values(this.plugins); t.unshift(this); const i = []; for (let s = 0; s < t.length; s++) { const n = e(t[s]); n && i.push(n); } return i; } /** * Requests the specified dependency asynchronously, with caching. * * @private * @param {string} type * @param {number} index * @return {Promise} */ getDependency(e, t) { const i = e + ":" + t; let s = this.cache.get(i); if (!s) { switch (e) { case "scene": s = this.loadScene(t); break; case "node": s = this._invokeOne(function(n) { return n.loadNode && n.loadNode(t); }); break; case "mesh": s = this._invokeOne(function(n) { return n.loadMesh && n.loadMesh(t); }); break; case "accessor": s = this.loadAccessor(t); break; case "bufferView": s = this._invokeOne(function(n) { return n.loadBufferView && n.loadBufferView(t); }); break; case "buffer": s = this.loadBuffer(t); break; case "material": s = this._invokeOne(function(n) { return n.loadMaterial && n.loadMaterial(t); }); break; case "texture": s = this._invokeOne(function(n) { return n.loadTexture && n.loadTexture(t); }); break; case "skin": s = this.loadSkin(t); break; case "animation": s = this._invokeOne(function(n) { return n.loadAnimation && n.loadAnimation(t); }); break; case "camera": s = this.loadCamera(t); break; default: if (s = this._invokeOne(function(n) { return n != this && n.getDependency && n.getDependency(e, t); }), !s) throw new Error("Unknown type: " + e); break; } this.cache.add(i, s); } return s; } /** * Requests all dependencies of the specified type asynchronously, with caching. * * @private * @param {string} type * @return {Promise>} */ getDependencies(e) { let t = this.cache.get(e); if (!t) { const i = this, s = this.json[e + (e === "mesh" ? "es" : "s")] || []; t = Promise.all(s.map(function(n, a) { return i.getDependency(e, a); })), this.cache.add(e, t); } return t; } /** * Specification: https://github.com/KhronosGroup/glTF/blob/master/specification/2.0/README.md#buffers-and-buffer-views * * @private * @param {number} bufferIndex * @return {Promise} */ loadBuffer(e) { const t = this.json.buffers[e], i = this.fileLoader; if (t.type && t.type !== "arraybuffer") throw new Error("THREE.GLTFLoader: " + t.type + " buffer type is not supported."); if (t.uri === void 0 && e === 0) return Promise.resolve(this.extensions[Ge.KHR_BINARY_GLTF].body); const s = this.options; return new Promise(function(n, a) { i.load(Ms.resolveURL(t.uri, s.path), n, void 0, function() { a(new Error('THREE.GLTFLoader: Failed to load buffer "' + t.uri + '".')); }); }); } /** * Specification: https://github.com/KhronosGroup/glTF/blob/master/specification/2.0/README.md#buffers-and-buffer-views * * @private * @param {number} bufferViewIndex * @return {Promise} */ loadBufferView(e) { const t = this.json.bufferViews[e]; return this.getDependency("buffer", t.buffer).then(function(i) { const s = t.byteLength || 0, n = t.byteOffset || 0; return i.slice(n, n + s); }); } /** * Specification: https://github.com/KhronosGroup/glTF/blob/master/specification/2.0/README.md#accessors * * @private * @param {number} accessorIndex * @return {Promise} */ loadAccessor(e) { const t = this, i = this.json, s = this.json.accessors[e]; if (s.bufferView === void 0 && s.sparse === void 0) { const a = ya[s.type], o = kr[s.componentType], l = s.normalized === !0, c = new o(s.count * a); return Promise.resolve(new zt(c, a, l)); } const n = []; return s.bufferView !== void 0 ? n.push(this.getDependency("bufferView", s.bufferView)) : n.push(null), s.sparse !== void 0 && (n.push(this.getDependency("bufferView", s.sparse.indices.bufferView)), n.push(this.getDependency("bufferView", s.sparse.values.bufferView))), Promise.all(n).then(function(a) { const o = a[0], l = ya[s.type], c = kr[s.componentType], h = c.BYTES_PER_ELEMENT, u = h * l, d = s.byteOffset || 0, f = s.bufferView !== void 0 ? i.bufferViews[s.bufferView].byteStride : void 0, g = s.normalized === !0; let v, m; if (f && f !== u) { const p = Math.floor(d / f), y = "InterleavedBuffer:" + s.bufferView + ":" + s.componentType + ":" + p + ":" + s.count; let _ = t.cache.get(y); _ || (v = new c(o, p * f, s.count * f / h), _ = new _d(v, f / h), t.cache.add(y, _)), m = new ko(_, l, d % f / h, g); } else o === null ? v = new c(s.count * l) : v = new c(o, d, s.count * l), m = new zt(v, l, g); if (s.sparse !== void 0) { const p = ya.SCALAR, y = kr[s.sparse.indices.componentType], _ = s.sparse.indices.byteOffset || 0, E = s.sparse.values.byteOffset || 0, A = new y(a[1], _, s.sparse.count * p), T = new c(a[2], E, s.sparse.count * l); o !== null && (m = new zt(m.array.slice(), m.itemSize, m.normalized)), m.normalized = !1; for (let R = 0, I = A.length; R < I; R++) { const b = A[R]; if (m.setX(b, T[R * l]), l >= 2 && m.setY(b, T[R * l + 1]), l >= 3 && m.setZ(b, T[R * l + 2]), l >= 4 && m.setW(b, T[R * l + 3]), l >= 5) throw new Error("THREE.GLTFLoader: Unsupported itemSize in sparse BufferAttribute."); } m.normalized = g; } return m; }); } /** * Specification: https://github.com/KhronosGroup/glTF/tree/master/specification/2.0#textures * * @private * @param {number} textureIndex * @return {Promise} */ loadTexture(e) { const t = this.json, i = this.options, s = t.textures[e].source, n = t.images[s]; let a = this.textureLoader; if (n.uri) { const o = i.manager.getHandler(n.uri); o !== null && (a = o); } return this.loadTextureImage(e, s, a); } loadTextureImage(e, t, i) { const s = this, n = this.json, a = n.textures[e], o = n.images[t], l = (o.uri || o.bufferView) + ":" + a.sampler; if (this.textureCache[l]) return this.textureCache[l]; const c = this.loadImageSource(t, i).then(function(h) { h.flipY = !1, h.name = a.name || o.name || "", h.name === "" && typeof o.uri == "string" && o.uri.startsWith("data:image/") === !1 && (h.name = o.uri); const u = (n.samplers || {})[a.sampler] || {}; return h.magFilter = Ac[u.magFilter] || xt, h.minFilter = Ac[u.minFilter] || Si, h.wrapS = Pc[u.wrapS] || Ei, h.wrapT = Pc[u.wrapT] || Ei, h.generateMipmaps = !h.isCompressedTexture && h.minFilter !== Dt && h.minFilter !== xt, s.associations.set(h, { textures: e }), h; }).catch(function() { return null; }); return this.textureCache[l] = c, c; } loadImageSource(e, t) { const i = this, s = this.json, n = this.options; if (this.sourceCache[e] !== void 0) return this.sourceCache[e].then((u) => u.clone()); const a = s.images[e], o = self.URL || self.webkitURL; let l = a.uri || "", c = !1; if (a.bufferView !== void 0) l = i.getDependency("bufferView", a.bufferView).then(function(u) { c = !0; const d = new Blob([u], { type: a.mimeType }); return l = o.createObjectURL(d), l; }); else if (a.uri === void 0) throw new Error("THREE.GLTFLoader: Image " + e + " is missing URI and bufferView"); const h = Promise.resolve(l).then(function(u) { return new Promise(function(d, f) { let g = d; t.isImageBitmapLoader === !0 && (g = function(v) { const m = new Ct(v); m.needsUpdate = !0, d(m); }), t.load(Ms.resolveURL(u, n.path), g, void 0, f); }); }).then(function(u) { return c === !0 && o.revokeObjectURL(l), xi(u, a), u.userData.mimeType = a.mimeType || c_(a.uri), u; }).catch(function(u) { throw console.error("THREE.GLTFLoader: Couldn't load texture", l), u; }); return this.sourceCache[e] = h, h; } /** * Asynchronously assigns a texture to the given material parameters. * * @private * @param {Object} materialParams * @param {string} mapName * @param {Object} mapDef * @param {string} [colorSpace] * @return {Promise} */ assignTexture(e, t, i, s) { const n = this; return this.getDependency("texture", i.index).then(function(a) { if (!a) return null; if (i.texCoord !== void 0 && i.texCoord > 0 && (a = a.clone(), a.channel = i.texCoord), n.extensions[Ge.KHR_TEXTURE_TRANSFORM]) { const o = i.extensions !== void 0 ? i.extensions[Ge.KHR_TEXTURE_TRANSFORM] : void 0; if (o) { const l = n.associations.get(a); a = n.extensions[Ge.KHR_TEXTURE_TRANSFORM].extendTexture(a, o), n.associations.set(a, l); } } return s !== void 0 && (a.colorSpace = s), e[t] = a, a; }); } /** * Assigns final material to a Mesh, Line, or Points instance. The instance * already has a material (generated from the glTF material options alone) * but reuse of the same glTF material may require multiple threejs materials * to accommodate different primitive types, defines, etc. New materials will * be created if necessary, and reused from a cache. * * @private * @param {Object3D} mesh Mesh, Line, or Points instance. */ assignFinalMaterial(e) { const t = e.geometry; let i = e.material; const s = t.attributes.tangent === void 0, n = t.attributes.color !== void 0, a = t.attributes.normal === void 0; if (e.isPoints) { const o = "PointsMaterial:" + i.uuid; let l = this.cache.get(o); l || (l = new dh(), $t.prototype.copy.call(l, i), l.color.copy(i.color), l.map = i.map, l.sizeAttenuation = !1, this.cache.add(o, l)), i = l; } else if (e.isLine) { const o = "LineBasicMaterial:" + i.uuid; let l = this.cache.get(o); l || (l = new uh(), $t.prototype.copy.call(l, i), l.color.copy(i.color), l.map = i.map, this.cache.add(o, l)), i = l; } if (s || n || a) { let o = "ClonedMaterial:" + i.uuid + ":"; s && (o += "derivative-tangents:"), n && (o += "vertex-colors:"), a && (o += "flat-shading:"); let l = this.cache.get(o); l || (l = i.clone(), n && (l.vertexColors = !0), a && (l.flatShading = !0), s && (l.normalScale && (l.normalScale.y *= -1), l.clearcoatNormalScale && (l.clearcoatNormalScale.y *= -1)), this.cache.add(o, l), this.associations.set(l, this.associations.get(i))), i = l; } e.material = i; } getMaterialType() { return jo; } /** * Specification: https://github.com/KhronosGroup/glTF/blob/master/specification/2.0/README.md#materials * * @private * @param {number} materialIndex * @return {Promise} */ loadMaterial(e) { const t = this, i = this.json, s = this.extensions, n = i.materials[e]; let a; const o = {}, l = n.extensions || {}, c = []; if (l[Ge.KHR_MATERIALS_UNLIT]) { const u = s[Ge.KHR_MATERIALS_UNLIT]; a = u.getMaterialType(), c.push(u.extendParams(o, n, t)); } else { const u = n.pbrMetallicRoughness || {}; if (o.color = new _e(1, 1, 1), o.opacity = 1, Array.isArray(u.baseColorFactor)) { const d = u.baseColorFactor; o.color.setRGB(d[0], d[1], d[2], Ut), o.opacity = d[3]; } u.baseColorTexture !== void 0 && c.push(t.assignTexture(o, "map", u.baseColorTexture, wt)), o.metalness = u.metallicFactor !== void 0 ? u.metallicFactor : 1, o.roughness = u.roughnessFactor !== void 0 ? u.roughnessFactor : 1, u.metallicRoughnessTexture !== void 0 && (c.push(t.assignTexture(o, "metalnessMap", u.metallicRoughnessTexture)), c.push(t.assignTexture(o, "roughnessMap", u.metallicRoughnessTexture))), a = this._invokeOne(function(d) { return d.getMaterialType && d.getMaterialType(e); }), c.push(Promise.all(this._invokeAll(function(d) { return d.extendMaterialParams && d.extendMaterialParams(e, o); }))); } n.doubleSided === !0 && (o.side = Vt); const h = n.alphaMode || Ma.OPAQUE; if (h === Ma.BLEND ? (o.transparent = !0, o.depthWrite = !1) : (o.transparent = !1, h === Ma.MASK && (o.alphaTest = n.alphaCutoff !== void 0 ? n.alphaCutoff : 0.5)), n.normalTexture !== void 0 && a !== Bt && (c.push(t.assignTexture(o, "normalMap", n.normalTexture)), o.normalScale = new oe(1, 1), n.normalTexture.scale !== void 0)) { const u = n.normalTexture.scale; o.normalScale.set(u, u); } if (n.occlusionTexture !== void 0 && a !== Bt && (c.push(t.assignTexture(o, "aoMap", n.occlusionTexture)), n.occlusionTexture.strength !== void 0 && (o.aoMapIntensity = n.occlusionTexture.strength)), n.emissiveFactor !== void 0 && a !== Bt) { const u = n.emissiveFactor; o.emissive = new _e().setRGB(u[0], u[1], u[2], Ut); } return n.emissiveTexture !== void 0 && a !== Bt && c.push(t.assignTexture(o, "emissiveMap", n.emissiveTexture, wt)), Promise.all(c).then(function() { const u = new a(o); return n.name && (u.name = n.name), xi(u, n), t.associations.set(u, { materials: e }), n.extensions && hr(s, u, n), u; }); } /** * When Object3D instances are targeted by animation, they need unique names. * * @private * @param {string} originalName * @return {string} */ createUniqueName(e) { const t = it.sanitizeNodeName(e || ""); return t in this.nodeNamesUsed ? t + "_" + ++this.nodeNamesUsed[t] : (this.nodeNamesUsed[t] = 0, t); } /** * Specification: https://github.com/KhronosGroup/glTF/blob/master/specification/2.0/README.md#geometry * * Creates BufferGeometries from primitives. * * @private * @param {Array} primitives * @return {Promise>} */ loadGeometries(e) { const t = this, i = this.extensions, s = this.primitiveCache; function n(o) { return i[Ge.KHR_DRACO_MESH_COMPRESSION].decodePrimitive(o, t).then(function(l) { return Dc(l, o, t); }); } const a = []; for (let o = 0, l = e.length; o < l; o++) { const c = e[o], h = l_(c), u = s[h]; if (u) a.push(u.promise); else { let d; c.extensions && c.extensions[Ge.KHR_DRACO_MESH_COMPRESSION] ? d = n(c) : d = Dc(new Qt(), c, t), s[h] = { primitive: c, promise: d }, a.push(d); } } return Promise.all(a); } /** * Specification: https://github.com/KhronosGroup/glTF/blob/master/specification/2.0/README.md#meshes * * @private * @param {number} meshIndex * @return {Promise} */ loadMesh(e) { const t = this, i = this.json, s = this.extensions, n = i.meshes[e], a = n.primitives, o = []; for (let l = 0, c = a.length; l < c; l++) { const h = a[l].material === void 0 ? n_(this.cache) : this.getDependency("material", a[l].material); o.push(h); } return o.push(t.loadGeometries(a)), Promise.all(o).then(function(l) { const c = l.slice(0, l.length - 1), h = l[l.length - 1], u = []; for (let f = 0, g = h.length; f < g; f++) { const v = h[f], m = a[f]; let p; const y = c[f]; if (m.mode === Zt.TRIANGLES || m.mode === Zt.TRIANGLE_STRIP || m.mode === Zt.TRIANGLE_FAN || m.mode === void 0) p = n.isSkinnedMesh === !0 ? new yd(v, y) : new nt(v, y), p.isSkinnedMesh === !0 && p.normalizeSkinWeights(), m.mode === Zt.TRIANGLE_STRIP ? p.geometry = Cc(p.geometry, eh) : m.mode === Zt.TRIANGLE_FAN && (p.geometry = Cc(p.geometry, ho)); else if (m.mode === Zt.LINES) p = new Cd(v, y); else if (m.mode === Zt.LINE_STRIP) p = new Go(v, y); else if (m.mode === Zt.LINE_LOOP) p = new Rd(v, y); else if (m.mode === Zt.POINTS) p = new Ad(v, y); else throw new Error("THREE.GLTFLoader: Primitive mode unsupported: " + m.mode); Object.keys(p.geometry.morphAttributes).length > 0 && o_(p, n), p.name = t.createUniqueName(n.name || "mesh_" + e), xi(p, n), m.extensions && hr(s, p, m), t.assignFinalMaterial(p), u.push(p); } for (let f = 0, g = u.length; f < g; f++) t.associations.set(u[f], { meshes: e, primitives: f }); if (u.length === 1) return n.extensions && hr(s, u[0], n), u[0]; const d = new zi(); n.extensions && hr(s, d, n), t.associations.set(d, { meshes: e }); for (let f = 0, g = u.length; f < g; f++) d.add(u[f]); return d; }); } /** * Specification: https://github.com/KhronosGroup/glTF/tree/master/specification/2.0#cameras * * @private * @param {number} cameraIndex * @return {Promise|undefined} */ loadCamera(e) { let t; const i = this.json.cameras[e], s = i[i.type]; if (!s) { console.warn("THREE.GLTFLoader: Missing camera parameters."); return; } return i.type === "perspective" ? t = new Mt(No.radToDeg(s.yfov), s.aspectRatio || 1, s.znear || 1, s.zfar || 2e6) : i.type === "orthographic" && (t = new mr(-s.xmag, s.xmag, s.ymag, -s.ymag, s.znear, s.zfar)), i.name && (t.name = this.createUniqueName(i.name)), xi(t, i), Promise.resolve(t); } /** * Specification: https://github.com/KhronosGroup/glTF/tree/master/specification/2.0#skins * * @private * @param {number} skinIndex * @return {Promise} */ loadSkin(e) { const t = this.json.skins[e], i = []; for (let s = 0, n = t.joints.length; s < n; s++) i.push(this._loadNodeShallow(t.joints[s])); return t.inverseBindMatrices !== void 0 ? i.push(this.getDependency("accessor", t.inverseBindMatrices)) : i.push(null), Promise.all(i).then(function(s) { const n = s.pop(), a = s, o = [], l = []; for (let c = 0, h = a.length; c < h; c++) { const u = a[c]; if (u) { o.push(u); const d = new Ue(); n !== null && d.fromArray(n.array, c * 16), l.push(d); } else console.warn('THREE.GLTFLoader: Joint "%s" could not be found.', t.joints[c]); } return new Ho(o, l); }); } /** * Specification: https://github.com/KhronosGroup/glTF/tree/master/specification/2.0#animations * * @private * @param {number} animationIndex * @return {Promise} */ loadAnimation(e) { const t = this.json, i = this, s = t.animations[e], n = s.name ? s.name : "animation_" + e, a = [], o = [], l = [], c = [], h = []; for (let u = 0, d = s.channels.length; u < d; u++) { const f = s.channels[u], g = s.samplers[f.sampler], v = f.target, m = v.node, p = s.parameters !== void 0 ? s.parameters[g.input] : g.input, y = s.parameters !== void 0 ? s.parameters[g.output] : g.output; v.node !== void 0 && (a.push(this.getDependency("node", m)), o.push(this.getDependency("accessor", p)), l.push(this.getDependency("accessor", y)), c.push(g), h.push(v)); } return Promise.all([ Promise.all(a), Promise.all(o), Promise.all(l), Promise.all(c), Promise.all(h) ]).then(function(u) { const d = u[0], f = u[1], g = u[2], v = u[3], m = u[4], p = []; for (let _ = 0, E = d.length; _ < E; _++) { const A = d[_], T = f[_], R = g[_], I = v[_], b = m[_]; if (A === void 0) continue; A.updateMatrix && A.updateMatrix(); const S = i._createAnimationTracks(A, T, R, I, b); if (S) for (let D = 0; D < S.length; D++) p.push(S[D]); } const y = new kd(n, void 0, p); return xi(y, s), y; }); } createNodeMesh(e) { const t = this.json, i = this, s = t.nodes[e]; return s.mesh === void 0 ? null : i.getDependency("mesh", s.mesh).then(function(n) { const a = i._getNodeRef(i.meshCache, s.mesh, n); return s.weights !== void 0 && a.traverse(function(o) { if (o.isMesh) for (let l = 0, c = s.weights.length; l < c; l++) o.morphTargetInfluences[l] = s.weights[l]; }), a; }); } /** * Specification: https://github.com/KhronosGroup/glTF/tree/master/specification/2.0#nodes-and-hierarchy * * @private * @param {number} nodeIndex * @return {Promise} */ loadNode(e) { const t = this.json, i = this, s = t.nodes[e], n = i._loadNodeShallow(e), a = [], o = s.children || []; for (let c = 0, h = o.length; c < h; c++) a.push(i.getDependency("node", o[c])); const l = s.skin === void 0 ? Promise.resolve(null) : i.getDependency("skin", s.skin); return Promise.all([ n, Promise.all(a), l ]).then(function(c) { const h = c[0], u = c[1], d = c[2]; d !== null && h.traverse(function(f) { f.isSkinnedMesh && f.bind(d, h_); }); for (let f = 0, g = u.length; f < g; f++) h.add(u[f]); return h; }); } // ._loadNodeShallow() parses a single node. // skin and child nodes are created and added in .loadNode() (no '_' prefix). _loadNodeShallow(e) { const t = this.json, i = this.extensions, s = this; if (this.nodeCache[e] !== void 0) return this.nodeCache[e]; const n = t.nodes[e], a = n.name ? s.createUniqueName(n.name) : "", o = [], l = s._invokeOne(function(c) { return c.createNodeMesh && c.createNodeMesh(e); }); return l && o.push(l), n.camera !== void 0 && o.push(s.getDependency("camera", n.camera).then(function(c) { return s._getNodeRef(s.cameraCache, n.camera, c); })), s._invokeAll(function(c) { return c.createNodeAttachment && c.createNodeAttachment(e); }).forEach(function(c) { o.push(c); }), this.nodeCache[e] = Promise.all(o).then(function(c) { let h; if (n.isBone === !0 ? h = new hh() : c.length > 1 ? h = new zi() : c.length === 1 ? h = c[0] : h = new dt(), h !== c[0]) for (let u = 0, d = c.length; u < d; u++) h.add(c[u]); if (n.name && (h.userData.name = n.name, h.name = a), xi(h, n), n.extensions && hr(i, h, n), n.matrix !== void 0) { const u = new Ue(); u.fromArray(n.matrix), h.applyMatrix4(u); } else n.translation !== void 0 && h.position.fromArray(n.translation), n.rotation !== void 0 && h.quaternion.fromArray(n.rotation), n.scale !== void 0 && h.scale.fromArray(n.scale); if (!s.associations.has(h)) s.associations.set(h, {}); else if (n.mesh !== void 0 && s.meshCache.refs[n.mesh] > 1) { const u = s.associations.get(h); s.associations.set(h, { ...u }); } return s.associations.get(h).nodes = e, h; }), this.nodeCache[e]; } /** * Specification: https://github.com/KhronosGroup/glTF/tree/master/specification/2.0#scenes * * @private * @param {number} sceneIndex * @return {Promise} */ loadScene(e) { const t = this.extensions, i = this.json.scenes[e], s = this, n = new zi(); i.name && (n.name = s.createUniqueName(i.name)), xi(n, i), i.extensions && hr(t, n, i); const a = i.nodes || [], o = []; for (let l = 0, c = a.length; l < c; l++) o.push(s.getDependency("node", a[l])); return Promise.all(o).then(function(l) { for (let h = 0, u = l.length; h < u; h++) n.add(l[h]); const c = (h) => { const u = /* @__PURE__ */ new Map(); for (const [d, f] of s.associations) (d instanceof $t || d instanceof Ct) && u.set(d, f); return h.traverse((d) => { const f = s.associations.get(d); f != null && u.set(d, f); }), u; }; return s.associations = c(n), n; }); } _createAnimationTracks(e, t, i, s, n) { const a = [], o = e.name ? e.name : e.uuid, l = []; Yi[n.path] === Yi.weights ? e.traverse(function(d) { d.morphTargetInfluences && l.push(d.name ? d.name : d.uuid); }) : l.push(o); let c; switch (Yi[n.path]) { case Yi.weights: c = Kr; break; case Yi.rotation: c = Zr; break; case Yi.translation: case Yi.scale: c = Jr; break; default: switch (i.itemSize) { case 1: c = Kr; break; case 2: case 3: default: c = Jr; break; } break; } const h = s.interpolation !== void 0 ? s_[s.interpolation] : Es, u = this._getArrayFromAccessor(i); for (let d = 0, f = l.length; d < f; d++) { const g = new c( l[d] + "." + Yi[n.path], t.array, u, h ); s.interpolation === "CUBICSPLINE" && this._createCubicSplineTrackInterpolant(g), a.push(g); } return a; } _getArrayFromAccessor(e) { let t = e.array; if (e.normalized) { const i = Mo(t.constructor), s = new Float32Array(t.length); for (let n = 0, a = t.length; n < a; n++) s[n] = t[n] * i; t = s; } return t; } _createCubicSplineTrackInterpolant(e) { e.createInterpolant = function(t) { const i = this instanceof Zr ? r_ : Lh; return new i(this.times, this.values, this.getValueSize() / 3, t); }, e.createInterpolant.isInterpolantFactoryMethodGLTFCubicSpline = !0; } } function d_(r, e, t) { const i = e.attributes, s = new Rt(); if (i.POSITION !== void 0) { const o = t.json.accessors[i.POSITION], l = o.min, c = o.max; if (l !== void 0 && c !== void 0) { if (s.set( new w(l[0], l[1], l[2]), new w(c[0], c[1], c[2]) ), o.normalized) { const h = Mo(kr[o.componentType]); s.min.multiplyScalar(h), s.max.multiplyScalar(h); } } else { console.warn("THREE.GLTFLoader: Missing min/max properties for accessor POSITION."); return; } } else return; const n = e.targets; if (n !== void 0) { const o = new w(), l = new w(); for (let c = 0, h = n.length; c < h; c++) { const u = n[c]; if (u.POSITION !== void 0) { const d = t.json.accessors[u.POSITION], f = d.min, g = d.max; if (f !== void 0 && g !== void 0) { if (l.setX(Math.max(Math.abs(f[0]), Math.abs(g[0]))), l.setY(Math.max(Math.abs(f[1]), Math.abs(g[1]))), l.setZ(Math.max(Math.abs(f[2]), Math.abs(g[2]))), d.normalized) { const v = Mo(kr[d.componentType]); l.multiplyScalar(v); } o.max(l); } else console.warn("THREE.GLTFLoader: Missing min/max properties for accessor POSITION."); } } s.expandByVector(o); } r.boundingBox = s; const a = new Ci(); s.getCenter(a.center), a.radius = s.min.distanceTo(s.max) / 2, r.boundingSphere = a; } function Dc(r, e, t) { const i = e.attributes, s = []; function n(a, o) { return t.getDependency("accessor", a).then(function(l) { r.setAttribute(o, l); }); } for (const a in i) { const o = yo[a] || a.toLowerCase(); o in r.attributes || s.push(n(i[a], o)); } if (e.indices !== void 0 && !r.index) { const a = t.getDependency("accessor", e.indices).then(function(o) { r.setIndex(o); }); s.push(a); } return Xe.workingColorSpace !== Ut && "COLOR_0" in i && console.warn(`THREE.GLTFLoader: Converting vertex colors from "srgb-linear" to "${Xe.workingColorSpace}" not supported.`), xi(r, e), d_(r, e, t), Promise.all(s).then(function() { return e.targets !== void 0 ? a_(r, e.targets, t) : r; }); } class p_ { loader; scene; models = []; // 存储加载的模型 constructor(e) { this.scene = e, this.loader = new Ph(); } async loadGLTF(e) { return new Promise((t, i) => { this.loader.load( e, (s) => { const n = s.scene; n.traverse((a) => { a instanceof nt && (a.receiveShadow = !0, a.castShadow = !0); }), this.scene.add(n), this.models.push({ children: this.extractMeshes(n) }), t(n); }, void 0, (s) => { console.error("An error happened loading the model:", s), i(s); } ); }); } /** * 从场景中提取所有 Mesh */ extractMeshes(e) { const t = []; return e.traverse((i) => { i instanceof nt && t.push(i); }), t; } /** * 清空所有模型 */ clearModels() { this.models = []; } } class f_ { // Currently unused - for future event handler implementation // private _raycaster!: THREE.Raycaster; // private _pointer!: THREE.Vector2; // private _camera!: THREE.Camera; scene; // private _canvas!: HTMLElement; // private _eventModule: IEventModule | null = null; // private _engineState!: EngineState; // private _outlineManager: OutlineManager | null = null; // 点击高亮材质(用于点击选中) highlightMaterial; // 存储原始材质的 Map(仅用于点击高亮) originalMaterials = /* @__PURE__ */ new Map(); // 存储原始 renderOrder 的 Map originalRenderOrders = /* @__PURE__ */ new Map(); // 当前点击选中的对象列表 selectedObjects = []; // 当前悬停的对象 (currently unused) // private hoveredObject: THREE.Object3D | null = null; // 用于区分点击和拖拽 (currently unused - related event handlers are commented out) // private mouseDownPosition: { x: number; y: number } | null = null; // private isDragging: boolean = false; constructor(e, t, i, s) { this.scene = e, this.highlightMaterial = new Bt({ color: 43775, // 明显的蓝色 depthTest: !1, // 不进行深度测试,始终显示 depthWrite: !1, // 不写入深度缓冲 transparent: !0, opacity: 0.8, // 半透明效果 side: Vt // 双面渲染 }); } /** * 设置 OutlineManager(由 EngineKernel 注入) * Currently unused - related to commented-out hover functionality */ // public setOutlineManager(outlineManager: OutlineManager) { // this._outlineManager = outlineManager; // } // 设置事件模块,用于触发事件 setEventModule(e) { } // Commented out - these methods are not currently used (event listeners are commented out in constructor) // private _onMouseDown(event: MouseEvent) { // // 只处理左键 // if (event.button !== 0) return; // // 记录鼠标按下时的位置 // this.mouseDownPosition = { // x: event.clientX, // y: event.clientY // }; // this.isDragging = false; // this.handleClick(event); // } // private _onMouseUp(event: MouseEvent) { // // 只处理左键 // if (event.button !== 0) return; // // 如果没有记录按下位置,或者正在拖拽,则不执行点击逻辑 // if (!this.mouseDownPosition || this.isDragging) { // this.mouseDownPosition = null; // this.isDragging = false; // return; // } // // 计算鼠标移动距离 // const deltaX = event.clientX - this.mouseDownPosition.x; // const deltaY = event.clientY - this.mouseDownPosition.y; // const distance = Math.sqrt(deltaX * deltaX + deltaY * deltaY); // // 只有移动距离小于阈值时才认为是点击(而不是拖拽) // const clickThreshold = 5; // 像素 // if (distance < clickThreshold) { // this.handleClick(event); // } // this.mouseDownPosition = null; // this.isDragging = false; // } // private handleClick(event: MouseEvent) { // const rect = this.canvas.getBoundingClientRect(); // this.pointer.x = ((event.clientX - rect.left) / rect.width) * 2 - 1; // this.pointer.y = -((event.clientY - rect.top) / rect.height) * 2 + 1; // this.raycaster.setFromCamera(this.pointer, this.camera); // const intersects = this.raycaster.intersectObjects(this.scene.children, true); // if (intersects.length > 0) { // const hit = intersects[0]; // const selected = hit.object as THREE.Mesh; // // 存储点击的世界坐标到全局状态,CustomOrbitControls 会自动使用这个坐标作为旋转中心 // this.engineState.setLastClickWorldPosition(hit.point); // this.engineState.setLastClickScreenPosition(this.pointer); // // 点击使用材质替换高亮 // this.setSelectedWithMaterial([selected]); // } else { // this.clearSelected(); // } // } // private _onPointerMove(event: MouseEvent) { // // 如果鼠标按下后移动,标记为拖拽 // if (this.mouseDownPosition) { // const deltaX = event.clientX - this.mouseDownPosition.x; // const deltaY = event.clientY - this.mouseDownPosition.y; // const distance = Math.sqrt(deltaX * deltaX + deltaY * deltaY); // // 移动超过阈值时标记为拖拽 // const dragThreshold = 5; // 像素 // if (distance > dragThreshold) { // this.isDragging = true; // } // } // const rect = this.canvas.getBoundingClientRect(); // this.pointer.x = ((event.clientX - rect.left) / rect.width) * 2 - 1; // this.pointer.y = -((event.clientY - rect.top) / rect.height) * 2 + 1; // this.raycaster.setFromCamera(this.pointer, this.camera); // const intersects = this.raycaster.intersectObjects(this.scene.children, true); // // 处理悬停高亮(使用 Outline) // if (intersects.length > 0) { // const hit = intersects[0]; // const hoveredObj = hit.object; // // 如果悬停到新对象,更新悬停高亮 // if (hoveredObj !== this.hoveredObject) { // // 只有当对象不是已经被点击选中的对象时,才应用悬停轮廓高亮 // const isSelected = this.selectedObjects.some(obj => obj === hoveredObj); // if (!isSelected) { // this.setHoveredWithOutline(hoveredObj); // } else { // // 如果是已选中对象,清除悬停高亮 // this.clearHovered(); // } // } // } else { // // 鼠标移出所有对象,清除悬停高亮 // this.clearHovered(); // } // // 构建鼠标事件数据 // const mouseData: MouseEventData = { // x: event.clientX, // y: event.clientY, // originalEvent: event // }; // if (intersects.length > 0) { // const hit = intersects[0]; // mouseData.worldPoint = { // x: hit.point.x, // y: hit.point.y, // z: hit.point.z // }; // mouseData.entityId = hit.object.uuid; // } // // 触发鼠标移动事件 // if (this.eventModule) { // this.eventModule.trigger(EventType.MouseMove, mouseData); // } // } /** * 设置选中对象(点击高亮 - 使用材质替换) */ setSelectedWithMaterial(e) { this.clearSelected(), e.forEach((t) => { t.isMesh && (this.originalMaterials.has(t.uuid) || this.originalMaterials.set(t.uuid, t.material), this.originalRenderOrders.has(t.uuid) || this.originalRenderOrders.set(t.uuid, t.renderOrder), t.material = this.highlightMaterial, t.renderOrder = 999, this.selectedObjects.push(t)); }); } /** * 清除选中高亮 */ clearSelected() { this.selectedObjects.forEach((e) => { const t = this.originalMaterials.get(e.uuid); t && (e.material = t); const i = this.originalRenderOrders.get(e.uuid); i !== void 0 && (e.renderOrder = i); }), this.selectedObjects = [], this.originalMaterials.clear(), this.originalRenderOrders.clear(); } /** * 设置悬停对象(鼠标划过高亮 - 使用 Outline 轮廓) * Currently unused - related to commented-out hover functionality */ // private setHoveredWithOutline(obj: THREE.Object3D) { // this.hoveredObject = obj; // if (this.outlineManager) { // this.outlineManager.setHoveredObjects([obj]); // } // } /** * 清除悬停高亮 * Currently unused - related to commented-out hover functionality */ // private clearHovered() { // this.hoveredObject = null; // if (this.outlineManager) { // this.outlineManager.clearHovered(); // } // } /** * 兼容旧 API:highlight(使用材质替换) */ highlight(e) { this.setSelectedWithMaterial(e); } /** * 兼容旧 API:clearHighlight */ clearHighlight() { this.clearSelected(); } setVisibility(e, t) { this.scene.traverse((i) => { (e.includes(i.uuid) || e.includes(i.name)) && (i.visible = t); }); } } class Ji extends tr { /** * Constructs a new outline pass. * * @param {Vector2} [resolution] - The effect's resolution. * @param {Scene} scene - The scene to render. * @param {Camera} camera - The camera. * @param {Array} [selectedObjects] - The selected 3D objects that should receive an outline. * */ constructor(e, t, i, s) { super(), this.renderScene = t, this.renderCamera = i, this.selectedObjects = s !== void 0 ? s : [], this.visibleEdgeColor = new _e(1, 1, 1), this.hiddenEdgeColor = new _e(0.1, 0.04, 0.02), this.edgeGlow = 0, this.usePatternTexture = !1, this.patternTexture = null, this.edgeThickness = 1, this.edgeStrength = 3, this.downSampleRatio = 2, this.pulsePeriod = 0, this._visibilityCache = /* @__PURE__ */ new Map(), this._selectionCache = /* @__PURE__ */ new Set(), this.resolution = e !== void 0 ? new oe(e.x, e.y) : new oe(256, 256); const n = Math.round(this.resolution.x / this.downSampleRatio), a = Math.round(this.resolution.y / this.downSampleRatio); this.renderTargetMaskBuffer = new _t(this.resolution.x, this.resolution.y), this.renderTargetMaskBuffer.texture.name = "OutlinePass.mask", this.renderTargetMaskBuffer.texture.generateMipmaps = !1, this.depthMaterial = new fh(), this.depthMaterial.side = Vt, this.depthMaterial.depthPacking = th, this.depthMaterial.blending = vt, this.prepareMaskMaterial = this._getPrepareMaskMaterial(), this.prepareMaskMaterial.side = Vt, this.prepareMaskMaterial.fragmentShader = h(this.prepareMaskMaterial.fragmentShader, this.renderCamera), this.renderTargetDepthBuffer = new _t(this.resolution.x, this.resolution.y, { type: ft }), this.renderTargetDepthBuffer.texture.name = "OutlinePass.depth", this.renderTargetDepthBuffer.texture.generateMipmaps = !1, this.renderTargetMaskDownSampleBuffer = new _t(n, a, { type: ft }), this.renderTargetMaskDownSampleBuffer.texture.name = "OutlinePass.depthDownSample", this.renderTargetMaskDownSampleBuffer.texture.generateMipmaps = !1, this.renderTargetBlurBuffer1 = new _t(n, a, { type: ft }), this.renderTargetBlurBuffer1.texture.name = "OutlinePass.blur1", this.renderTargetBlurBuffer1.texture.generateMipmaps = !1, this.renderTargetBlurBuffer2 = new _t(Math.round(n / 2), Math.round(a / 2), { type: ft }), this.renderTargetBlurBuffer2.texture.name = "OutlinePass.blur2", this.renderTargetBlurBuffer2.texture.generateMipmaps = !1, this.edgeDetectionMaterial = this._getEdgeDetectionMaterial(), this.renderTargetEdgeBuffer1 = new _t(n, a, { type: ft }), this.renderTargetEdgeBuffer1.texture.name = "OutlinePass.edge1", this.renderTargetEdgeBuffer1.texture.generateMipmaps = !1, this.renderTargetEdgeBuffer2 = new _t(Math.round(n / 2), Math.round(a / 2), { type: ft }), this.renderTargetEdgeBuffer2.texture.name = "OutlinePass.edge2", this.renderTargetEdgeBuffer2.texture.generateMipmaps = !1; const o = 4, l = 4; this.separableBlurMaterial1 = this._getSeparableBlurMaterial(o), this.separableBlurMaterial1.uniforms.texSize.value.set(n, a), this.separableBlurMaterial1.uniforms.kernelRadius.value = 1, this.separableBlurMaterial2 = this._getSeparableBlurMaterial(l), this.separableBlurMaterial2.uniforms.texSize.value.set(Math.round(n / 2), Math.round(a / 2)), this.separableBlurMaterial2.uniforms.kernelRadius.value = l, this.overlayMaterial = this._getOverlayMaterial(); const c = Qi; this.copyUniforms = ui.clone(c.uniforms), this.materialCopy = new ct({ uniforms: this.copyUniforms, vertexShader: c.vertexShader, fragmentShader: c.fragmentShader, blending: vt, depthTest: !1, depthWrite: !1 }), this.enabled = !0, this.needsSwap = !1, this._oldClearColor = new _e(), this.oldClearAlpha = 1, this._fsQuad = new Ds(null), this.tempPulseColor1 = new _e(), this.tempPulseColor2 = new _e(), this.textureMatrix = new Ue(); function h(u, d) { const f = d.isPerspectiveCamera ? "perspective" : "orthographic"; return u.replace(/DEPTH_TO_VIEW_Z/g, f + "DepthToViewZ"); } } /** * Frees the GPU-related resources allocated by this instance. Call this * method whenever the pass is no longer used in your app. */ dispose() { this.renderTargetMaskBuffer.dispose(), this.renderTargetDepthBuffer.dispose(), this.renderTargetMaskDownSampleBuffer.dispose(), this.renderTargetBlurBuffer1.dispose(), this.renderTargetBlurBuffer2.dispose(), this.renderTargetEdgeBuffer1.dispose(), this.renderTargetEdgeBuffer2.dispose(), this.depthMaterial.dispose(), this.prepareMaskMaterial.dispose(), this.edgeDetectionMaterial.dispose(), this.separableBlurMaterial1.dispose(), this.separableBlurMaterial2.dispose(), this.overlayMaterial.dispose(), this.materialCopy.dispose(), this._fsQuad.dispose(); } /** * Sets the size of the pass. * * @param {number} width - The width to set. * @param {number} height - The height to set. */ setSize(e, t) { this.renderTargetMaskBuffer.setSize(e, t), this.renderTargetDepthBuffer.setSize(e, t); let i = Math.round(e / this.downSampleRatio), s = Math.round(t / this.downSampleRatio); this.renderTargetMaskDownSampleBuffer.setSize(i, s), this.renderTargetBlurBuffer1.setSize(i, s), this.renderTargetEdgeBuffer1.setSize(i, s), this.separableBlurMaterial1.uniforms.texSize.value.set(i, s), i = Math.round(i / 2), s = Math.round(s / 2), this.renderTargetBlurBuffer2.setSize(i, s), this.renderTargetEdgeBuffer2.setSize(i, s), this.separableBlurMaterial2.uniforms.texSize.value.set(i, s); } /** * Performs the Outline pass. * * @param {WebGLRenderer} renderer - The renderer. * @param {WebGLRenderTarget} writeBuffer - The write buffer. This buffer is intended as the rendering * destination for the pass. * @param {WebGLRenderTarget} readBuffer - The read buffer. The pass can access the result from the * previous pass from this buffer. * @param {number} deltaTime - The delta time in seconds. * @param {boolean} maskActive - Whether masking is active or not. */ render(e, t, i, s, n) { if (this.selectedObjects.length > 0) { e.getClearColor(this._oldClearColor), this.oldClearAlpha = e.getClearAlpha(); const a = e.autoClear; e.autoClear = !1, n && e.state.buffers.stencil.setTest(!1), e.setClearColor(16777215, 1), this._updateSelectionCache(), this._changeVisibilityOfSelectedObjects(!1); const o = this.renderScene.background, l = this.renderScene.overrideMaterial; if (this.renderScene.background = null, this.renderScene.overrideMaterial = this.depthMaterial, e.setRenderTarget(this.renderTargetDepthBuffer), e.clear(), e.render(this.renderScene, this.renderCamera), this._changeVisibilityOfSelectedObjects(!0), this._visibilityCache.clear(), this._updateTextureMatrix(), this._changeVisibilityOfNonSelectedObjects(!1), this.renderScene.overrideMaterial = this.prepareMaskMaterial, this.prepareMaskMaterial.uniforms.cameraNearFar.value.set(this.renderCamera.near, this.renderCamera.far), this.prepareMaskMaterial.uniforms.depthTexture.value = this.renderTargetDepthBuffer.texture, this.prepareMaskMaterial.uniforms.textureMatrix.value = this.textureMatrix, e.setRenderTarget(this.renderTargetMaskBuffer), e.clear(), e.render(this.renderScene, this.renderCamera), this._changeVisibilityOfNonSelectedObjects(!0), this._visibilityCache.clear(), this._selectionCache.clear(), this.renderScene.background = o, this.renderScene.overrideMaterial = l, this._fsQuad.material = this.materialCopy, this.copyUniforms.tDiffuse.value = this.renderTargetMaskBuffer.texture, e.setRenderTarget(this.renderTargetMaskDownSampleBuffer), e.clear(), this._fsQuad.render(e), this.tempPulseColor1.copy(this.visibleEdgeColor), this.tempPulseColor2.copy(this.hiddenEdgeColor), this.pulsePeriod > 0) { const c = 0.625 + Math.cos(performance.now() * 0.01 / this.pulsePeriod) * 0.75 / 2; this.tempPulseColor1.multiplyScalar(c), this.tempPulseColor2.multiplyScalar(c); } this._fsQuad.material = this.edgeDetectionMaterial, this.edgeDetectionMaterial.uniforms.maskTexture.value = this.renderTargetMaskDownSampleBuffer.texture, this.edgeDetectionMaterial.uniforms.texSize.value.set(this.renderTargetMaskDownSampleBuffer.width, this.renderTargetMaskDownSampleBuffer.height), this.edgeDetectionMaterial.uniforms.visibleEdgeColor.value = this.tempPulseColor1, this.edgeDetectionMaterial.uniforms.hiddenEdgeColor.value = this.tempPulseColor2, e.setRenderTarget(this.renderTargetEdgeBuffer1), e.clear(), this._fsQuad.render(e), this._fsQuad.material = this.separableBlurMaterial1, this.separableBlurMaterial1.uniforms.colorTexture.value = this.renderTargetEdgeBuffer1.texture, this.separableBlurMaterial1.uniforms.direction.value = Ji.BlurDirectionX, this.separableBlurMaterial1.uniforms.kernelRadius.value = this.edgeThickness, e.setRenderTarget(this.renderTargetBlurBuffer1), e.clear(), this._fsQuad.render(e), this.separableBlurMaterial1.uniforms.colorTexture.value = this.renderTargetBlurBuffer1.texture, this.separableBlurMaterial1.uniforms.direction.value = Ji.BlurDirectionY, e.setRenderTarget(this.renderTargetEdgeBuffer1), e.clear(), this._fsQuad.render(e), this._fsQuad.material = this.separableBlurMaterial2, this.separableBlurMaterial2.uniforms.colorTexture.value = this.renderTargetEdgeBuffer1.texture, this.separableBlurMaterial2.uniforms.direction.value = Ji.BlurDirectionX, e.setRenderTarget(this.renderTargetBlurBuffer2), e.clear(), this._fsQuad.render(e), this.separableBlurMaterial2.uniforms.colorTexture.value = this.renderTargetBlurBuffer2.texture, this.separableBlurMaterial2.uniforms.direction.value = Ji.BlurDirectionY, e.setRenderTarget(this.renderTargetEdgeBuffer2), e.clear(), this._fsQuad.render(e), this._fsQuad.material = this.overlayMaterial, this.overlayMaterial.uniforms.maskTexture.value = this.renderTargetMaskBuffer.texture, this.overlayMaterial.uniforms.edgeTexture1.value = this.renderTargetEdgeBuffer1.texture, this.overlayMaterial.uniforms.edgeTexture2.value = this.renderTargetEdgeBuffer2.texture, this.overlayMaterial.uniforms.patternTexture.value = this.patternTexture, this.overlayMaterial.uniforms.edgeStrength.value = this.edgeStrength, this.overlayMaterial.uniforms.edgeGlow.value = this.edgeGlow, this.overlayMaterial.uniforms.usePatternTexture.value = this.usePatternTexture, n && e.state.buffers.stencil.setTest(!0), e.setRenderTarget(i), this._fsQuad.render(e), e.setClearColor(this._oldClearColor, this.oldClearAlpha), e.autoClear = a; } this.renderToScreen && (this._fsQuad.material = this.materialCopy, this.copyUniforms.tDiffuse.value = i.texture, e.setRenderTarget(null), this._fsQuad.render(e)); } // internals _updateSelectionCache() { const e = this._selectionCache; function t(i) { i.isMesh && e.add(i); } e.clear(); for (let i = 0; i < this.selectedObjects.length; i++) this.selectedObjects[i].traverse(t); } _changeVisibilityOfSelectedObjects(e) { const t = this._visibilityCache; for (const i of this._selectionCache) e === !0 ? i.visible = t.get(i) : (t.set(i, i.visible), i.visible = e); } _changeVisibilityOfNonSelectedObjects(e) { const t = this._visibilityCache, i = this._selectionCache; function s(n) { if (n.isPoints || n.isLine || n.isLine2) e === !0 ? n.visible = t.get(n) : (t.set(n, n.visible), n.visible = e); else if ((n.isMesh || n.isSprite) && !i.has(n)) { const a = n.visible; (e === !1 || t.get(n) === !0) && (n.visible = e), t.set(n, a); } } this.renderScene.traverse(s); } _updateTextureMatrix() { this.textureMatrix.set( 0.5, 0, 0, 0.5, 0, 0.5, 0, 0.5, 0, 0, 0.5, 0.5, 0, 0, 0, 1 ), this.textureMatrix.multiply(this.renderCamera.projectionMatrix), this.textureMatrix.multiply(this.renderCamera.matrixWorldInverse); } _getPrepareMaskMaterial() { return new ct({ uniforms: { depthTexture: { value: null }, cameraNearFar: { value: new oe(0.5, 0.5) }, textureMatrix: { value: null } }, vertexShader: `#include #include #include varying vec4 projTexCoord; varying vec4 vPosition; uniform mat4 textureMatrix; void main() { #include #include #include #include #include #include vPosition = mvPosition; vec4 worldPosition = vec4( transformed, 1.0 ); #ifdef USE_INSTANCING worldPosition = instanceMatrix * worldPosition; #endif worldPosition = modelMatrix * worldPosition; projTexCoord = textureMatrix * worldPosition; }`, fragmentShader: `#include varying vec4 vPosition; varying vec4 projTexCoord; uniform sampler2D depthTexture; uniform vec2 cameraNearFar; void main() { float depth = unpackRGBAToDepth(texture2DProj( depthTexture, projTexCoord )); float viewZ = - DEPTH_TO_VIEW_Z( depth, cameraNearFar.x, cameraNearFar.y ); float depthTest = (-vPosition.z > viewZ) ? 1.0 : 0.0; gl_FragColor = vec4(0.0, depthTest, 1.0, 1.0); }` }); } _getEdgeDetectionMaterial() { return new ct({ uniforms: { maskTexture: { value: null }, texSize: { value: new oe(0.5, 0.5) }, visibleEdgeColor: { value: new w(1, 1, 1) }, hiddenEdgeColor: { value: new w(1, 1, 1) } }, vertexShader: `varying vec2 vUv; void main() { vUv = uv; gl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 ); }`, fragmentShader: `varying vec2 vUv; uniform sampler2D maskTexture; uniform vec2 texSize; uniform vec3 visibleEdgeColor; uniform vec3 hiddenEdgeColor; void main() { vec2 invSize = 1.0 / texSize; vec4 uvOffset = vec4(1.0, 0.0, 0.0, 1.0) * vec4(invSize, invSize); vec4 c1 = texture2D( maskTexture, vUv + uvOffset.xy); vec4 c2 = texture2D( maskTexture, vUv - uvOffset.xy); vec4 c3 = texture2D( maskTexture, vUv + uvOffset.yw); vec4 c4 = texture2D( maskTexture, vUv - uvOffset.yw); float diff1 = (c1.r - c2.r)*0.5; float diff2 = (c3.r - c4.r)*0.5; float d = length( vec2(diff1, diff2) ); float a1 = min(c1.g, c2.g); float a2 = min(c3.g, c4.g); float visibilityFactor = min(a1, a2); vec3 edgeColor = 1.0 - visibilityFactor > 0.001 ? visibleEdgeColor : hiddenEdgeColor; gl_FragColor = vec4(edgeColor, 1.0) * vec4(d); }` }); } _getSeparableBlurMaterial(e) { return new ct({ defines: { MAX_RADIUS: e }, uniforms: { colorTexture: { value: null }, texSize: { value: new oe(0.5, 0.5) }, direction: { value: new oe(0.5, 0.5) }, kernelRadius: { value: 1 } }, vertexShader: `varying vec2 vUv; void main() { vUv = uv; gl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 ); }`, fragmentShader: `#include varying vec2 vUv; uniform sampler2D colorTexture; uniform vec2 texSize; uniform vec2 direction; uniform float kernelRadius; float gaussianPdf(in float x, in float sigma) { return 0.39894 * exp( -0.5 * x * x/( sigma * sigma))/sigma; } void main() { vec2 invSize = 1.0 / texSize; float sigma = kernelRadius/2.0; float weightSum = gaussianPdf(0.0, sigma); vec4 diffuseSum = texture2D( colorTexture, vUv) * weightSum; vec2 delta = direction * invSize * kernelRadius/float(MAX_RADIUS); vec2 uvOffset = delta; for( int i = 1; i <= MAX_RADIUS; i ++ ) { float x = kernelRadius * float(i) / float(MAX_RADIUS); float w = gaussianPdf(x, sigma); vec4 sample1 = texture2D( colorTexture, vUv + uvOffset); vec4 sample2 = texture2D( colorTexture, vUv - uvOffset); diffuseSum += ((sample1 + sample2) * w); weightSum += (2.0 * w); uvOffset += delta; } gl_FragColor = diffuseSum/weightSum; }` }); } _getOverlayMaterial() { return new ct({ uniforms: { maskTexture: { value: null }, edgeTexture1: { value: null }, edgeTexture2: { value: null }, patternTexture: { value: null }, edgeStrength: { value: 1 }, edgeGlow: { value: 1 }, usePatternTexture: { value: 0 } }, vertexShader: `varying vec2 vUv; void main() { vUv = uv; gl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 ); }`, fragmentShader: `varying vec2 vUv; uniform sampler2D maskTexture; uniform sampler2D edgeTexture1; uniform sampler2D edgeTexture2; uniform sampler2D patternTexture; uniform float edgeStrength; uniform float edgeGlow; uniform bool usePatternTexture; void main() { vec4 edgeValue1 = texture2D(edgeTexture1, vUv); vec4 edgeValue2 = texture2D(edgeTexture2, vUv); vec4 maskColor = texture2D(maskTexture, vUv); vec4 patternColor = texture2D(patternTexture, 6.0 * vUv); float visibilityFactor = 1.0 - maskColor.g > 0.0 ? 1.0 : 0.5; vec4 edgeValue = edgeValue1 + edgeValue2 * edgeGlow; vec4 finalColor = edgeStrength * maskColor.r * edgeValue; if(usePatternTexture) finalColor += + visibilityFactor * (1.0 - maskColor.r) * (1.0 - patternColor.r); gl_FragColor = finalColor; }`, blending: yn, depthTest: !1, depthWrite: !1, transparent: !0 }); } } Ji.BlurDirectionX = new oe(1, 0); Ji.BlurDirectionY = new oe(0, 1); class m_ { outlinePass; hoveredObjects = []; selectedObjects = []; constructor(e, t, i, s) { this.outlinePass = new Ji( new oe(i, s), e, t ), this.outlinePass.edgeStrength = 3, this.outlinePass.edgeGlow = 0.5, this.outlinePass.edgeThickness = 1, this.outlinePass.pulsePeriod = 0, this.outlinePass.visibleEdgeColor.set("#ff9800"), this.outlinePass.hiddenEdgeColor.set("#ff9800"); } /** * 获取 OutlinePass 实例 */ getPass() { return this.outlinePass; } /** * 设置悬停对象(微微高亮) */ setHoveredObjects(e) { this.hoveredObjects = e, this.updateOutline(), e.length > 0 && (this.outlinePass.edgeStrength = 3, this.outlinePass.edgeGlow = 0.5, this.outlinePass.visibleEdgeColor.set("#ff9800"), this.outlinePass.hiddenEdgeColor.set("#ff9800")); } /** * 设置选中对象(强高亮) */ setSelectedObjects(e) { this.selectedObjects = e, this.updateOutline(), e.length > 0 && (this.outlinePass.edgeStrength = 5, this.outlinePass.edgeGlow = 1, this.outlinePass.visibleEdgeColor.set("#00aaff"), this.outlinePass.hiddenEdgeColor.set("#00aaff")); } /** * 清除悬停高亮 */ clearHovered() { this.hoveredObjects = [], this.updateOutline(); } /** * 清除选中高亮 */ clearSelected() { this.selectedObjects = [], this.updateOutline(); } /** * 清除所有高亮 */ clearAll() { this.hoveredObjects = [], this.selectedObjects = [], this.updateOutline(); } /** * 更新 OutlinePass 的选中对象 * 优先级:选中 > 悬停 */ updateOutline() { this.selectedObjects.length > 0 ? (this.outlinePass.selectedObjects = this.selectedObjects, this.outlinePass.edgeStrength = 5, this.outlinePass.edgeGlow = 1, this.outlinePass.visibleEdgeColor.set("#00aaff"), this.outlinePass.hiddenEdgeColor.set("#00aaff")) : this.hoveredObjects.length > 0 ? (this.outlinePass.selectedObjects = this.hoveredObjects, this.outlinePass.edgeStrength = 3, this.outlinePass.edgeGlow = 0.5, this.outlinePass.visibleEdgeColor.set("#ff9800"), this.outlinePass.hiddenEdgeColor.set("#ff9800")) : this.outlinePass.selectedObjects = []; } /** * 更新分辨率 */ resize(e, t) { this.outlinePass.setSize(e, t); } /** * 自定义悬停样式 */ setHoverStyle(e) { e.color && (this.outlinePass.visibleEdgeColor.set(e.color), this.outlinePass.hiddenEdgeColor.set(e.color)), e.strength !== void 0 && (this.outlinePass.edgeStrength = e.strength), e.glow !== void 0 && (this.outlinePass.edgeGlow = e.glow), e.thickness !== void 0 && (this.outlinePass.edgeThickness = e.thickness); } /** * 自定义选中样式 */ setSelectedStyle(e) { } } class g_ { scene; camera; canvas; controls; // OrbitControls outlineManager; // 框选状态 isSelecting = !1; startPoint = new oe(); endPoint = new oe(); ctrlPressed = !1; controlsEnabled = !0; // UI虚线框 selectionBox = null; // 当前框选的对象 selectedObjects = []; constructor(e, t, i, s, n) { this.scene = e, this.camera = t, this.canvas = i, this.controls = s, this.outlineManager = n, this.setupEventListeners(), this.createSelectionBoxElement(); } /** * 创建虚线框UI元素 */ createSelectionBoxElement() { this.selectionBox = document.createElement("div"), this.selectionBox.style.position = "absolute", this.selectionBox.style.border = "2px dashed #00aaff", this.selectionBox.style.backgroundColor = "rgba(0, 170, 255, 0.1)", this.selectionBox.style.pointerEvents = "none", this.selectionBox.style.display = "none", this.selectionBox.style.zIndex = "1000", this.canvas.parentElement && this.canvas.parentElement.appendChild(this.selectionBox); } /** * 设置事件监听器 */ setupEventListeners() { window.addEventListener("keydown", this.onKeyDown.bind(this)), window.addEventListener("keyup", this.onKeyUp.bind(this)), this.canvas.addEventListener("mousedown", this.onMouseDown.bind(this)), this.canvas.addEventListener("mousemove", this.onMouseMove.bind(this)), this.canvas.addEventListener("mouseup", this.onMouseUp.bind(this)); } /** * 按下键盘 */ onKeyDown(e) { (e.key === "Control" || e.key === "Meta") && (this.ctrlPressed = !0); } /** * 松开键盘 */ onKeyUp(e) { (e.key === "Control" || e.key === "Meta") && (this.ctrlPressed = !1, this.isSelecting && this.endSelection()); } /** * 鼠标按下 */ onMouseDown(e) { if (e.button !== 0 || !this.ctrlPressed) return; const t = this.canvas.getBoundingClientRect(); this.startPoint.set(e.clientX - t.left, e.clientY - t.top), this.endPoint.copy(this.startPoint), this.isSelecting = !0, this.controls && this.controls.enabled !== void 0 && (this.controlsEnabled = this.controls.enabled, this.controls.enabled = !1), this.selectionBox && (this.selectionBox.style.display = "block", this.updateSelectionBoxUI()), e.preventDefault(), e.stopPropagation(); } /** * 鼠标移动 */ onMouseMove(e) { if (!this.isSelecting) return; const t = this.canvas.getBoundingClientRect(); this.endPoint.set(e.clientX - t.left, e.clientY - t.top), this.updateSelectionBoxUI(), this.updateSelectedObjects(), e.preventDefault(), e.stopPropagation(); } /** * 鼠标松开 */ onMouseUp(e) { this.isSelecting && (this.endSelection(), e.preventDefault(), e.stopPropagation()); } /** * 结束框选 */ endSelection() { this.isSelecting && (this.isSelecting = !1, this.controls && this.controls.enabled !== void 0 && (this.controls.enabled = this.controlsEnabled), this.selectionBox && (this.selectionBox.style.display = "none"), this.updateSelectedObjects()); } /** * 更新虚线框UI */ updateSelectionBoxUI() { if (!this.selectionBox) return; const e = Math.min(this.startPoint.x, this.endPoint.x), t = Math.min(this.startPoint.y, this.endPoint.y), i = Math.abs(this.endPoint.x - this.startPoint.x), s = Math.abs(this.endPoint.y - this.startPoint.y); this.selectionBox.style.left = `${e}px`, this.selectionBox.style.top = `${t}px`, this.selectionBox.style.width = `${i}px`, this.selectionBox.style.height = `${s}px`; } /** * 更新选中的对象 */ updateSelectedObjects() { const e = this.endPoint.x > this.startPoint.x, t = this.endPoint.y > this.startPoint.y, i = e && t, s = this.canvas.getBoundingClientRect(), n = s.width, a = s.height, o = new oe( Math.min(this.startPoint.x, this.endPoint.x) / n, Math.min(this.startPoint.y, this.endPoint.y) / a ), l = new oe( Math.max(this.startPoint.x, this.endPoint.x) / n, Math.max(this.startPoint.y, this.endPoint.y) / a ), c = []; this.scene.traverse((h) => { if (!h.isMesh || !h.visible) return; const u = h; if (!u.geometry) return; u.geometry.boundingBox || u.geometry.computeBoundingBox(); const d = u.geometry.boundingBox; if (!d) return; const f = this.getBoundingBoxCorners(d, u).map((m) => this.worldToScreen(m)), g = this.getScreenBoundingBox(f); let v = !1; i ? v = this.isFullyContained(g, o, l) : v = this.isPartiallyContained(g, o, l), v && c.push(h); }), this.selectedObjects = c, this.outlineManager.setSelectedObjects(this.selectedObjects); } /** * 获取包围盒的8个顶点 */ getBoundingBoxCorners(e, t) { const i = [], s = e.min, n = e.max; return i.push(new w(s.x, s.y, s.z)), i.push(new w(n.x, s.y, s.z)), i.push(new w(s.x, n.y, s.z)), i.push(new w(n.x, n.y, s.z)), i.push(new w(s.x, s.y, n.z)), i.push(new w(n.x, s.y, n.z)), i.push(new w(s.x, n.y, n.z)), i.push(new w(n.x, n.y, n.z)), i.forEach((a) => { a.applyMatrix4(t.matrixWorld); }), i; } /** * 世界坐标转屏幕坐标(归一化) */ worldToScreen(e) { const t = e.clone(); t.project(this.camera); const i = (t.x + 1) / 2, s = (1 - t.y) / 2; return new oe(i, s); } /** * 获取屏幕空间包围盒 */ getScreenBoundingBox(e) { const t = new oe(1 / 0, 1 / 0), i = new oe(-1 / 0, -1 / 0); return e.forEach((s) => { t.x = Math.min(t.x, s.x), t.y = Math.min(t.y, s.y), i.x = Math.max(i.x, s.x), i.y = Math.max(i.y, s.y); }), { min: t, max: i }; } /** * 判断是否完全包含 */ isFullyContained(e, t, i) { return e.min.x >= t.x && e.min.y >= t.y && e.max.x <= i.x && e.max.y <= i.y; } /** * 判断是否部分包含 */ isPartiallyContained(e, t, i) { return !(e.max.x < t.x || e.min.x > i.x || e.max.y < t.y || e.min.y > i.y); } /** * 清除选中 */ clearSelection() { this.selectedObjects = [], this.outlineManager.clearSelected(); } /** * 获取当前选中的对象 */ getSelectedObjects() { return this.selectedObjects; } /** * 销毁 */ dispose() { window.removeEventListener("keydown", this.onKeyDown.bind(this)), window.removeEventListener("keyup", this.onKeyUp.bind(this)), this.canvas.removeEventListener("mousedown", this.onMouseDown.bind(this)), this.canvas.removeEventListener("mousemove", this.onMouseMove.bind(this)), this.canvas.removeEventListener("mouseup", this.onMouseUp.bind(this)), this.selectionBox && this.selectionBox.parentElement && this.selectionBox.parentElement.removeChild(this.selectionBox), this.clearSelection(); } } class v_ { scene; clippingPlane; stencilGroup = null; isEnabledFlag = !1; capMesh = null; planeInitialized = !1; tempCenter = new w(); sceneBounds = new Rt(); // 截面颜色 (主要颜色) capColor = new _e(16711680); constructor(e) { this.scene = e, this.clippingPlane = new yi(new w(0, -1, 0), 0); } /** * 启用剖切功能 */ enable() { this.isEnabledFlag = !0, this.refresh(); } /** * 禁用剖切功能 */ disable() { this.isEnabledFlag = !1, this.cleanup(); } /** * 刷新剖切几何体 * 当场景中的模型发生变化(加载新模型、移动物体)时调用此方法 */ refresh() { this.isEnabledFlag && (this.cleanupStencilGroup(), this.ensurePlaneInitialized(), this.updateSceneMaterials(!0), this.createStencilGroup()); } /** * 设剖切面位置和方向 * @param normal 法线方向 * @param constant 平面常数 (距离原点的有向距离的相反数) */ setPlane(e, t) { this.planeInitialized = !0, this.clippingPlane.normal.copy(e).normalize(), this.clippingPlane.constant = t, this.isEnabledFlag && this.updateCapPlane(); } isEnabled() { return this.isEnabledFlag; } /** * 设置截面补面颜色 */ setCapColor(e) { if (this.capColor.set(e), this.capMesh) { const t = this.capMesh.material; t.color.copy(this.capColor), t.needsUpdate = !0; } } /** * 遍历场景设置材质的剖切属性 */ updateSceneMaterials(e) { this.scene.traverse((t) => { if (t instanceof nt) { if (t.userData.isStencilCap) return; (Array.isArray(t.material) ? t.material : [t.material]).forEach((i) => { i && (e ? ((!i.clippingPlanes || i.clippingPlanes.indexOf(this.clippingPlane) === -1) && (i.clippingPlanes = [this.clippingPlane]), i.clipShadows = !0) : i.clippingPlanes = [], i.needsUpdate = !0); }); } }); } /** * 创建模板缓冲组 */ createStencilGroup() { this.stencilGroup = new zi(), this.stencilGroup.name = "ClippingStencilGroup", this.scene.add(this.stencilGroup); let e = 0; this.scene.traverse((t) => { if (t instanceof nt && t.visible && !t.userData.isStencilCap) { if (!t.geometry) return; this.createStencilMeshesForObject(t), e++; } }), console.log(`ClippingManager: Generated stencil geometry for ${e} meshes.`), this.addCapPlane(), this.updateCapPlane(); } createStencilMeshesForObject(e) { const t = e.geometry; e.updateMatrixWorld(!0); const i = e.matrixWorld, s = new Bt({ depthWrite: !1, depthTest: !1, colorWrite: !1, stencilWrite: !0, stencilFunc: uo, clippingPlanes: [this.clippingPlane] }), n = s.clone(); n.side = Ft, n.stencilFail = Bn, n.stencilZFail = Bn, n.stencilZPass = Bn; const a = new nt(t, n); a.applyMatrix4(i), a.matrixAutoUpdate = !1, a.userData.isStencilCap = !0, a.renderOrder = 1, this.stencilGroup.add(a); const o = s.clone(); o.side = Ti, o.stencilFail = Fn, o.stencilZFail = Fn, o.stencilZPass = Fn; const l = new nt(t, o); l.applyMatrix4(i), l.matrixAutoUpdate = !1, l.userData.isStencilCap = !0, l.renderOrder = 1, this.stencilGroup.add(l); } addCapPlane() { const e = new Bt({ color: this.capColor, side: Vt, stencilWrite: !0, transparent: !0, opacity: 0, stencilFunc: yu, // Stencil != 0 时绘制 stencilRef: 0, clippingPlanes: [], // 盖板本身不被剖切! depthTest: !0, polygonOffset: !0, polygonOffsetFactor: -1, //稍微拉向摄像机,防止z-fighting polygonOffsetUnits: -1 }), t = new Rs(1e5, 1e5), i = new nt(t, e); i.userData.isCapPlane = !0, i.userData.isStencilCap = !0, i.renderOrder = 2, this.capMesh = i, this.stencilGroup.add(i); } updateCapPlane() { if (!this.stencilGroup || !this.capMesh) return; const e = this.capMesh, t = this.clippingPlane.normal, i = -this.clippingPlane.constant; e.quaternion.setFromUnitVectors(new w(0, 0, 1), t), e.position.copy(t).multiplyScalar(i); } cleanupStencilGroup() { this.stencilGroup && (this.scene.remove(this.stencilGroup), this.stencilGroup.traverse((e) => { e.material && (Array.isArray(e.material) ? e.material.forEach((t) => t.dispose()) : e.material.dispose()), e.geometry && e.userData.isCapPlane && e.geometry.dispose(); }), this.stencilGroup = null, this.capMesh = null); } cleanup() { this.updateSceneMaterials(!1), this.cleanupStencilGroup(); } ensurePlaneInitialized() { if (this.planeInitialized || (this.sceneBounds.makeEmpty(), this.sceneBounds.setFromObject(this.scene), this.sceneBounds.isEmpty())) return; this.sceneBounds.getCenter(this.tempCenter); const e = this.clippingPlane.normal; this.clippingPlane.constant = -e.dot(this.tempCenter), this.planeInitialized = !0, this.updateCapPlane(); } } class __ { // 用户最后一次左键点击的世界坐标(用作相机旋转中心) _lastClickWorldPosition = null; // 用户最后一次左键点击的屏幕坐标 _lastClickScreenPosition = null; constructor() { } /** * 设置最后一次点击的世界坐标 */ setLastClickWorldPosition(e) { this._lastClickWorldPosition = e.clone(); } /** * 获取最后一次点击的世界坐标 */ getLastClickWorldPosition() { return this._lastClickWorldPosition; } /** * 设置最后一次点击的屏幕坐标 */ setLastClickScreenPosition(e) { this._lastClickScreenPosition = e.clone(); } /** * 获取最后一次点击的屏幕坐标 */ getLastClickScreenPosition() { return this._lastClickScreenPosition; } /** * 清除所有点击状态 */ clearClickState() { this._lastClickWorldPosition = null, this._lastClickScreenPosition = null; } } function x_(r) { let e = new Object(); return e.updataSceneOctreeBox = function() { r.octreeBoxModels = []; let t = e.getBoundingBox(); e.ocBox = e.splitBoxIntoAuto(t); let i = 0; r.models.forEach((a) => { a.children.forEach((o) => { o.info.forEach((l) => { n(l, e.ocBox); }); }), i = i + 1; }), s(e.ocBox); function s(a) { for (let o = a.children.length - 1; o >= 0; o--) { let l = a.children[o]; l.isLeaf == !1 && s(l), l.children.length == 0 && (l.isLeaf = !0), l.isLeaf && (l.elements == null || l.elements.length == 0) && a.children.splice(o, 1); } } function n(a, o) { var l = { min: a.box.min, max: a.box.max }; if (e.boxContainBox(o, l) == !0) if (o.elements == null && (o.elements = []), o.isLeaf == !1) { let c = !1; for (let h = 0; h < o.children.length; h++) if (n(a, o.children[h]) == !0) { c = !0; break; } c == !1 && o.elements.push([i, ...a.index]); } else o.elements.push([i, ...a.index]); else return !1; return !0; } }, e.rayInterationModel = function(t) { var i = []; n(t, e.ocBox); var s = a(t, i); return s; function n(o, l) { if (l == null) return; let c = new Rt(l.min, l.max), h = o.ray.intersectsBox(c); if (!(h == null || h == !1)) if (l.children == null || l.children.length == 0) { if (l.elements != null) for (var u of l.elements) i.push(u); } else { if (l.elements != null) for (var u of l.elements) i.push(u); for (let d of l.children) n(o, d); } } function a(o, l) { let c = []; const h = new Bt({ color: 16711680 }); for (let u of l) { let d = r.models[u[0]].children[u[1]]; if (d.TypeName == "Mesh" && d.geometry.groups[u[2]].visibility !== !1) { let f = new nt(d.geometryArray[u[2]], h); f.indexs = u, f.TypeName = d.TypeName, c.push(f); } else d.TypeName == "InstancedMesh" || d.TypeName == "InstancedMesh-Pipe"; } return o.intersectObjects(c, !1); } }, e.boxContainBox = function(t, i) { return i.min.x >= t.min.x && i.min.y >= t.min.y && i.min.z >= t.min.z && i.max.x <= t.max.x && i.max.y <= t.max.y && i.max.z <= t.max.z; }, e.splitBoxIntoAuto = function(t, i = 10) { let s = [], n = [], a = [], o = (t.max.x - t.min.x) * 0.5, l = (t.max.y - t.min.y) * 0.5, c = (t.max.z - t.min.z) * 0.5; if (o > i) { let h = t, u = { min: h.min, max: new w(h.min.x + o, h.max.y, h.max.z) }, d = { min: new w(h.min.x + o, h.min.y, h.min.z), max: h.max }; s.push(u), s.push(d); } if (l > i) for (let h of s) { let u = { min: h.min, max: new w(h.max.x, h.min.y + l, h.max.z) }, d = { min: new w(h.min.x, h.min.y + l, h.min.z), max: h.max }; n.push(u), n.push(d); } else n = s; if (c > i) for (let h of n) { let u = { min: h.min, max: new w(h.max.x, h.max.y, h.min.z + c) }, d = { min: new w(h.min.x, h.min.y, h.min.z + c), max: h.max }; a.push(u), a.push(d); } else a = n; if (t.children = a, t.children.length > 0) { t.isLeaf = !1; for (let h = 0; h < t.children.length; h++) t.children[h] = e.splitBoxIntoAuto(t.children[h]); } else t.isLeaf = !0; return t.length = t.min.distanceTo(t.max), t; }, e.splitBoxInto8 = function(t) { const i = t.min, s = t.max, n = new w().addVectors(i, s).multiplyScalar(0.5), a = []; for (let o = 0; o < 2; o++) for (let l = 0; l < 2; l++) for (let c = 0; c < 2; c++) { const h = new w( o === 0 ? i.x : n.x, l === 0 ? i.y : n.y, c === 0 ? i.z : n.z ), u = new w( o === 1 ? s.x : n.x, l === 1 ? s.y : n.y, c === 1 ? s.z : n.z ), d = new Rt(h, u); a.push(d); } return a; }, e.boundingSphereToBox = function(t) { let i = t.center, s = new w( i.x - t.radius * 0.5, i.y - t.radius * 0.5, i.z - t.radius * 0.5 ), n = new w( i.x + t.radius * 0.5, i.y + t.radius * 0.5, i.z + t.radius * 0.5 ); return { min: s, max: n }; }, e.getBoundingBox = function() { let t = r.models, i = new w(1e8, 1e9, 1e10), s = new w(-1e8, -1e9, -1e10); return t.forEach((n) => { n.children.forEach((a) => { a.geometry.computeBoundingBox(); let o = a.geometry.boundingBox.min, l = a.geometry.boundingBox.max; o.x < i.x && (i.x = o.x), o.y < i.y && (i.y = o.y), o.z < i.z && (i.z = o.z), l.x > s.x && (s.x = l.x), l.y > s.y && (s.y = l.y), l.z > s.z && (s.z = l.z); }); }), { min: i, max: s }; }, e; } var Hr = Object.freeze({ Linear: Object.freeze({ None: function(r) { return r; }, In: function(r) { return r; }, Out: function(r) { return r; }, InOut: function(r) { return r; } }), Quadratic: Object.freeze({ In: function(r) { return r * r; }, Out: function(r) { return r * (2 - r); }, InOut: function(r) { return (r *= 2) < 1 ? 0.5 * r * r : -0.5 * (--r * (r - 2) - 1); } }), Cubic: Object.freeze({ In: function(r) { return r * r * r; }, Out: function(r) { return --r * r * r + 1; }, InOut: function(r) { return (r *= 2) < 1 ? 0.5 * r * r * r : 0.5 * ((r -= 2) * r * r + 2); } }), Quartic: Object.freeze({ In: function(r) { return r * r * r * r; }, Out: function(r) { return 1 - --r * r * r * r; }, InOut: function(r) { return (r *= 2) < 1 ? 0.5 * r * r * r * r : -0.5 * ((r -= 2) * r * r * r - 2); } }), Quintic: Object.freeze({ In: function(r) { return r * r * r * r * r; }, Out: function(r) { return --r * r * r * r * r + 1; }, InOut: function(r) { return (r *= 2) < 1 ? 0.5 * r * r * r * r * r : 0.5 * ((r -= 2) * r * r * r * r + 2); } }), Sinusoidal: Object.freeze({ In: function(r) { return 1 - Math.sin((1 - r) * Math.PI / 2); }, Out: function(r) { return Math.sin(r * Math.PI / 2); }, InOut: function(r) { return 0.5 * (1 - Math.sin(Math.PI * (0.5 - r))); } }), Exponential: Object.freeze({ In: function(r) { return r === 0 ? 0 : Math.pow(1024, r - 1); }, Out: function(r) { return r === 1 ? 1 : 1 - Math.pow(2, -10 * r); }, InOut: function(r) { return r === 0 ? 0 : r === 1 ? 1 : (r *= 2) < 1 ? 0.5 * Math.pow(1024, r - 1) : 0.5 * (-Math.pow(2, -10 * (r - 1)) + 2); } }), Circular: Object.freeze({ In: function(r) { return 1 - Math.sqrt(1 - r * r); }, Out: function(r) { return Math.sqrt(1 - --r * r); }, InOut: function(r) { return (r *= 2) < 1 ? -0.5 * (Math.sqrt(1 - r * r) - 1) : 0.5 * (Math.sqrt(1 - (r -= 2) * r) + 1); } }), Elastic: Object.freeze({ In: function(r) { return r === 0 ? 0 : r === 1 ? 1 : -Math.pow(2, 10 * (r - 1)) * Math.sin((r - 1.1) * 5 * Math.PI); }, Out: function(r) { return r === 0 ? 0 : r === 1 ? 1 : Math.pow(2, -10 * r) * Math.sin((r - 0.1) * 5 * Math.PI) + 1; }, InOut: function(r) { return r === 0 ? 0 : r === 1 ? 1 : (r *= 2, r < 1 ? -0.5 * Math.pow(2, 10 * (r - 1)) * Math.sin((r - 1.1) * 5 * Math.PI) : 0.5 * Math.pow(2, -10 * (r - 1)) * Math.sin((r - 1.1) * 5 * Math.PI) + 1); } }), Back: Object.freeze({ In: function(r) { var e = 1.70158; return r === 1 ? 1 : r * r * ((e + 1) * r - e); }, Out: function(r) { var e = 1.70158; return r === 0 ? 0 : --r * r * ((e + 1) * r + e) + 1; }, InOut: function(r) { var e = 2.5949095; return (r *= 2) < 1 ? 0.5 * (r * r * ((e + 1) * r - e)) : 0.5 * ((r -= 2) * r * ((e + 1) * r + e) + 2); } }), Bounce: Object.freeze({ In: function(r) { return 1 - Hr.Bounce.Out(1 - r); }, Out: function(r) { return r < 1 / 2.75 ? 7.5625 * r * r : r < 2 / 2.75 ? 7.5625 * (r -= 1.5 / 2.75) * r + 0.75 : r < 2.5 / 2.75 ? 7.5625 * (r -= 2.25 / 2.75) * r + 0.9375 : 7.5625 * (r -= 2.625 / 2.75) * r + 0.984375; }, InOut: function(r) { return r < 0.5 ? Hr.Bounce.In(r * 2) * 0.5 : Hr.Bounce.Out(r * 2 - 1) * 0.5 + 0.5; } }), generatePow: function(r) { return r === void 0 && (r = 4), r = r < Number.EPSILON ? Number.EPSILON : r, r = r > 1e4 ? 1e4 : r, { In: function(e) { return Math.pow(e, r); }, Out: function(e) { return 1 - Math.pow(1 - e, r); }, InOut: function(e) { return e < 0.5 ? Math.pow(e * 2, r) / 2 : (1 - Math.pow(2 - e * 2, r)) / 2 + 0.5; } }; } }), _s = function() { return performance.now(); }, y_ = ( /** @class */ (function() { function r() { this._tweens = {}, this._tweensAddedDuringUpdate = {}; } return r.prototype.getAll = function() { var e = this; return Object.keys(this._tweens).map(function(t) { return e._tweens[t]; }); }, r.prototype.removeAll = function() { this._tweens = {}; }, r.prototype.add = function(e) { this._tweens[e.getId()] = e, this._tweensAddedDuringUpdate[e.getId()] = e; }, r.prototype.remove = function(e) { delete this._tweens[e.getId()], delete this._tweensAddedDuringUpdate[e.getId()]; }, r.prototype.update = function(e, t) { e === void 0 && (e = _s()), t === void 0 && (t = !1); var i = Object.keys(this._tweens); if (i.length === 0) return !1; for (; i.length > 0; ) { this._tweensAddedDuringUpdate = {}; for (var s = 0; s < i.length; s++) { var n = this._tweens[i[s]], a = !t; n && n.update(e, a) === !1 && !t && delete this._tweens[i[s]]; } i = Object.keys(this._tweensAddedDuringUpdate); } return !0; }, r; })() ), So = { Linear: function(r, e) { var t = r.length - 1, i = t * e, s = Math.floor(i), n = So.Utils.Linear; return e < 0 ? n(r[0], r[1], i) : e > 1 ? n(r[t], r[t - 1], t - i) : n(r[s], r[s + 1 > t ? t : s + 1], i - s); }, Utils: { Linear: function(r, e, t) { return (e - r) * t + r; } } }, Ih = ( /** @class */ (function() { function r() { } return r.nextId = function() { return r._nextId++; }, r._nextId = 0, r; })() ), bo = new y_(), M_ = ( /** @class */ (function() { function r(e, t) { t === void 0 && (t = bo), this._object = e, this._group = t, this._isPaused = !1, this._pauseStart = 0, this._valuesStart = {}, this._valuesEnd = {}, this._valuesStartRepeat = {}, this._duration = 1e3, this._isDynamic = !1, this._initialRepeat = 0, this._repeat = 0, this._yoyo = !1, this._isPlaying = !1, this._reversed = !1, this._delayTime = 0, this._startTime = 0, this._easingFunction = Hr.Linear.None, this._interpolationFunction = So.Linear, this._chainedTweens = [], this._onStartCallbackFired = !1, this._onEveryStartCallbackFired = !1, this._id = Ih.nextId(), this._isChainStopped = !1, this._propertiesAreSetUp = !1, this._goToEnd = !1; } return r.prototype.getId = function() { return this._id; }, r.prototype.isPlaying = function() { return this._isPlaying; }, r.prototype.isPaused = function() { return this._isPaused; }, r.prototype.getDuration = function() { return this._duration; }, r.prototype.to = function(e, t) { if (t === void 0 && (t = 1e3), this._isPlaying) throw new Error("Can not call Tween.to() while Tween is already started or paused. Stop the Tween first."); return this._valuesEnd = e, this._propertiesAreSetUp = !1, this._duration = t < 0 ? 0 : t, this; }, r.prototype.duration = function(e) { return e === void 0 && (e = 1e3), this._duration = e < 0 ? 0 : e, this; }, r.prototype.dynamic = function(e) { return e === void 0 && (e = !1), this._isDynamic = e, this; }, r.prototype.start = function(e, t) { if (e === void 0 && (e = _s()), t === void 0 && (t = !1), this._isPlaying) return this; if (this._group && this._group.add(this), this._repeat = this._initialRepeat, this._reversed) { this._reversed = !1; for (var i in this._valuesStartRepeat) this._swapEndStartRepeatValues(i), this._valuesStart[i] = this._valuesStartRepeat[i]; } if (this._isPlaying = !0, this._isPaused = !1, this._onStartCallbackFired = !1, this._onEveryStartCallbackFired = !1, this._isChainStopped = !1, this._startTime = e, this._startTime += this._delayTime, !this._propertiesAreSetUp || t) { if (this._propertiesAreSetUp = !0, !this._isDynamic) { var s = {}; for (var n in this._valuesEnd) s[n] = this._valuesEnd[n]; this._valuesEnd = s; } this._setupProperties(this._object, this._valuesStart, this._valuesEnd, this._valuesStartRepeat, t); } return this; }, r.prototype.startFromCurrentValues = function(e) { return this.start(e, !0); }, r.prototype._setupProperties = function(e, t, i, s, n) { for (var a in i) { var o = e[a], l = Array.isArray(o), c = l ? "array" : typeof o, h = !l && Array.isArray(i[a]); if (!(c === "undefined" || c === "function")) { if (h) { var u = i[a]; if (u.length === 0) continue; for (var d = [o], f = 0, g = u.length; f < g; f += 1) { var v = this._handleRelativeValue(o, u[f]); if (isNaN(v)) { h = !1, console.warn("Found invalid interpolation list. Skipping."); break; } d.push(v); } h && (i[a] = d); } if ((c === "object" || l) && o && !h) { t[a] = l ? [] : {}; var m = o; for (var p in m) t[a][p] = m[p]; s[a] = l ? [] : {}; var u = i[a]; if (!this._isDynamic) { var y = {}; for (var p in u) y[p] = u[p]; i[a] = u = y; } this._setupProperties(m, t[a], u, s[a], n); } else (typeof t[a] > "u" || n) && (t[a] = o), l || (t[a] *= 1), h ? s[a] = i[a].slice().reverse() : s[a] = t[a] || 0; } } }, r.prototype.stop = function() { return this._isChainStopped || (this._isChainStopped = !0, this.stopChainedTweens()), this._isPlaying ? (this._group && this._group.remove(this), this._isPlaying = !1, this._isPaused = !1, this._onStopCallback && this._onStopCallback(this._object), this) : this; }, r.prototype.end = function() { return this._goToEnd = !0, this.update(1 / 0), this; }, r.prototype.pause = function(e) { return e === void 0 && (e = _s()), this._isPaused || !this._isPlaying ? this : (this._isPaused = !0, this._pauseStart = e, this._group && this._group.remove(this), this); }, r.prototype.resume = function(e) { return e === void 0 && (e = _s()), !this._isPaused || !this._isPlaying ? this : (this._isPaused = !1, this._startTime += e - this._pauseStart, this._pauseStart = 0, this._group && this._group.add(this), this); }, r.prototype.stopChainedTweens = function() { for (var e = 0, t = this._chainedTweens.length; e < t; e++) this._chainedTweens[e].stop(); return this; }, r.prototype.group = function(e) { return e === void 0 && (e = bo), this._group = e, this; }, r.prototype.delay = function(e) { return e === void 0 && (e = 0), this._delayTime = e, this; }, r.prototype.repeat = function(e) { return e === void 0 && (e = 0), this._initialRepeat = e, this._repeat = e, this; }, r.prototype.repeatDelay = function(e) { return this._repeatDelayTime = e, this; }, r.prototype.yoyo = function(e) { return e === void 0 && (e = !1), this._yoyo = e, this; }, r.prototype.easing = function(e) { return e === void 0 && (e = Hr.Linear.None), this._easingFunction = e, this; }, r.prototype.interpolation = function(e) { return e === void 0 && (e = So.Linear), this._interpolationFunction = e, this; }, r.prototype.chain = function() { for (var e = [], t = 0; t < arguments.length; t++) e[t] = arguments[t]; return this._chainedTweens = e, this; }, r.prototype.onStart = function(e) { return this._onStartCallback = e, this; }, r.prototype.onEveryStart = function(e) { return this._onEveryStartCallback = e, this; }, r.prototype.onUpdate = function(e) { return this._onUpdateCallback = e, this; }, r.prototype.onRepeat = function(e) { return this._onRepeatCallback = e, this; }, r.prototype.onComplete = function(e) { return this._onCompleteCallback = e, this; }, r.prototype.onStop = function(e) { return this._onStopCallback = e, this; }, r.prototype.update = function(e, t) { var i = this, s; if (e === void 0 && (e = _s()), t === void 0 && (t = !0), this._isPaused) return !0; var n, a = this._startTime + this._duration; if (!this._goToEnd && !this._isPlaying) { if (e > a) return !1; t && this.start(e, !0); } if (this._goToEnd = !1, e < this._startTime) return !0; this._onStartCallbackFired === !1 && (this._onStartCallback && this._onStartCallback(this._object), this._onStartCallbackFired = !0), this._onEveryStartCallbackFired === !1 && (this._onEveryStartCallback && this._onEveryStartCallback(this._object), this._onEveryStartCallbackFired = !0); var o = e - this._startTime, l = this._duration + ((s = this._repeatDelayTime) !== null && s !== void 0 ? s : this._delayTime), c = this._duration + this._repeat * l, h = function() { if (i._duration === 0 || o > c) return 1; var m = Math.trunc(o / l), p = o - m * l, y = Math.min(p / i._duration, 1); return y === 0 && o === i._duration ? 1 : y; }, u = h(), d = this._easingFunction(u); if (this._updateProperties(this._object, this._valuesStart, this._valuesEnd, d), this._onUpdateCallback && this._onUpdateCallback(this._object, u), this._duration === 0 || o >= this._duration) if (this._repeat > 0) { var f = Math.min(Math.trunc((o - this._duration) / l) + 1, this._repeat); isFinite(this._repeat) && (this._repeat -= f); for (n in this._valuesStartRepeat) !this._yoyo && typeof this._valuesEnd[n] == "string" && (this._valuesStartRepeat[n] = // eslint-disable-next-line // @ts-ignore FIXME? this._valuesStartRepeat[n] + parseFloat(this._valuesEnd[n])), this._yoyo && this._swapEndStartRepeatValues(n), this._valuesStart[n] = this._valuesStartRepeat[n]; return this._yoyo && (this._reversed = !this._reversed), this._startTime += l * f, this._onRepeatCallback && this._onRepeatCallback(this._object), this._onEveryStartCallbackFired = !1, !0; } else { this._onCompleteCallback && this._onCompleteCallback(this._object); for (var g = 0, v = this._chainedTweens.length; g < v; g++) this._chainedTweens[g].start(this._startTime + this._duration, !1); return this._isPlaying = !1, !1; } return !0; }, r.prototype._updateProperties = function(e, t, i, s) { for (var n in i) if (t[n] !== void 0) { var a = t[n] || 0, o = i[n], l = Array.isArray(e[n]), c = Array.isArray(o), h = !l && c; h ? e[n] = this._interpolationFunction(o, s) : typeof o == "object" && o ? this._updateProperties(e[n], a, o, s) : (o = this._handleRelativeValue(a, o), typeof o == "number" && (e[n] = a + (o - a) * s)); } }, r.prototype._handleRelativeValue = function(e, t) { return typeof t != "string" ? t : t.charAt(0) === "+" || t.charAt(0) === "-" ? e + parseFloat(t) : parseFloat(t); }, r.prototype._swapEndStartRepeatValues = function(e) { var t = this._valuesStartRepeat[e], i = this._valuesEnd[e]; typeof i == "string" ? this._valuesStartRepeat[e] = this._valuesStartRepeat[e] + parseFloat(i) : this._valuesStartRepeat[e] = this._valuesEnd[e], this._valuesEnd[e] = t; }, r; })() ); Ih.nextId; var wi = bo; wi.getAll.bind(wi); wi.removeAll.bind(wi); wi.add.bind(wi); wi.remove.bind(wi); wi.update.bind(wi); var ba = { Easing: Hr, Tween: M_ }; function S_() { return new zo(); } function b_(r, e) { r.appendChild(e.domElement); } function T_(r, e, t) { var i = new Object(); i.visible = !0; let s = null, n, a, o = []; i.init = function() { n || (c(), h(), u()); }, i.Hide = function() { n.style.display = "none", i.visible = !1; }, i.Show = function() { n.style.display = "block", i.visible = !0; }, i.RenderScene = function() { i.camera.quaternion.copy(e.camera.quaternion); let g = new w(0, 0, -1).clone().applyMatrix4(e.camera.matrixWorld.clone()), v = e.camera.position.clone().sub(g.clone()).setLength(100); i.camera.position.copy(v), i.camera.lookAt(new w()), i.sceneOrtho.renderer.render(i.sceneOrtho, i.camera); }, i.ToggleDirectionView = function(g) { console.log(g); var v = new w(0, 0, 0); g == "top" ? v = new w(0, 1, 0) : g == "down" ? v = new w(0, -1, 0) : g == "front" ? v = new w(0, 0, 1) : g == "left" ? v = new w(-1, 0, 0) : g == "back" ? v = new w(0, 0, -1) : g == "right" ? v = new w(1, 0, 0) : g == "top_front" ? v = new w(1, 1, 0) : g == "top_left" ? v = new w(0, 1, -1) : g == "top_back" ? v = new w(-1, 1, 0) : g == "top_right" ? v = new w(0, 1, 1) : g == "down_front" ? v = new w(1, -1, 0) : g == "down_left" ? v = new w(0, -1, -1) : g == "down_back" ? v = new w(-1, -1, 0) : g == "down_right" ? v = new w(0, -1, 1) : g == "front_right" ? v = new w(1, 0, 1) : g == "right_back" ? v = new w(-1, 0, 1) : g == "back_left" ? v = new w(-1, 0, -1) : g == "left_front" ? v = new w(1, 0, -1) : g == "top_left_front" ? v = new w(1, 1, -1) : g == "top_front_right" ? v = new w(1, 1, 1) : g == "top_right_back" ? v = new w(-1, 1, 1) : g == "top_back_left" ? v = new w(-1, 1, -1) : g == "button_left_front" ? v = new w(1, -1, -1) : g == "button_front_right" ? v = new w(1, -1, 1) : g == "button_right_back" ? v = new w(-1, 1, 1) : g == "button_back_left" && (v = new w(-1, -1, -1)); var m = r.octreeBox.getBoundingBox(), p = m.min, y = m.max, _ = p.clone().add(y.clone()).multiplyScalar(0.5), E = _.clone().add(v.multiplyScalar(1 * y.distanceTo(p))); l(e.camera.position, E, r.controls.target.clone(), _); }, i.GetCameraPose = function() { var g = e.camera.quaternion, v = e.camera.position, m = r.controls.target, p = { quaternion: g, position: v, target: m }; return p; }, i.ReductionCameraPose = function(g, v = 1e3, m) { var p = new mi( g.quaternion._x, g.quaternion._y, g.quaternion._z, g.quaternion._w ), y = new w(g.position.x, g.position.y, g.position.z), _ = new w(g.target.x, g.target.y, g.target.z); let E = !1; l( e.camera.position, y, r.controls.target.clone(), _, e.camera.quaternion, p, v, (A) => { m && (E || (m(A), E = !0)); } ), m && setTimeout(() => { E || (m(!0), E = !0); }, v + 10); }, i.CameraGoHome = function() { var g = r.octreeBox.getBoundingBox(), v = g.min.clone().add(g.max.clone()).multiplyScalar(0.5); let m = new w(1, 1, 1); var p = v.clone().add(m.multiplyScalar(1 * g.max.distanceTo(g.min))); l(e.camera.position, p, r.controls.target.clone(), v); }; function l(g, v, m, p, y, _, E = 1e3, A) { var T; y && _ ? (T = new ba.Tween({ x1: g.x, // 相机当前位置x y1: g.y, // 相机当前位置y z1: g.z, // 相机当前位置z x2: m.x, // 控制当前的中心点x y2: m.y, // 控制当前的中心点y z2: m.z, // 控制当前的中心点z _x: y._x, // 相机当前quaternion _y: y._y, // 相机当前quaternion _z: y._z, // 相机当前quaternion _w: y._w // 相机当前quaternion }), T.to( { x1: v.x, // 新的相机位置x y1: v.y, // 新的相机位置y z1: v.z, // 新的相机位置z x2: p.x, // 新的控制中心点位置x y2: p.y, // 新的控制中心点位置x z2: p.z, // 新的控制中心点位置x _x: _._x, // 新的相机quaternion _y: _._y, // 新的相机quaternion _z: _._z, // 新的相机quaternion _w: _._w // 新的相机quaternion }, E )) : (T = new ba.Tween({ x1: g.x, // 相机当前位置x y1: g.y, // 相机当前位置y z1: g.z, // 相机当前位置z x2: m.x, // 控制当前的中心点x y2: m.y, // 控制当前的中心点y z2: m.z // 控制当前的中心点z }), T.to( { x1: v.x, // 新的相机位置x y1: v.y, // 新的相机位置y z1: v.z, // 新的相机位置z x2: p.x, // 新的控制中心点位置x y2: p.y, // 新的控制中心点位置x z2: p.z // 新的控制中心点位置x }, E )), T.onUpdate(function(I) { y && _ ? (e.camera.quaternion._x = I._x, e.camera.quaternion._y = I._y, e.camera.quaternion._z = I._z, e.camera.quaternion._w = I._w) : r.controls.auto = !0, e.camera.position.x = I.x1, e.camera.position.y = I.y1, e.camera.position.z = I.z1, r.controls.target.x = I.x2, r.controls.target.y = I.y2, r.controls.target.z = I.z2, r.controls.update(), i.RenderScene(); }), T.onComplete(function(I) { r.controls.auto = !1, i.RenderScene(), A && A(!0), cancelAnimationFrame(s), s = null; }), T.easing(ba.Easing.Cubic.InOut); function R(I) { s = requestAnimationFrame(R), T.update(); } T.start(), R(); } function c() { n = document.createElement("div"), n.className = "ViewCube", t.appendChild(n), a = document.createElement("div"), a.className = "ViewAttr", t.appendChild(a); } function h() { i.sceneOrtho = S_(); var m = window.innerWidth, p = window.innerHeight, g = m > p ? m / p : p / m, v = 150; i.camera = new mr( v * g / -2, v * g / 2, 2 * v / 2, 1.4 * v / -2, 0.01, 1e4 ); var m = n.clientWidth, p = n.clientHeight, y = new Rn({ alpha: !0 }); y.setSize(m, p), y.setClearAlpha(0), i.sceneOrtho.renderer = y; let _ = new Mh(16777215, 0.8); i.sceneOrtho.add(_), b_(n, y); } function u() { let g = [ { label: "右", icon: "cube/cn_right.png" }, { label: "左", icon: "cube/cn_left.png" }, { label: "顶", icon: "cube/cn_top.png" }, { label: "底", icon: "cube/cn_bottom.png" }, { label: "前", icon: "cube/cn_front.png" }, { label: "后", icon: "cube/cn_back.png" } ]; var v = []; for (const p of g) v.push( new Bt({ color: 16777215, map: new xh().load(p.icon) }) ); new Ld({ color: 255 }); var m = new nt(new fr(110, 110, 110), v); i.sceneOrtho.add(m), d(122), n.addEventListener("mousedown", (p) => { var y = {}; y.x = p.offsetX / n.clientWidth * 2 - 1, y.y = -(p.offsetY / n.clientHeight) * 2 + 1; var _ = new Zl(); _.setFromCamera(y, i.camera); const E = _.intersectObjects(o, !1); E.length > 0 && i.ToggleDirectionView(E[0].object.name); }), n.addEventListener("mousemove", (p) => { var y = {}; y.x = p.offsetX / n.clientWidth * 2 - 1, y.y = -(p.offsetY / n.clientHeight) * 2 + 1; var _ = new Zl(); _.setFromCamera(y, i.camera); const E = _.intersectObjects(o, !1); for (var A of o) A.material.opacity = 0.01; E.length > 0 && (E[0].object.material.opacity = 0.2); }); } function d(g) { for (var v = g * 0.5 - 20, m = [ { name: "right", a: 30, b: 75, c: 75, point: new w(v, 0, 0) }, { name: "back", a: 75, b: 75, c: 30, point: new w(0, 0, -v) }, { name: "left", a: 30, b: 75, c: 75, point: new w(-v, 0, 0) }, { name: "front", a: 75, b: 75, c: 30, point: new w(0, 0, v) }, { name: "top", a: 75, b: 30, c: 75, point: new w(0, v, 0) }, { name: "button", a: 75, b: 30, c: 75, point: new w(0, -v, 0) } ], p = [ { name: "top_right_back", a: 30, b: 30, c: 30, point: new w(-v, v, v) }, { name: "button_front_right", a: 30, b: 30, c: 30, point: new w(-v, -v, v) }, { name: "top_front_right", a: 30, b: 30, c: 30, point: new w(v, v, v) }, { name: "button_right_back", a: 30, b: 30, c: 30, point: new w(v, -v, v) }, { name: "top_back_left", a: 30, b: 30, c: 30, point: new w(-v, v, -v) }, { name: "button_back_left", a: 30, b: 30, c: 30, point: new w(-v, -v, -v) }, { name: "top_left_front", a: 30, b: 30, c: 30, point: new w(v, v, -v) }, { name: "button_left_front", a: 30, b: 30, c: 30, point: new w(v, -v, -v) } ], y = [ { name: "top_front", a: 30, b: 30, c: 75, point: new w(v, v, 0) }, { name: "top_right", a: 75, b: 30, c: 30, point: new w(0, v, v) }, { name: "top_back", a: 30, b: 30, c: 75, point: new w(-v, v, 0) }, { name: "top_left", a: 75, b: 30, c: 30, point: new w(0, v, -v) }, { name: "button_front", a: 30, b: 30, c: 75, point: new w(v, -v, 0) }, { name: "button_right", a: 75, b: 30, c: 30, point: new w(0, -v, v) }, { name: "button_back", a: 30, b: 30, c: 75, point: new w(-v, -v, 0) }, { name: "button_left", a: 75, b: 30, c: 30, point: new w(0, -v, -v) }, { name: "front_right", a: 30, b: 75, c: 30, point: new w(v, 0, v) }, { name: "right_back", a: 30, b: 75, c: 30, point: new w(-v, 0, v) }, { name: "back_left", a: 30, b: 75, c: 30, point: new w(-v, 0, -v) }, { name: "left_front", a: 30, b: 75, c: 30, point: new w(v, 0, -v) } ], _ = 0; _ < m.length; _++) o.push(f(m[_])); for (var _ = 0; _ < p.length; _++) o.push(f(p[_])); for (var _ = 0; _ < y.length; _++) o.push(f(y[_])); } function f(g) { const v = new fr(g.a, g.b, g.c), m = new Bt({ color: "blue", transparent: !0, opacity: 0.01 }), p = new Ue().makeTranslation(g.point.x, g.point.y, g.point.z); let y = v.applyMatrix4(p), _ = new nt(y, m); return _.name = g.name, i.sceneOrtho.add(_), _; } return i; } class Lc { constructor(e, t) { this.object = e, this.id = t; } get uuid() { return this.object.uuid; } get name() { return this.object.name; } set name(e) { this.object.name = e; } get visible() { return this.object.visible; } set visible(e) { this.object.visible = e; } getBoundingBox() { const e = new Rt().setFromObject(this.object); return { min: e.min, max: e.max }; } setMatrix(e) { this.object.matrix.fromArray(e), this.object.matrix.decompose(this.object.position, this.object.quaternion, this.object.scale); } } let E_ = class { constructor(r, e, t) { this.manager = r, this.scene = e, this.clippingManager = t; } models = /* @__PURE__ */ new Map(); async loadModel(r, e) { const t = await this.manager.loadGLTF(r), i = e?.id || t.uuid; t.name = i, e?.position && t.position.fromArray(e.position), e?.scale && t.scale.fromArray(e.scale), e?.rotation && t.rotation.setFromVector3(new w(...e.rotation)); const s = new Lc(t, i); return this.models.set(i, s), this.clippingManager?.refresh(), s; } unloadModel(r) { const e = this.models.get(r); e && e instanceof Lc && (this.scene.remove(e.object), this.models.delete(r)); } getAllModels() { return Array.from(this.models.values()); } getModel(r) { return this.models.get(r); } }, w_ = class { constructor(r) { this.manager = r; } setView(r, e) { this.manager.setView(r); } fitToView(r, e) { console.log("[V1] fitToView not fully implemented in manager, resetting camera"), this.manager.camera.position.set(20, 20, 20), this.manager.camera.lookAt(0, 0, 0), this.manager.controls.update(); } goHome(r) { this.manager.camera.position.set(20, 20, 20), this.manager.camera.lookAt(0, 0, 0), this.manager.controls.update(); } setProjection(r) { console.warn("[V1] Projection switching not supported in V1 CameraManager"); } setNavigationMode(r) { r === An.PanOnly ? this.manager.controls.enableRotate = !1 : this.manager.controls.enableRotate = !0; } getState() { return { position: this.manager.camera.position.toArray(), target: this.manager.controls.target.toArray(), up: this.manager.camera.up.toArray(), projection: Nr.Perspective }; } restoreState(r, e) { this.manager.camera.position.fromArray(r.position), this.manager.camera.up.fromArray(r.up), this.manager.controls.target.fromArray(r.target), this.manager.controls.update(); } }, C_ = class { constructor(r, e) { this.manager = r, this.scene = e; } getSelection() { return console.warn("[V1] getSelection not fully supported by InteractionManager"), []; } select(r) { const e = []; this.scene.traverse((t) => { t instanceof nt && r.includes(t.name) && e.push(t); }), this.manager.highlight(e); } addSelection(r) { this.select(r); } removeSelection(r) { this.manager.clearHighlight(); } clearSelection() { this.manager.clearHighlight(); } getHiddenComponents() { const r = []; return this.scene.traverse((e) => { e.visible || r.push(e.name); }), r; } setVisibility(r, e) { this.manager.setVisibility(r, e); } isolate(r) { this.scene.traverse((e) => e.visible = !1), this.setVisibility(r, !0); } clearIsolation() { this.scene.traverse((r) => r.visible = !0); } setColor(r, e) { console.warn("[V1] setColor not implemented"); } restoreColor(r) { console.warn("[V1] restoreColor not implemented"); } setOpacity(r, e) { console.warn("[V1] setOpacity not implemented"); } restoreOpacity(r) { console.warn("[V1] restoreOpacity not implemented"); } clearAllOverrides() { } getBoundingBox(r) { let e; if (this.scene.traverse((t) => { t.name === r && (e = t); }), e) { const t = new Rt().setFromObject(e); return { min: t.min, max: t.max }; } return { min: { x: 0, y: 0, z: 0 }, max: { x: 0, y: 0, z: 0 } }; } }, R_ = class { constructor(r, e) { this.sceneManager = r, this.renderer = e; } setBackgroundColor(r) { this.sceneManager.setBackground(r); } setSkybox(r) { const e = new _h().load(r); this.sceneManager.scene.background = e; } enableShadows(r) { } enableAntialiasing(r) { } enableAmbientOcclusion(r) { } addSectionPlane(r, e) { return ""; } removeSectionPlane(r) { } clearSectionPlanes() { } enableSectioning(r) { } captureScreen(r, e) { return this.renderer.domElement.toDataURL(); } getViewerConfig() { return { shadows: !1, ambientOcclusion: !1, sectioning: !1 }; } getRenderStatistics() { const r = this.renderer.info || {}, e = r.render || {}, t = r.memory || {}; return { calls: e.calls || 0, triangles: e.triangles || 0, points: e.points || 0, lines: e.lines || 0, memory: { geometries: t.geometries || 0, textures: t.textures || 0 } }; } }, A_ = class { async getProperties(r) { return [ { name: "Identity Data", properties: [ { name: "Element ID", value: r }, { name: "Version", value: "V1 Engine" } ] } ]; } async getPropertyValue(r, e) { return "Unknown"; } async getModelTree(r) { return [ { id: "root", name: "Model Root (V1)", type: "Model", hasChildren: !1 } ]; } async search(r) { return []; } }, P_ = class { activeTool = null; tools = /* @__PURE__ */ new Map(); activate(r, e) { console.log(`[V1] Activating tool: ${r}`, e), this.activeTool = r; } deactivate() { this.activeTool && (console.log(`[V1] Deactivating tool: ${this.activeTool}`), this.activeTool = null); } getActiveTool() { return this.activeTool; } registerTool(r, e) { this.tools.set(r, e); } }, D_ = class { listeners = /* @__PURE__ */ new Map(); on(r, e) { this.listeners.has(r) || this.listeners.set(r, []), this.listeners.get(r).push(e); } off(r, e) { if (!this.listeners.has(r)) return; const t = this.listeners.get(r), i = t.indexOf(e); i !== -1 && t.splice(i, 1); } trigger(r, e) { this.listeners.has(r) && this.listeners.get(r).forEach((t) => { try { t(e); } catch (i) { console.error(`Error in event listener for ${r}:`, i); } }); } }, L_ = class { container; renderer; // WebGPURenderer or WebGLRenderer composer = null; stats = null; // Global Engine State engineState; // Internal Managers (Legacy V1 architecture) sceneManager; cameraManager; loaderManager; interactionManager; outlineManager; selectionBoxManager = null; clippingManager; octreeBox; // 公共接口 loader; cameraTool; components; data; viewer; tools; events; // 内部的一些类 viewCube; scene; camera; models; controls; measure; animationId = null; constructor(r) { const e = document.getElementById(r.containerId); if (!e) throw new Error(`Container ${r.containerId} not found`); this.container = e, this.models = [], this.engineState = new __(), this.sceneManager = new _0(r); const { width: t, height: i } = this.getContainerSize(); this.cameraManager = new L0(this.container, t, i, this.engineState); try { this.renderer = new Rn({ antialias: r.antialias ?? !0 }), console.log("Engine: Using WebGPURenderer"); } catch (s) { console.warn("WebGPURenderer failed", s), this.renderer = new Rn({ antialias: r.antialias ?? !0 }); } this.renderer.setSize(t, i), this.renderer.setPixelRatio(window.devicePixelRatio), this.renderer.shadowMap.enabled = !0, this.renderer.shadowMap.type = Fc, this.renderer.toneMapping = Eo, this.renderer.toneMappingExposure = 1, this.renderer.localClippingEnabled = !0, this.container.appendChild(this.renderer.domElement), this.loaderManager = new p_(this.sceneManager.scene), this.outlineManager = new m_( this.sceneManager.scene, this.cameraManager.camera, t, i ), this.interactionManager = new f_( this.sceneManager.scene, this.cameraManager.camera, this.renderer.domElement, this.engineState ), this.selectionBoxManager = new g_( this.sceneManager.scene, this.cameraManager.camera, this.renderer.domElement, this.cameraManager.controls, this.outlineManager ), this.clippingManager = new v_(this.sceneManager.scene), setTimeout(() => { this.clippingManager.enable(); }, 1e3), this.events = new D_(), this.interactionManager.setEventModule(this.events), this.loader = new E_(this.loaderManager, this.sceneManager.scene, this.clippingManager), this.cameraTool = new w_(this.cameraManager), this.components = new C_(this.interactionManager, this.sceneManager.scene), this.viewer = new R_(this.sceneManager, this.renderer), this.data = new A_(), this.tools = new P_(), this.scene = this.sceneManager.scene, this.scene.camera = this.cameraManager.camera, this.camera = this.cameraManager.camera, this.controls = this.cameraManager.controls, this.octreeBox = x_(this), this.viewCube = T_(this, this.scene, this.container), this.viewCube.init(), this.setupVisuals(), this.setupPostProcessing(), r.showStats !== !1 && this.initStats(), this.setupResizeObserver(), this.animate(); } initStats() { this.stats = new v0(), this.stats.showPanel(0), this.stats.dom.style.position = "absolute", this.stats.dom.style.top = "0px", this.stats.dom.style.left = "0px", this.stats.dom.style.zIndex = "1000", this.container.appendChild(this.stats.dom); } toggleStats(r) { r && !this.stats ? this.initStats() : !r && this.stats && (this.container.removeChild(this.stats.dom), this.stats = null); } getVersion() { return "1.2.0 (WebGPU Experimental)"; } setupVisuals() { const r = this.sceneManager.scene; r.children.filter((s) => s instanceof Ps).forEach((s) => r.remove(s)); const e = new yh(16777215, 4.5); e.position.set(10, 20, 10), e.castShadow = !0, e.shadow.mapSize.width = 4096, e.shadow.mapSize.height = 4096, e.shadow.camera.near = 0.1, e.shadow.camera.far = 500, e.shadow.bias = -5e-5, e.shadow.normalBias = 0.02; const t = 50; e.shadow.camera.left = -t, e.shadow.camera.right = t, e.shadow.camera.top = t, e.shadow.camera.bottom = -t, e.shadow.radius = 2, r.add(e); const i = new Mh(4210752, 0.4); r.add(i), new Qv().load("https://raw.githubusercontent.com/mrdoob/three.js/master/examples/textures/equirectangular/royal_esplanade_1k.hdr", (s) => { s.mapping = Mn, r.environment = s, r.environmentIntensity = 1; }); } setupPostProcessing() { if (!this.renderer) return; const { width: r, height: e } = this.getContainerSize(), t = window.devicePixelRatio, i = this.sceneManager.scene, s = this.cameraManager.camera; this.composer = new s0(this.renderer), this.composer.setPixelRatio(t), this.composer.setSize(r, e); const n = new n0(i, s); this.composer.addPass(n); const a = new ai(i, s, r, e); a.output = ai.OUTPUT.Default, a.blendIntensity = 1, a.updateGtaoMaterial && a.updateGtaoMaterial({ radius: 3, // 减小半径以获得更紧密、更逼真的接触阴影 (原为 10) distanceExponent: 1, // 衰减 thickness: 1, // 厚度 scale: 1, // 缩放 distanceFallOff: 1, // 距离衰减 screenSpaceRadius: !1 }), this.composer.addPass(a); const o = this.outlineManager.getPass(); this.composer.addPass(o); const l = new $r( new oe(r, e), 0.05, // 强度 0.1, // 半径 0.5 // 阈值 ); this.composer.addPass(l); const c = new u0(); this.composer.addPass(c); const h = new _o(d0); h.material.uniforms.resolution.value.x = 1 / (r * t), h.material.uniforms.resolution.value.y = 1 / (e * t), this.composer.addPass(h); } resize() { const { width: r, height: e } = this.getContainerSize(), t = window.devicePixelRatio; if (this.cameraManager.updateAspect(r, e), this.renderer.setSize(r, e), this.renderer.setPixelRatio(t), this.outlineManager && this.outlineManager.resize(r, e), this.composer) { this.composer.setPixelRatio(t), this.composer.setSize(r, e); const i = this.composer.passes.find((s) => s instanceof _o && s.material.uniforms.resolution); i && (i.material.uniforms.resolution.value.x = 1 / (r * t), i.material.uniforms.resolution.value.y = 1 / (e * t)); } } getContainerSize() { return { width: this.container.clientWidth, height: this.container.clientHeight }; } setupResizeObserver() { new ResizeObserver(() => { this.resize(); }).observe(this.container); } animate = () => { this.animationId = requestAnimationFrame(this.animate), this.viewCube.RenderScene(), this.stats && this.stats.begin(), this.cameraManager.tick(), this.composer ? this.composer.render() : this.renderer.renderAsync ? this.renderer.renderAsync(this.sceneManager.scene, this.cameraManager.camera) : this.renderer.render(this.sceneManager.scene, this.cameraManager.camera), this.stats && this.stats.end(); }; dispose() { this.animationId && cancelAnimationFrame(this.animationId), this.selectionBoxManager && this.selectionBoxManager.dispose(), this.renderer.dispose(), this.container.innerHTML = ""; } }; class Ic { constructor(e, t, i) { this.object = e, this.id = t, this.uuid = i, this.object.name = t; } get name() { return this.object.name; } set name(e) { this.object.name = e; } get visible() { return this.object.visible; } set visible(e) { this.object.visible = e; } getBoundingBox() { const e = new Rt().setFromObject(this.object); return { min: e.min, max: e.max }; } setMatrix(e) { this.object.matrix.fromArray(e), this.object.matrix.decompose(this.object.position, this.object.quaternion, this.object.scale); } } class I_ { scene; gltfLoader; models = /* @__PURE__ */ new Map(); constructor(e) { this.scene = e, this.gltfLoader = new Ph(); } async loadModel(e, t) { return new Promise((i, s) => { this.gltfLoader.load( e, (n) => { const a = n.scene, o = t?.id || No.generateUUID(); t?.position && a.position.fromArray(t.position), t?.scale && a.scale.fromArray(t.scale), t?.rotation && a.rotation.setFromVector3(new w(...t.rotation)), this.scene.add(a); const l = new Ic(a, o, a.uuid); this.models.set(o, l), i(l); }, (n) => { t?.onProgress && t.onProgress(n.loaded / n.total * 100); }, (n) => s(n) ); }); } unloadModel(e) { const t = this.models.get(e); t && t instanceof Ic && (this.scene.remove(t.object), this.models.delete(e)); } getAllModels() { return Array.from(this.models.values()); } getModel(e) { return this.models.get(e); } } class U_ { camera; controls; container; constructor(e, t, i) { this.container = e, this.camera = new Mt(75, t / i, 0.1, 1e3), this.camera.position.set(10, 10, 10), this.camera.lookAt(0, 0, 0), this.controls = new Ah(this.camera, this.container), this.controls.enableDamping = !0; } // Used by EngineKernel to update/render getCamera() { return this.camera; } update() { this.controls.update(); } updateAspect(e, t) { if (this.camera instanceof Mt) this.camera.aspect = e / t, this.camera.updateProjectionMatrix(); else if (this.camera instanceof mr) { const i = e / t, s = 20; this.camera.left = -s * i / 2, this.camera.right = s * i / 2, this.camera.top = s / 2, this.camera.bottom = -s / 2, this.camera.updateProjectionMatrix(); } } setView(e, t) { switch (e) { case zr.Top: this.camera.position.set(0, 20, 0); break; case zr.Front: this.camera.position.set(0, 0, 20); break; // ... handle others default: console.warn("View not fully implemented:", e); } this.camera.lookAt(0, 0, 0), this.controls.update(); } fitToView(e, t) { } goHome(e) { this.camera.position.set(10, 10, 10), this.camera.lookAt(0, 0, 0), this.controls.update(); } setProjection(e) { e === Nr.Perspective && !(this.camera instanceof Mt) || e === Nr.Orthographic && this.camera instanceof mr; } setNavigationMode(e) { e === An.Orbit ? (this.controls.enabled = !0, this.controls.enableRotate = !0) : e === An.PanOnly && (this.controls.enableRotate = !1); } getState() { const e = this.controls.target; return { position: this.camera.position.toArray(), target: e.toArray(), up: this.camera.up.toArray(), projection: this.camera instanceof Mt ? Nr.Perspective : Nr.Orthographic }; } restoreState(e, t) { this.camera.position.fromArray(e.position), this.camera.up.fromArray(e.up), this.controls.target.fromArray(e.target), this.controls.update(); } } class N_ { scene; selectedIds = /* @__PURE__ */ new Set(); // Store original materials for restore materialCache = /* @__PURE__ */ new Map(); constructor(e) { this.scene = e; } findObject(e) { let t; return this.scene.traverse((i) => { i.name === e && (t = i); }), t; } getSelection() { return Array.from(this.selectedIds); } select(e) { this.clearSelection(), this.addSelection(e); } addSelection(e) { e.forEach((t) => { this.selectedIds.add(t), this.findObject(t); }); } removeSelection(e) { e.forEach((t) => this.selectedIds.delete(t)); } clearSelection() { this.selectedIds.clear(); } getHiddenComponents() { const e = []; return this.scene.traverse((t) => { t.visible || e.push(t.name); }), e; } setVisibility(e, t) { e.forEach((i) => { const s = this.findObject(i); s && (s.visible = t); }); } isolate(e) { this.scene.traverse((t) => t.visible = !1), this.setVisibility(e, !0); } clearIsolation() { this.scene.traverse((e) => e.visible = !0); } setColor(e, t) { e.forEach((i) => { const s = this.findObject(i); if (s && s instanceof nt) { this.materialCache.has(i) || this.materialCache.set(i, s.material); const n = new Bt({ color: t }); s.material = n; } }); } restoreColor(e) { e.forEach((t) => { const i = this.findObject(t); i && this.materialCache.has(t) && (i.material = this.materialCache.get(t), this.materialCache.delete(t)); }); } setOpacity(e, t) { } restoreOpacity(e) { } clearAllOverrides() { this.materialCache.forEach((e, t) => { const i = this.findObject(t); i && i instanceof nt && (i.material = e); }), this.materialCache.clear(); } getBoundingBox(e) { const t = this.findObject(e); if (t) { const i = new Rt().setFromObject(t); return { min: i.min, max: i.max }; } return { min: { x: 0, y: 0, z: 0 }, max: { x: 0, y: 0, z: 0 } }; } } class O_ { // In a real implementation, this would connect to a backend or parse metadata from the loaded model (e.g. IFC/Revit data) async getProperties(e) { return [ { name: "Identity Data", properties: [ { name: "Element ID", value: e }, { name: "Name", value: "Sample Element" } ] } ]; } async getPropertyValue(e, t) { return "Unknown"; } async getModelTree(e) { return [ { id: "root", name: "Model Root", type: "Model", hasChildren: !0, children: [ { id: "l1", name: "Level 1", type: "Level", hasChildren: !1 } ] } ]; } async search(e) { return console.log("Searching for:", e), []; } } class B_ { scene; renderer; // State tracking _shadowsEnabled = !1; _aoEnabled = !1; _sectioningEnabled = !1; constructor(e, t) { this.scene = e, this.renderer = t; } setBackgroundColor(e) { this.scene.background = new _e(e); } setSkybox(e) { const t = new _h().load(e); this.scene.background = t; } enableShadows(e) { this._shadowsEnabled = e, this.renderer.shadowMap.enabled = e, this.scene.traverse((t) => { t instanceof nt && (t.castShadow = e, t.receiveShadow = e); }); } enableAntialiasing(e) { console.warn("Changing antialiasing at runtime requires recreating the WebGL context, which is complex. Ignored."); } enableAmbientOcclusion(e) { this._aoEnabled = e, console.log("AO enabled:", e, "(Requires PostProcessing pass - not implemented in this basic kernel)"); } addSectionPlane(e, t) { const i = new yi(new w(...e), t); return this.renderer.clippingPlanes.push(i), "plane-" + (this.renderer.clippingPlanes.length - 1); } removeSectionPlane(e) { this.renderer.clippingPlanes.pop(); } clearSectionPlanes() { this.renderer.clippingPlanes = []; } enableSectioning(e) { this._sectioningEnabled = e, this.renderer.localClippingEnabled = e; } captureScreen(e, t) { return this.renderer.domElement.toDataURL(); } getViewerConfig() { return { shadows: this._shadowsEnabled, ambientOcclusion: this._aoEnabled, sectioning: this._sectioningEnabled }; } getRenderStatistics() { const e = this.renderer.info; return { calls: e.render.calls, triangles: e.render.triangles, points: e.render.points, lines: e.render.lines, memory: { geometries: e.memory.geometries, textures: e.memory.textures } }; } } class F_ { activeTool = null; tools = /* @__PURE__ */ new Map(); activate(e, t) { console.log(`Activating tool: ${e}`, t), this.activeTool = e; } deactivate() { this.activeTool && (console.log(`Deactivating tool: ${this.activeTool}`), this.activeTool = null); } getActiveTool() { return this.activeTool; } registerTool(e, t) { this.tools.set(e, t); } } class z_ { listeners = /* @__PURE__ */ new Map(); on(e, t) { this.listeners.has(e) || this.listeners.set(e, []), this.listeners.get(e).push(t); } off(e, t) { if (!this.listeners.has(e)) return; const i = this.listeners.get(e), s = i.indexOf(t); s !== -1 && i.splice(s, 1); } trigger(e, t) { this.listeners.has(e) && this.listeners.get(e).forEach((i) => { try { i(t); } catch (s) { console.error(`Error in event listener for ${e}:`, s); } }); } } class Uc { loader; cameraTool; components; data; viewer; tools; events; viewCube; container; scene; renderer; // Internal modules (typed as concrete classes if needed internally, but exposed as interfaces) _cameraModule; animationId = null; constructor(e) { const t = document.getElementById(e.containerId); if (!t) throw new Error(`Container ${e.containerId} not found`); this.container = t, this.scene = new zo(), this.renderer = new Rn({ antialias: e.antialias ?? !0, alpha: !0 }), this.renderer.setPixelRatio(window.devicePixelRatio), this.container.appendChild(this.renderer.domElement), this.events = new z_(), this._cameraModule = new U_(this.container, this.container.clientWidth, this.container.clientHeight), this.cameraTool = this._cameraModule, this.loader = new I_(this.scene), this.components = new N_(this.scene), this.data = new O_(), this.viewer = new B_(this.scene, this.renderer), this.tools = new F_(), this.viewCube = { show: () => console.warn("[V2] ViewCube not implemented"), hide: () => { }, setDirection: () => { }, goHome: () => { }, isVisible: () => !1, updateOptions: () => { } }, this.resize(), this.setupResizeObserver(), this.animate(); } getVersion() { return "2.0.0"; } resize() { const e = this.container.clientWidth, t = this.container.clientHeight; this.renderer.setSize(e, t), this._cameraModule.updateAspect(e, t); } dispose() { this.animationId && cancelAnimationFrame(this.animationId), this.renderer.dispose(), this.container.innerHTML = ""; } setupResizeObserver() { new ResizeObserver(() => { this.resize(); }).observe(this.container); } animate = () => { this.animationId = requestAnimationFrame(this.animate), this._cameraModule.update(), this.renderer.render(this.scene, this._cameraModule.getCamera()); }; } function k_(r) { const e = r.version || "v1"; switch (e) { case "v2": return new Uc(r); case "v1": return new L_(r); default: return console.warn(`Version '${e}' not found. Falling back to v2.`), new Uc(r); } } class H_ { /** 第三方 3D 引擎实例 */ engine = null; /** 引擎挂载的容器元素 */ container; /** 引擎容器 ID(用于传递给 createEngine) */ containerId; /** 引擎配置选项(不包含 container) */ options; /** 是否已初始化 */ _isInitialized = !1; /** 是否已销毁 */ _isDestroyed = !1; /** 主题订阅取消函数 */ unsubscribeTheme = null; /** * 构造函数 * @param options 3D 引擎配置选项 */ constructor(e) { this.container = e.container, this.container.id ? this.containerId = this.container.id : (this.containerId = `engine-container-${Date.now()}-${Math.random().toString(36).substr(2, 9)}`, this.container.id = this.containerId), this.options = { backgroundColor: e.backgroundColor ?? 1710618, // 默认深色背景 version: e.version ?? "v1", // 默认使用 v1 版本 showStats: e.showStats ?? !1, // 默认不显示统计 showViewCube: e.showViewCube ?? !0 // 默认显示视图立方体 }; } /** * 初始化组件 (接口实现) * 创建 div 容器并初始化引擎 */ init() { if (this._isInitialized) { console.warn("[Engine] Engine already initialized."); return; } if (this._isDestroyed) { console.error("[Engine] Cannot initialize destroyed engine."); return; } try { const e = { containerId: this.containerId, backgroundColor: this.options.backgroundColor, version: this.options.version, showStats: this.options.showStats, showViewCube: this.options.showViewCube }; if (this.engine = k_(e), !this.engine) throw new Error("Failed to create engine instance"); this._isInitialized = !0, this.unsubscribeTheme = oi.subscribe((t) => { this.setTheme(t); }), this.setTheme(oi.getTheme()); } catch (e) { throw console.error("[Engine] Failed to initialize engine:", e), this._isInitialized = !1, e; } } /** * 设置主题 (接口实现) * 根据主题调整 3D 引擎的视觉效果(如背景色) * @param theme 全局主题配置 */ setTheme(e) { if (!this._isInitialized || !this.engine) return; let t; e.name === "dark" ? t = 1710618 : e.name === "light" ? t = 16119285 : t = this.options.backgroundColor ?? 1710618, this.engine && typeof this.engine.setBackgroundColor == "function" ? this.engine.setBackgroundColor(t) : this.engine && this.engine.scene && this.engine.scene.background && this.engine.scene.background.setHex(t); } /** * 设置语言 (接口实现) */ setLocales() { } /** * 检查是否已初始化 */ isInitialized() { return this._isInitialized; } /** * 加载 3D 模型 * @param url 模型文件 URL * @param options 加载选项(位置、旋转、缩放) */ loadModel(e, t) { if (!this._isInitialized || !this.engine) { console.error("[Engine] Engine not initialized. Please call init() first."); return; } if (!e) { console.error("[Engine] Model URL is required."); return; } this.engine.loader.loadModel(e, t); } /** * 获取原始 3D 引擎实例 */ getEngine() { return this.engine; } /** * 销毁组件 (接口实现) * 清理资源、取消订阅、销毁引擎实例 */ destroy() { this._isDestroyed || (this.unsubscribeTheme && (this.unsubscribeTheme(), this.unsubscribeTheme = null), this.container.innerHTML = "", this._isDestroyed = !0, this._isInitialized = !1); } } class V_ { /** 3D 引擎挂载的父容器 */ container; /** 3D 引擎组件实例 */ engine = null; /** * 构造函数 * @param container 3D 引擎挂载的目标容器 */ constructor(e) { this.container = e; } /** * 初始化 3D 引擎 * @param options 引擎配置选项(可选,如果不提供则使用默认配置) * @returns 是否初始化成功 */ initialize(e) { this.engine && this.engine.isInitialized() && (console.warn("[EngineManager] 3D Engine already initialized. Destroying old instance..."), this.engine.destroy(), this.engine = null); try { return this.engine = new H_({ container: this.container, ...e // 合并配置选项 }), this.engine.init(), this.engine.isInitialized(); } catch (t) { return console.error("[EngineManager] Failed to initialize 3D engine:", t), this.engine = null, !1; } } /** * 检查 3D 引擎是否已初始化 */ isInitialized() { return this.engine !== null && this.engine.isInitialized(); } /** * 加载 3D 模型 * @param url 模型文件 URL * @param options 加载选项(位置、旋转、缩放) */ loadModel(e, t) { if (!this.engine || !this.engine.isInitialized()) { console.error("[EngineManager] 3D Engine not initialized. Please call initialize() first."); return; } this.engine.loadModel(e, t); } /** * 获取原始 3D 引擎实例 * 用于直接调用第三方引擎的其他 API */ getEngine() { return this.engine ? this.engine.getEngine() : (console.warn("[EngineManager] 3D Engine not initialized."), null); } /** * 销毁 3D 引擎实例 */ destroy() { this.engine && (this.engine.destroy(), this.engine = null); } } class G_ { container; wrapper = null; topLeftGroup = null; // 保存左上角按钮组的引用 toolbar = null; // 底部专用 buttonGroup = null; // 通用 dialog = null; engine = null; // 3D 引擎管理器 get localeManager() { return dr; } get themeManager() { return oi; } constructor(e, t) { const i = typeof e == "string" ? document.getElementById(e) : e; if (!i) throw new Error("Container not found"); this.container = i, t?.locale && dr.setLocale(t.locale), t?.theme && (t.theme === "custom" ? console.warn("Custom theme should be set via setCustomTheme().") : oi.setTheme(t.theme)), this.init(); } setLocale(e) { dr.setLocale(e); } getLocale() { return dr.getLocale(); } setTheme(e) { oi.setTheme(e); } setCustomTheme(e) { oi.setCustomTheme(e); } init() { this.container.innerHTML = "", this.wrapper = document.createElement("div"), this.wrapper.className = "bim-engine-wrapper", this.container.appendChild(this.wrapper), this.engine = new V_(this.wrapper), this.dialog = new Zh(this.wrapper), this.toolbar = new qh(this.wrapper), this.buttonGroup = new Yh(this.wrapper), this.updateTheme(oi.getTheme()), this.topLeftGroup && this.topLeftGroup.setColors({ backgroundColor: "#ff00ff" }), oi.subscribe((e) => { this.updateTheme(e); }); } /** * 初始化 3D 引擎组件 * 注意:只初始化引擎,不加载模型。模型加载在使用层(如 demo.html)进行 * @param options 引擎配置选项(可选) */ initEngine(e) { return this.engine ? this.engine.initialize(e) : (console.error("[BimEngine] Engine manager not available."), !1); } updateTheme(e) { this.wrapper && (this.wrapper.style.backgroundColor = e.background, this.wrapper.style.color = e.textPrimary); } destroy() { this.toolbar?.destroy(), this.buttonGroup?.destroy(), this.engine?.destroy(), this.dialog = null, this.container.innerHTML = ""; } } export { Nc as BimButtonGroup, G_ as BimEngine, Xh as Toolbar, k_ as createEngine }; //# sourceMappingURL=bim-engine-sdk.es.js.map